polyoxide-clob 0.18.2

Rust client library for Polymarket CLOB (order book) API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
//! Live integration tests against the Polymarket CLOB API.
//!
//! These tests hit the real API and require network access.
//! They are gated behind `#[ignore]` so they don't run in CI.
//!
//! Run manually with:
//! ```sh
//! cargo test -p polyoxide-clob --test live_api -- --ignored
//! ```

use polyoxide_clob::{
    Account, Clob, ClobBuilder, CreateOrderParams, OrderKind, OrderSide, SignatureType,
};
use polyoxide_core::QueryBuilder;
use polyoxide_gamma::Gamma;
use std::time::Duration;

fn public_client() -> Clob {
    Clob::public()
}

fn authenticated_client() -> Clob {
    dotenvy::dotenv().ok();
    let account =
        Account::from_env().expect("POLYMARKET_* env vars required for authenticated tests");
    // The test account is a Polymarket proxy wallet, so authenticated read
    // endpoints (balances, notifications, rewards) need the POLY_PROXY signature
    // type to resolve the correct on-chain address.
    ClobBuilder::new()
        .with_account(account)
        .signature_type(SignatureType::PolyProxy)
        .build()
        .expect("authenticated clob client")
}

fn authenticated_address() -> String {
    dotenvy::dotenv().ok();
    let account =
        Account::from_env().expect("POLYMARKET_* env vars required for authenticated tests");
    format!("{:#x}", account.address())
}

/// Find a token_id with an active order book using Gamma.
///
/// The CLOB `/markets` listing returns mostly resolved markets. Gamma's
/// `closed=false` filter reliably returns markets with live order books.
async fn find_active_token_id() -> String {
    let gamma = Gamma::builder().build().expect("gamma client");
    let markets = gamma
        .markets()
        .list()
        .closed(false)
        .send()
        .await
        .expect("gamma list markets");

    markets
        .iter()
        .find_map(|m| {
            // clob_token_ids is a JSON-encoded array string: '["id1", "id2"]'
            m.clob_token_ids.as_ref().and_then(|ids| {
                serde_json::from_str::<Vec<String>>(ids)
                    .ok()
                    .and_then(|v| v.into_iter().next())
            })
        })
        .expect("should find at least one active market with a token_id via Gamma")
}

// ── Health ───────────────────────────────────────────────────────

#[tokio::test]
#[ignore]
async fn live_ping() {
    let client = public_client();
    let latency = client.health().ping().await.expect("ping should succeed");
    assert!(
        latency < Duration::from_secs(10),
        "latency too high: {:?}",
        latency
    );
}

// ── Markets ──────────────────────────────────────────────────────

#[tokio::test]
#[ignore]
async fn live_list_markets() {
    let client = public_client();
    let resp = client.markets().list().send().await.expect("list markets");
    assert!(!resp.data.is_empty(), "should return at least one market");
}

#[tokio::test]
#[ignore]
async fn live_simplified_markets() {
    let client = public_client();
    let resp = client
        .markets()
        .simplified()
        .send()
        .await
        .expect("simplified markets");
    assert!(
        !resp.data.is_empty(),
        "should return at least one simplified market"
    );
}

#[tokio::test]
#[ignore]
async fn live_sampling_markets() {
    let client = public_client();
    let _resp = client
        .markets()
        .sampling()
        .send()
        .await
        .expect("sampling markets should deserialize");
}

#[tokio::test]
#[ignore]
async fn live_sampling_simplified_markets() {
    let client = public_client();
    let _resp = client
        .markets()
        .sampling_simplified()
        .send()
        .await
        .expect("sampling simplified markets should deserialize");
}

#[tokio::test]
#[ignore]
async fn live_fee_rate() {
    let token_id = find_active_token_id().await;
    let client = public_client();

    let resp = client
        .markets()
        .fee_rate(&token_id)
        .send()
        .await
        .expect("fee_rate should deserialize");

    assert!(
        resp.base_fee <= 10_000,
        "fee rate {} bps seems unreasonably high",
        resp.base_fee
    );
}

#[tokio::test]
#[ignore]
async fn live_midpoint() {
    let token_id = find_active_token_id().await;
    let client = public_client();

    let resp = client
        .markets()
        .midpoint(&token_id)
        .send()
        .await
        .expect("midpoint should succeed");

    let mid: f64 = resp.mid.parse().expect("mid should be a number");
    assert!(
        (0.0..=1.0).contains(&mid),
        "midpoint {mid} should be between 0 and 1"
    );
}

#[tokio::test]
#[ignore]
async fn live_order_book() {
    let token_id = find_active_token_id().await;
    let client = public_client();

    let book = client
        .markets()
        .order_book(&token_id)
        .send()
        .await
        .expect("order book should succeed");

    assert!(
        !book.bids.is_empty() || !book.asks.is_empty(),
        "order book should have at least some levels"
    );
}

