rs-clob-client-v2 0.2.0

Rust client for Polymarket's CLOB v2 protocol (Central Limit Order Book)
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
use crate::client::ClobClient;
use crate::constants::{END_CURSOR, INITIAL_CURSOR};
use crate::endpoints::endpoints;
use crate::errors::{ClobError, ClobResult};
use crate::headers::create_l2_headers;
use crate::order_builder::{calculate_buy_market_price, calculate_sell_market_price};
use crate::types::*;
use rs_order_utils::v2::SignedOrder;
use std::collections::HashMap;

impl ClobClient {
    // ===================================
    // L1 Auth Methods
    // ===================================

    /// Creates a signed limit order
    ///
    /// # Arguments
    ///
    /// * `user_order` - Order parameters (token_id, price, size, side, etc.)
    /// * `options` - Optional CreateOrderOptions (tick_size, neg_risk)
    ///
    /// # Returns
    ///
    /// A JSON representation of the signed order ready for posting
    pub async fn create_limit_order(
        &self,
        user_limit_order: &UserLimitOrder,
        options: Option<CreateOrderOptions>,
    ) -> ClobResult<serde_json::Value> {
        self.can_l1_auth()?;

        let token_id = &user_limit_order.token_id;

        let tick_size = if let Some(opts) = &options {
            opts.tick_size
        } else {
            self.get_tick_size(token_id).await?
        };

        let neg_risk = if let Some(opts) = &options {
            opts.neg_risk.unwrap_or(false)
        } else {
            self.get_neg_risk(token_id).await?
        };

        let create_options = CreateOrderOptions {
            tick_size,
            neg_risk: Some(neg_risk),
        };

        let order_builder = self
            .order_builder
            .as_ref()
            .ok_or(ClobError::L1AuthUnavailable)?;

        let signed_order = order_builder
            .build_limit_order(user_limit_order, &create_options)
            .await?;
        self.signed_order_to_json(signed_order)
    }

    /// Creates a signed market order
    ///
    /// # Arguments
    ///
    /// * `user_market_order` - Market order parameters (token_id, amount, side, etc.)
    /// * `options` - Optional CreateOrderOptions (tick_size, neg_risk)
    ///
    /// # Returns
    ///
    /// A JSON representation of the signed order ready for posting
    pub async fn create_market_order(
        &self,
        user_market_order: &UserMarketOrder,
        options: Option<CreateOrderOptions>,
    ) -> ClobResult<serde_json::Value> {
        self.can_l1_auth()?;

        let token_id = &user_market_order.token_id;

        let tick_size = if let Some(opts) = &options {
            opts.tick_size
        } else {
            self.get_tick_size(token_id).await?
        };

        let neg_risk = if let Some(opts) = &options {
            opts.neg_risk.unwrap_or(false)
        } else {
            self.get_neg_risk(token_id).await?
        };

        let create_options = CreateOrderOptions {
            tick_size,
            neg_risk: Some(neg_risk),
        };

        let mut order = user_market_order.clone();

        // Calculate market price if not provided
        if order.price.is_none() {
            let price = self
                .calculate_market_price(
                    token_id,
                    order.side,
                    order.amount,
                    order.order_type.unwrap_or(OrderType::Fok),
                )
                .await?;
            order.price = Some(price);
        }

        let order_builder = self
            .order_builder
            .as_ref()
            .ok_or(ClobError::L1AuthUnavailable)?;

        let signed_order = order_builder
            .build_market_order(&order, &create_options)
            .await?;
        self.signed_order_to_json(signed_order)
    }

    // ===================================
    // L2 Auth Methods
    // ===================================

    /// Creates and posts a limit order in one call
    ///
    /// # Arguments
    ///
    /// * `user_order` - Order parameters, the size is in shares both for buy and sell
    /// * `options` - Optional CreateOrderOptions
    /// * `order_type` - GTC, FOK, FAK, or GTD
    /// 
    ///
    /// # Returns
    ///
    /// API response with order status
    pub async fn create_and_post_limit_order(
        &self,
        user_limit_order: &UserLimitOrder,
        options: Option<CreateOrderOptions>,
        order_type: OrderType,
    ) -> ClobResult<serde_json::Value> {
        let order = self.create_limit_order(user_limit_order, options).await?;
        self.post_order(order, order_type).await
    }