#[tokio::test]
#[ignore]
async fn live_price() {
    let token_id = find_active_token_id().await;
    let client = public_client();

    let resp = client
        .markets()
        .price(&token_id, OrderSide::Buy)
        .send()
        .await
        .expect("price should succeed");

    let price: f64 = resp.price.parse().expect("price should be a number");
    assert!(
        (0.0..=1.0).contains(&price),
        "price {price} should be between 0 and 1"
    );
}

#[tokio::test]
#[ignore]
async fn live_prices_history() {
    let token_id = find_active_token_id().await;
    let client = public_client();

    let resp = client
        .markets()
        .prices_history(&token_id)
        .query("interval", "max")
        .send()
        .await
        .expect("prices_history should succeed");

    assert!(
        !resp.history.is_empty(),
        "prices history should be non-empty"
    );
}

#[tokio::test]
#[ignore]
async fn live_neg_risk() {
    let token_id = find_active_token_id().await;
    let client = public_client();

    let _resp = client
        .markets()
        .neg_risk(&token_id)
        .send()
        .await
        .expect("neg_risk should deserialize");
}

#[tokio::test]
#[ignore]
async fn live_tick_size() {
    let token_id = find_active_token_id().await;
    let client = public_client();

    let resp = client
        .markets()
        .tick_size(&token_id)
        .send()
        .await
        .expect("tick_size should succeed");

    let tick: f64 = resp
        .minimum_tick_size
        .parse()
        .expect("minimum_tick_size should be a number");
    assert!(tick > 0.0, "tick size {tick} should be positive");
}

#[tokio::test]
#[ignore]
async fn live_get_market() {
    let client = public_client();

    // Get a condition_id from the market list
    let list = client.markets().list().send().await.expect("list markets");
    let condition_id = &list
        .data
        .first()
        .expect("should have at least one market")
        .condition_id;

    let market = client
        .markets()
        .get(condition_id)
        .send()
        .await
        .expect("get market should succeed");

    assert_eq!(
        &market.condition_id, condition_id,
        "returned market should match requested condition_id"
    );
}

#[tokio::test]
#[ignore]
async fn live_get_markets_by_token_ids() {
    let token_id = find_active_token_id().await;
    let client = public_client();

    let resp = client
        .markets()
        .get_by_token_ids(vec![token_id.clone()])
        .send()
        .await
        .expect("get_by_token_ids should succeed");

    assert!(
        !resp.data.is_empty(),
        "should return at least one market for the given token_id"
    );
}

// ── Path-parameter variants (OpenAPI parity) ────────────────────

#[tokio::test]
#[ignore]
async fn live_fee_rate_path() {
    let token_id = find_active_token_id().await;
    let client = public_client();

    let resp = client
        .markets()
        .fee_rate_path(&token_id)
        .send()
        .await
        .expect("fee_rate_path should deserialize");

    assert!(
        resp.base_fee <= 10_000,
        "fee rate {} bps seems unreasonably high",
        resp.base_fee
    );
}

#[tokio::test]
#[ignore]
async fn live_tick_size_path() {
    let token_id = find_active_token_id().await;
    let client = public_client();

    let resp = client
        .markets()
        .tick_size_path(&token_id)
        .send()
        .await
        .expect("tick_size_path should deserialize");

    let tick: f64 = resp
        .minimum_tick_size
        .parse()
        .expect("minimum_tick_size should parse");
    assert!(tick > 0.0, "tick size {tick} should be positive");
}

#[tokio::test]
#[ignore]
async fn live_neg_risk_path() {
    let token_id = find_active_token_id().await;
    let client = public_client();

    let _resp = client
        .markets()
        .neg_risk_path(&token_id)
        .send()
        .await
        .expect("neg_risk_path should deserialize");
}

#[tokio::test]
#[ignore]
async fn live_clob_market_details() {
    let client = public_client();
    let list = client.markets().list().send().await.expect("list markets");
    let condition_id = &list
        .data
        .first()
        .expect("should have at least one market")
        .condition_id;

    let _details = client
        .markets()
        .clob_market_details(condition_id)
        .send()
        .await
        .expect("clob_market_details should deserialize");
}

#[tokio::test]
#[ignore]
async fn live_market_by_token() {
    let token_id = find_active_token_id().await;
    let client = public_client();

    let resp = client
        .markets()
        .market_by_token(&token_id)
        .send()
        .await
        .expect("market_by_token should deserialize");

    assert!(
        !resp.condition_id.is_empty(),
        "condition_id should be non-empty"
    );
    assert!(
        !resp.primary_token_id.is_empty() || !resp.secondary_token_id.is_empty(),
        "should have at least one token id"
    );
}