    /// Creates and posts a market order in one call
    ///
    /// # Arguments
    ///
    /// * `user_market_order` - Market order parameters
    /// * `options` - Optional CreateOrderOptions
    /// * `order_type` - Typically FOK or FAK
    ///
    /// # Returns
    ///
    /// API response with order status
    pub async fn create_and_post_market_order(
        &self,
        user_market_order: &UserMarketOrder,
        options: Option<CreateOrderOptions>,
        order_type: OrderType,
    ) -> ClobResult<serde_json::Value> {
        let order = self.create_market_order(user_market_order, options).await?;
        self.post_order(order, order_type).await
    }

    /// Gets all trade history with automatic pagination
    /// Note: The trades history only includes trades that have been executed, does not include limit orders
    pub async fn get_trades(&self, params: Option<TradeParams>) -> ClobResult<Vec<Trade>> {
        self.can_l2_auth()?;

        let mut results = Vec::new();
        let mut next_cursor = INITIAL_CURSOR.to_string();

        while next_cursor != END_CURSOR {
            let response = self
                .get_trades_paginated(params.clone(), Some(next_cursor.clone()))
                .await?;
            next_cursor = response.next_cursor;
            results.extend(response.data);
        }

        Ok(results)
    }

    /// Gets trades with pagination support
    pub async fn get_trades_paginated(
        &self,
        params: Option<TradeParams>,
        cursor: Option<String>,
    ) -> ClobResult<TradesPaginatedResponse> {
        self.can_l2_auth()?;

        let wallet = self.wallet.as_ref().ok_or(ClobError::L1AuthUnavailable)?;
        let creds = self.creds.as_ref().ok_or(ClobError::L2AuthNotAvailable)?;

        let endpoint_path = endpoints::GET_TRADES;
        let timestamp = if self.use_server_time {
            Some(self.get_server_time().await?)
        } else {
            None
        };

        let headers = create_l2_headers(wallet, creds, "GET", endpoint_path, None, timestamp)
            .await?
            .to_headers();

        let mut query_params = HashMap::new();

        // Add cursor
        query_params.insert(
            "next_cursor".to_string(),
            cursor.unwrap_or_else(|| INITIAL_CURSOR.to_string()),
        );

        // Add user params
        if let Some(p) = params {
            if let Some(id) = p.id {
                query_params.insert("id".to_string(), id);
            }
            if let Some(market) = p.market {
                query_params.insert("market".to_string(), market);
            }
            if let Some(asset_id) = p.asset_id {
                query_params.insert("asset_id".to_string(), asset_id);
            }
            if let Some(maker) = p.maker_address {
                query_params.insert("maker_address".to_string(), maker);
            }
            if let Some(before) = p.before {
                query_params.insert("before".to_string(), before.to_string());
            }
            if let Some(after) = p.after {
                query_params.insert("after".to_string(), after.to_string());
            }
        }

        self.http_client
            .get(endpoint_path, Some(headers), Some(query_params))
            .await
    }

    /// Gets an open order by ID
    pub async fn get_open_order(&self, order_id: &str) -> ClobResult<OpenOrder> {
        self.can_l2_auth()?;

        let wallet = self.wallet.as_ref().ok_or(ClobError::L1AuthUnavailable)?;
        let creds = self.creds.as_ref().ok_or(ClobError::L2AuthNotAvailable)?;

        let endpoint_path = format!("{}{}", endpoints::GET_ORDER, order_id);
        let timestamp = if self.use_server_time {
            Some(self.get_server_time().await?)
        } else {
            None
        };

        let headers = create_l2_headers(wallet, creds, "GET", &endpoint_path, None, timestamp)
            .await?
            .to_headers();

        self.http_client
            .get(&endpoint_path, Some(headers), None)
            .await
    }