#[tokio::test]
#[ignore]
async fn live_live_activity_market() {
    let client = public_client();
    let list = client.markets().list().send().await.expect("list markets");
    let condition_id = &list
        .data
        .first()
        .expect("should have at least one market")
        .condition_id;

    let _resp = client
        .markets()
        .live_activity_market(condition_id)
        .send()
        .await
        .expect("live_activity_market should deserialize");
}

#[tokio::test]
#[ignore]
async fn live_live_activity_bulk() {
    let client = public_client();
    let list = client.markets().list().send().await.expect("list markets");
    let ids: Vec<String> = list
        .data
        .iter()
        .take(2)
        .map(|m| m.condition_id.clone())
        .collect();
    if ids.is_empty() {
        return;
    }

    let _resp = client
        .markets()
        .live_activity_bulk(ids)
        .expect("body construction")
        .send()
        .await
        .expect("live_activity_bulk should deserialize");
}

#[tokio::test]
#[ignore]
async fn live_batch_prices_history() {
    let token_id = find_active_token_id().await;
    let client = public_client();

    let req = polyoxide_clob::BatchPricesHistoryRequest {
        markets: vec![token_id],
        interval: Some("1d".into()),
        ..Default::default()
    };

    let _resp = client
        .markets()
        .batch_prices_history(&req)
        .expect("body construction")
        .send()
        .await
        .expect("batch_prices_history should deserialize");
}

// ── Health: server time ─────────────────────────────────────────

#[tokio::test]
#[ignore]
async fn live_server_time() {
    let client = public_client();
    let resp = client
        .health()
        .server_time()
        .send()
        .await
        .expect("server_time should succeed");

    assert!(
        resp.time > 0,
        "server time {} should be positive",
        resp.time
    );
}

// ── Markets: spread ────────────────────────────────────────────

#[tokio::test]
#[ignore]
async fn live_spread() {
    let token_id = find_active_token_id().await;
    let client = public_client();

    let resp = client
        .markets()
        .spread(&token_id)
        .send()
        .await
        .expect("spread should succeed");

    let spread: f64 = resp.spread.parse().expect("spread should be a number");
    assert!(spread >= 0.0, "spread {spread} should be non-negative");
}

// ── Markets: last trade price ──────────────────────────────────

#[tokio::test]
#[ignore]
async fn live_last_trade_price() {
    let token_id = find_active_token_id().await;
    let client = public_client();

    let resp = client
        .markets()
        .last_trade_price(&token_id)
        .send()
        .await
        .expect("last_trade_price should succeed");

    let price_str = resp
        .price
        .or(resp.last_trade_price)
        .expect("response should have price or last_trade_price");
    let price: f64 = price_str.parse().expect("price should be a number");
    assert!(
        (0.0..=1.0).contains(&price),
        "last trade price {price} should be between 0 and 1"
    );
}

// ── Authenticated: Account ──────────────────────────────────────

#[tokio::test]
#[ignore]
async fn live_usdc_balance() {
    let client = authenticated_client();
    let resp = client
        .account_api()
        .expect("account_api")
        .usdc_balance()
        .send()
        .await
        .expect("usdc_balance should deserialize");

    let balance: f64 = resp.balance.parse().expect("balance should be a number");
    assert!(balance >= 0.0, "balance {balance} should be non-negative");
}

#[tokio::test]
#[ignore]
async fn live_balance_allowance() {
    let token_id = find_active_token_id().await;
    let client = authenticated_client();
    let _resp = client
        .account_api()
        .expect("account_api")
        .balance_allowance(&token_id)
        .send()
        .await
        .expect("balance_allowance should deserialize");
}

#[tokio::test]
#[ignore]
async fn live_update_balance_allowance() {
    let client = authenticated_client();
    let _resp = client
        .account_api()
        .expect("account_api")
        .update_balance_allowance("COLLATERAL", None, None)
        .await
        .expect("update_balance_allowance should succeed");
}

#[tokio::test]
#[ignore]
async fn live_list_trades() {
    let client = authenticated_client();
    let maker = authenticated_address();
    let _trades = client
        .account_api()
        .expect("account_api")
        .trades(maker)
        .send()
        .await
        .expect("trades should deserialize");
}

#[tokio::test]
#[ignore]
async fn live_list_trades_with_filter() {
    let client = authenticated_client();
    let maker = authenticated_address();
    let _trades = client
        .account_api()
        .expect("account_api")
        .trades(maker)
        .after("0")
        .send()
        .await
        .expect("trades with after filter should deserialize");
}

/// ── Authenticated: Account — builder trades ────────────────────