    /// Gets open orders for the user
    pub async fn get_open_orders(
        &self,
        params: Option<OpenOrderParams>,
    ) -> ClobResult<OpenOrdersResponse> {
        self.can_l2_auth()?;

        let wallet = self.wallet.as_ref().ok_or(ClobError::L1AuthUnavailable)?;
        let creds = self.creds.as_ref().ok_or(ClobError::L2AuthNotAvailable)?;

        let endpoint_path = endpoints::GET_OPEN_ORDERS;
        let timestamp = if self.use_server_time {
            Some(self.get_server_time().await?)
        } else {
            None
        };

        let headers = create_l2_headers(wallet, creds, "GET", endpoint_path, None, timestamp)
            .await?
            .to_headers();

        let mut query_params = HashMap::new();

        if let Some(p) = params {
            if let Some(id) = p.id {
                query_params.insert("id".to_string(), id);
            }
            if let Some(market) = p.market {
                query_params.insert("market".to_string(), market);
            }
            if let Some(asset_id) = p.asset_id {
                query_params.insert("asset_id".to_string(), asset_id);
            }
        }

        self.http_client
            .get(
                endpoint_path,
                Some(headers),
                (!query_params.is_empty()).then_some(query_params),
            )
            .await
    }

    /// Posts an order to the exchange
    pub async fn post_order(
        &self,
        order: serde_json::Value,
        order_type: OrderType,
    ) -> ClobResult<serde_json::Value> {
        self.can_l2_auth()?;

        let wallet = self.wallet.as_ref().ok_or(ClobError::L1AuthUnavailable)?;
        let creds = self.creds.as_ref().ok_or(ClobError::L2AuthNotAvailable)?;

        // Prepare order payload
        let order_payload = self.order_to_json(order, order_type)?;
        let body = serde_json::to_string(&order_payload)?;

        // Create L2 headers with body
        let endpoint_path = endpoints::POST_ORDER;
        let timestamp = if self.use_server_time {
            Some(self.get_server_time().await?)
        } else {
            None
        };

        let headers =
            create_l2_headers(wallet, creds, "POST", endpoint_path, Some(&body), timestamp).await?;

        // Inject builder headers if available
        let final_headers = if self.can_builder_auth() {
            match self
                ._generate_builder_headers(headers.clone(), "POST", endpoint_path, Some(&body))
                .await?
            {
                Some(builder_headers) => builder_headers.to_headers(),
                None => headers.to_headers(),
            }
        } else {
            headers.to_headers()
        };

        // Make request
        self.http_client
            .post(
                endpoint_path,
                Some(final_headers),
                Some(order_payload),
                None,
            )
            .await
    }

    /// Posts multiple orders to the exchange
    pub async fn post_orders(&self, orders: Vec<PostOrdersArgs>) -> ClobResult<serde_json::Value> {
        self.can_l2_auth()?;

        let wallet = self.wallet.as_ref().ok_or(ClobError::L1AuthUnavailable)?;
        let creds = self.creds.as_ref().ok_or(ClobError::L2AuthNotAvailable)?;

        // Convert each order to payload format
        let owner = &creds.key;
        let payloads: Vec<_> = orders
            .iter()
            .map(|arg| {
                serde_json::json!({
                    "order": arg.order,
                    "owner": owner,
                    "orderType": arg.order_type,
                    "deferExec": false
                })
            })
            .collect();

        let body = serde_json::to_string(&payloads)?;

        let endpoint_path = endpoints::POST_ORDERS;
        let timestamp = if self.use_server_time {
            Some(self.get_server_time().await?)
        } else {
            None
        };

        let headers =
            create_l2_headers(wallet, creds, "POST", endpoint_path, Some(&body), timestamp).await?;

        // Inject builder headers if available
        let final_headers = if self.can_builder_auth() {
            match self
                ._generate_builder_headers(headers.clone(), "POST", endpoint_path, Some(&body))
                .await?
            {
                Some(builder_headers) => builder_headers.to_headers(),
                None => headers.to_headers(),
            }
        } else {
            headers.to_headers()
        };

        self.http_client
            .post(endpoint_path, Some(final_headers), Some(payloads), None)
            .await
    }

    /// Cancels a single order by ID
    pub async fn cancel_order(&self, order_id: &str) -> ClobResult<serde_json::Value> {
        self.can_l2_auth()?;

        let wallet = self.wallet.as_ref().ok_or(ClobError::L1AuthUnavailable)?;
        let creds = self.creds.as_ref().ok_or(ClobError::L2AuthNotAvailable)?;

        let payload = OrderPayload {
            order_id: order_id.to_string(),
        };
        let body = serde_json::to_string(&payload)?;

        let endpoint_path = endpoints::CANCEL_ORDER;
        let timestamp = if self.use_server_time {
            Some(self.get_server_time().await?)
        } else {
            None
        };

        let headers = create_l2_headers(
            wallet,
            creds,
            "DELETE",
            endpoint_path,
            Some(&body),
            timestamp,
        )
        .await?
        .to_headers();

        self.http_client
            .delete(endpoint_path, Some(headers), Some(payload), None)
            .await
    }

    /// Cancels multiple orders by IDs
    pub async fn cancel_orders(&self, order_ids: Vec<String>) -> ClobResult<serde_json::Value> {
        self.can_l2_auth()?;

        let wallet = self.wallet.as_ref().ok_or(ClobError::L1AuthUnavailable)?;
        let creds = self.creds.as_ref().ok_or(ClobError::L2AuthNotAvailable)?;

        #[derive(serde::Serialize)]
        struct CancelOrdersPayload {
            order_ids: Vec<String>,
        }

        let payload = CancelOrdersPayload { order_ids };
        let body = serde_json::to_string(&payload)?;

        let endpoint_path = endpoints::CANCEL_ORDERS;
        let timestamp = if self.use_server_time {
            Some(self.get_server_time().await?)
        } else {
            None
        };

        let headers = create_l2_headers(
            wallet,
            creds,
            "DELETE",
            endpoint_path,
            Some(&body),
            timestamp,
        )
        .await?
        .to_headers();

        self.http_client
            .delete(endpoint_path, Some(headers), Some(payload), None)
            .await
    }

    /// Cancels all open orders
    pub async fn cancel_all(&self) -> ClobResult<serde_json::Value> {
        self.can_l2_auth()?;

        let wallet = self.wallet.as_ref().ok_or(ClobError::L1AuthUnavailable)?;
        let creds = self.creds.as_ref().ok_or(ClobError::L2AuthNotAvailable)?;

        let endpoint_path = endpoints::CANCEL_ALL;
        let timestamp = if self.use_server_time {
            Some(self.get_server_time().await?)
        } else {
            None
        };

        let headers = create_l2_headers(wallet, creds, "DELETE", endpoint_path, None, timestamp)
            .await?
            .to_headers();

        self.http_client
            .delete(endpoint_path, Some(headers), None::<()>, None)
            .await
    }

    /// Cancels orders for a specific market or asset
    pub async fn cancel_market_orders(
        &self,
        params: OrderMarketCancelParams,
    ) -> ClobResult<serde_json::Value> {
        self.can_l2_auth()?;

        let wallet = self.wallet.as_ref().ok_or(ClobError::L1AuthUnavailable)?;
        let creds = self.creds.as_ref().ok_or(ClobError::L2AuthNotAvailable)?;

        let body = serde_json::to_string(&params)?;

        let endpoint_path = endpoints::CANCEL_MARKET_ORDERS;
        let timestamp = if self.use_server_time {
            Some(self.get_server_time().await?)
        } else {
            None
        };

        let headers = create_l2_headers(
            wallet,
            creds,
            "DELETE",
            endpoint_path,
            Some(&body),
            timestamp,
        )
        .await?
        .to_headers();

        self.http_client
            .delete(endpoint_path, Some(headers), Some(params), None)
            .await
    }

    // ===================================
    // Builder Auth Methods (Trades)
    // ===================================

    /// Gets builder trades with pagination
    pub async fn get_builder_trades(
        &self,
        params: Option<TradeParams>,
        cursor: Option<String>,
    ) -> ClobResult<BuilderTradesResponse> {
        self.must_builder_auth()?;

        let endpoint_path = endpoints::GET_BUILDER_TRADES;

        // Get builder headers (already a HashMap)
        let headers = self
            ._get_builder_headers("GET", endpoint_path, None)
            .await?;

        let mut query_params = HashMap::new();

        // Add cursor
        query_params.insert(
            "next_cursor".to_string(),
            cursor.unwrap_or_else(|| INITIAL_CURSOR.to_string()),
        );

        // Add user params
        if let Some(p) = params {
            if let Some(id) = p.id {
                query_params.insert("id".to_string(), id);
            }
            if let Some(market) = p.market {
                query_params.insert("market".to_string(), market);
            }
            if let Some(asset_id) = p.asset_id {
                query_params.insert("asset_id".to_string(), asset_id);
            }
        }

        self.http_client
            .get(endpoint_path, Some(headers), Some(query_params))
            .await
    }