#[tokio::test]
#[ignore]
async fn live_builder_trades() {
    dotenvy::dotenv().ok();
    // `builder_code` is required by the endpoint and is account-specific, so it
    // lives in the environment rather than being hard-coded. Skip when absent
    // so a non-builder account doesn't see a spurious failure.
    let Ok(builder_code) = std::env::var("POLYMARKET_BUILDER_CODE") else {
        eprintln!("skipping live_builder_trades: POLYMARKET_BUILDER_CODE not set");
        return;
    };

    let client = authenticated_client();
    let _trades = client
        .account_api()
        .expect("account_api")
        .builder_trades(builder_code)
        .send()
        .await
        .expect("builder_trades should deserialize");
}

// ── Authenticated: Account — heartbeat ──────────────────────────

#[tokio::test]
#[ignore]
async fn live_heartbeat() {
    let client = authenticated_client();
    let _resp = client
        .account_api()
        .expect("account_api")
        .heartbeat()
        .await
        .expect("heartbeat should succeed");
}

// ── Authenticated: Notifications ────────────────────────────────

#[tokio::test]
#[ignore]
async fn live_list_notifications() {
    let client = authenticated_client();
    let _notifications = client
        .notifications()
        .expect("notifications")
        .list()
        .send()
        .await
        .expect("list notifications should deserialize");
}

// ── Authenticated: Auth — ban status ────────────────────────────

#[tokio::test]
#[ignore]
async fn live_closed_only_status() {
    let client = authenticated_client();
    let _resp = client
        .auth()
        .expect("auth")
        .closed_only_status()
        .send()
        .await
        .expect("closed_only_status should deserialize");
}

// ── Authenticated: Rewards ─────────────────────────────────────

#[tokio::test]
#[ignore]
async fn live_reward_earnings() {
    let client = authenticated_client();
    let _resp = client
        .rewards()
        .expect("rewards")
        .earnings("2024-01-01")
        .send()
        .await
        .expect("earnings should deserialize");
}

#[tokio::test]
#[ignore]
async fn live_reward_total_earnings() {
    let client = authenticated_client();
    let _resp = client
        .rewards()
        .expect("rewards")
        .total_earnings("2024-01-01")
        .send()
        .await
        .expect("total_earnings should deserialize");
}

#[tokio::test]
#[ignore]
async fn live_reward_percentages() {
    let client = authenticated_client();
    let _resp = client
        .rewards()
        .expect("rewards")
        .percentages()
        .send()
        .await
        .expect("percentages should deserialize");
}

#[tokio::test]
#[ignore]
async fn live_reward_market_earnings() {
    let client = authenticated_client();
    let _resp = client
        .rewards()
        .expect("rewards")
        .market_earnings()
        .send()
        .await
        .expect("market_earnings should deserialize");
}

#[tokio::test]
#[ignore]
async fn live_reward_current_markets() {
    let client = authenticated_client();
    let _resp = client
        .rewards()
        .expect("rewards")
        .current_markets()
        .send()
        .await
        .expect("current_markets should deserialize");
}

// ── Authenticated: Orders ───────────────────────────────────────

#[tokio::test]
#[ignore]
async fn live_list_open_orders() {
    let client = authenticated_client();
    let _orders = client
        .orders()
        .expect("orders")
        .list()
        .send()
        .await
        .expect("list open orders should deserialize");
}

// ── Authenticated: Orders — V2 re-validation (places a real-money order) ──

/// End-to-end re-validation that the CLOB **V2** order shape is accepted by the
/// live exchange: build → sign → post a small GTC buy at the best ask, then
/// cancel it. Places a real (small) order, so it is gated behind `#[ignore]`
/// and a funded proxy account; never runs in CI.
#[tokio::test]
#[ignore] // live; run with `-- --ignored`, needs funded proxy account
async fn live_v2_place_and_cancel() {
    let clob = authenticated_client();
    let token_id = find_active_token_id().await;
    let book = clob.markets().order_book(&token_id).send().await.unwrap();
    let ask = book.asks.iter().map(|l| l.price).min().expect("asks");
    let price: f64 = ask.to_string().parse().unwrap();
    let params = CreateOrderParams {
        token_id,
        price,
        size: 5.0,
        side: OrderSide::Buy,
        order_type: OrderKind::Gtc,
        post_only: false,
        expiration: None,
        funder: None,
        signature_type: Some(SignatureType::PolyProxy),
    };
    let order = clob.create_order(&params, None).await.unwrap();
    let signed = clob.sign_order(&order).await.unwrap();
    let resp = clob
        .post_order(&signed, OrderKind::Gtc, false)
        .await
        .unwrap();
    assert!(resp.success, "V2 order rejected: {:?}", resp.error_msg);
    if let Some(id) = resp.order_id {
        let _ = clob.orders().unwrap().cancel(id).send().await;
    }
}