    // ===================================
    // Public Method (Market Price Calculation)
    // ===================================

    /// Calculates market execution price from orderbook
    ///
    /// # Arguments
    ///
    /// * `token_id` - Token ID to calculate price for
    /// * `side` - Buy or Sell
    /// * `amount` - Amount in USDC (for Buy) or tokens (for Sell)
    /// * `order_type` - FOK or FAK
    ///
    /// # Returns
    ///
    /// Calculated execution price with buffer
    pub async fn calculate_market_price(
        &self,
        token_id: &str,
        side: Side,
        amount: f64,
        order_type: OrderType,
    ) -> ClobResult<f64> {
        let orderbook = self.get_order_book(token_id).await?;
        match side {
            Side::Buy => {
                if orderbook.asks.is_empty() {
                    return Err(ClobError::NoMatch);
                }
                calculate_buy_market_price(&orderbook.asks, amount, order_type)
            }
            Side::Sell => {
                if orderbook.bids.is_empty() {
                    return Err(ClobError::NoMatch);
                }
                calculate_sell_market_price(&orderbook.bids, amount, order_type)
            }
        }
    }

    // ===================================
    // Private Helper Methods
    // ===================================

    /// Converts order to JSON payload for API submission
    fn order_to_json(
        &self,
        order: serde_json::Value,
        order_type: OrderType,
    ) -> ClobResult<serde_json::Value> {
        let owner = self
            .creds
            .as_ref()
            .ok_or(ClobError::L2AuthNotAvailable)?
            .key
            .clone();

        // Wrap the order in the expected payload format
        Ok(serde_json::json!({
            "order": order,
            "owner": owner,
            "orderType": order_type,
        }))
    }

    fn signed_order_to_json(&self, signed_order: SignedOrder) -> ClobResult<serde_json::Value> {
        serde_json::to_value(&signed_order).map_err(ClobError::JsonError)
    }

    // Pre-migration orders (L2 Authentication)

    /// Auto-paginates all pre-migration (V1) orders for the authenticated user.
    pub async fn get_pre_migration_orders(&self) -> ClobResult<Vec<OpenOrder>> {
        self.can_l2_auth()?;

        let mut results = Vec::new();
        let mut next_cursor = INITIAL_CURSOR.to_string();

        while next_cursor != END_CURSOR {
            let page = self
                .get_pre_migration_orders_paginated(Some(next_cursor))
                .await?;
            results.extend(page.data);
            next_cursor = page.next_cursor;
        }

        Ok(results)
    }

    /// Fetches a single page of pre-migration orders starting at `cursor`.
    pub async fn get_pre_migration_orders_paginated(
        &self,
        cursor: Option<String>,
    ) -> ClobResult<PreMigrationOrdersPaginatedResponse> {
        self.can_l2_auth()?;

        let wallet = self.wallet.as_ref().ok_or(ClobError::L1AuthUnavailable)?;
        let creds = self.creds.as_ref().ok_or(ClobError::L2AuthNotAvailable)?;

        let endpoint_path = endpoints::GET_PRE_MIGRATION_ORDERS;
        let timestamp = if self.use_server_time {
            Some(self.get_server_time().await?)
        } else {
            None
        };

        let headers = create_l2_headers(wallet, creds, "GET", endpoint_path, None, timestamp)
            .await?
            .to_headers();

        let mut query_params = HashMap::new();
        query_params.insert(
            "next_cursor".to_string(),
            cursor.unwrap_or_else(|| INITIAL_CURSOR.to_string()),
        );

        self.http_client
            .get(endpoint_path, Some(headers), Some(query_params))
            .await
    }
}