nautilus-polymarket 0.61.0

Polymarket integration adapter for the Nautilus trading engine
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
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Provides the HTTP client for the Polymarket CLOB REST API.

use std::{collections::HashMap, result::Result as StdResult, str::from_utf8, sync::Arc};

use nautilus_core::{
    consts::NAUTILUS_USER_AGENT,
    time::{AtomicTime, get_atomic_clock_realtime},
};
use nautilus_model::{
    data::BookOrder,
    enums::{BookType, OrderSide},
    identifiers::InstrumentId,
    orderbook::OrderBook,
};
use nautilus_network::{
    http::{HttpClient, HttpClientError, Method, USER_AGENT},
    websocket::proxy::ProxyUrl,
};
use serde::{Deserialize, Serialize, de::DeserializeOwned};

use crate::{
    common::{credential::Credential, enums::PolymarketOrderType, urls::clob_http_url},
    http::{
        error::{Error, Result},
        models::{
            ClobBookResponse, ClobMarketResponse, FeeRateResponse, PolymarketOpenOrder,
            PolymarketOrder, PolymarketTradeReport, TickSizeResponse,
        },
        query::{
            BalanceAllowance, BatchCancelResponse, CancelMarketOrdersParams, CancelResponse,
            GetBalanceAllowanceParams, GetOrdersParams, GetTradesParams, OrderResponse,
            PaginatedResponse,
        },
        rate_limits::{PolymarketRateLimiter, RateLimitHeaders, TradingBucket},
    },
    websocket::parse::{parse_price, parse_quantity},
};

const CURSOR_START: &str = "MA==";
const CURSOR_END: &str = "LTE=";

const PATH_ORDERS: &str = "/data/orders";
const PATH_TRADES: &str = "/data/trades";
const PATH_BALANCE_ALLOWANCE: &str = "/balance-allowance";
const PATH_BALANCE_ALLOWANCE_UPDATE: &str = "/balance-allowance/update";
const PATH_POST_ORDER: &str = "/order";
const PATH_POST_ORDERS: &str = "/orders";
const PATH_CANCEL_ALL: &str = "/cancel-all";
const PATH_CANCEL_MARKET_ORDERS: &str = "/cancel-market-orders";
const PATH_HEARTBEATS: &str = "/heartbeats";

const CLOB_CANCEL_BATCH_LIMIT: usize = 1_000;

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct PostOrderBody<'a> {
    order: &'a PolymarketOrder,
    owner: &'a str,
    order_type: PolymarketOrderType,
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    post_only: bool,
}

#[derive(Serialize)]
struct CancelOrderBody<'a> {
    #[serde(rename = "orderID")]
    order_id: &'a str,
}

#[derive(Serialize)]
struct HeartbeatRequest<'a> {
    heartbeat_id: &'a str,
}

#[derive(Deserialize)]
struct HeartbeatWireResponse {
    heartbeat_id: Option<String>,
    status: Option<String>,
}

/// Outcome from an authenticated CLOB order-safety heartbeat.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum HeartbeatResponse {
    /// The heartbeat was acknowledged, with an optional next ID for chaining.
    Acknowledged(Option<String>),
    /// The supplied ID was stale and the venue returned the current ID.
    Resynchronize(String),
}

/// Provides an authenticated HTTP client for the Polymarket CLOB REST API.
///
/// Handles HTTP transport, L2 HMAC-SHA256 auth signing, pagination, and raw
/// API calls that closely match Polymarket endpoint specifications.
/// Credential is always present: the CLOB API requires authentication.
#[derive(Debug, Clone)]
pub struct PolymarketClobHttpClient {
    client: HttpClient,
    rate_limiter: Arc<PolymarketRateLimiter>,
    base_url: String,
    credential: Credential,
    address: String,
    clock: &'static AtomicTime,
}

impl PolymarketClobHttpClient {
    /// Creates a new authenticated [`PolymarketClobHttpClient`].
    ///
    /// # Errors
    ///
    /// Returns an error if the HTTP client cannot be created.
    pub fn new(
        credential: Credential,
        address: String,
        base_url: Option<String>,
        timeout_secs: u64,
    ) -> StdResult<Self, HttpClientError> {
        Self::new_with_proxy(credential, address, base_url, timeout_secs, None)
    }

    /// Creates a new authenticated client with an optional validated proxy URL.
    ///
    /// # Errors
    ///
    /// Returns an error if the HTTP client cannot be created.
    pub fn new_with_proxy(
        credential: Credential,
        address: String,
        base_url: Option<String>,
        timeout_secs: u64,
        proxy_url: Option<ProxyUrl>,
    ) -> StdResult<Self, HttpClientError> {
        let rate_limiter = PolymarketRateLimiter::for_signer(&address);
        Ok(Self {
            client: HttpClient::new(
                Self::default_headers(),
                RateLimitHeaders::names(),
                vec![],
                None,
                Some(timeout_secs),
                proxy_url.map(|url| url.expose().to_string()),
            )?,
            rate_limiter,
            base_url: base_url
                .unwrap_or_else(|| clob_http_url().to_string())
                .trim_end_matches('/')
                .to_string(),
            credential,
            address,
            clock: get_atomic_clock_realtime(),
        })
    }

    fn default_headers() -> HashMap<String, String> {
        HashMap::from([
            (USER_AGENT.to_string(), NAUTILUS_USER_AGENT.to_string()),
            ("Content-Type".to_string(), "application/json".to_string()),
        ])
    }

    fn url(&self, path: &str) -> String {
        format!("{}{path}", self.base_url)
    }

    fn timestamp(&self) -> String {
        (self.clock.get_time_ns().as_u64() / 1_000_000_000).to_string()
    }

    fn auth_headers(&self, method: &str, path: &str, body: &str) -> HashMap<String, String> {
        let timestamp = self.timestamp();
        let signature = self.credential.sign(&timestamp, method, path, body);

        HashMap::from([
            ("POLY_ADDRESS".to_string(), self.address.clone()),
            ("POLY_SIGNATURE".to_string(), signature),
            ("POLY_TIMESTAMP".to_string(), timestamp),
            (
                "POLY_API_KEY".to_string(),
                self.credential.api_key().to_string(),
            ),
            (
                "POLY_PASSPHRASE".to_string(),
                self.credential.passphrase().to_string(),
            ),
        ])
    }

    async fn send_get<P: Serialize, T: DeserializeOwned>(
        &self,
        path: &str,
        params: Option<&P>,
        auth: bool,
    ) -> Result<T> {
        let headers = if auth {
            Some(self.auth_headers("GET", path, ""))
        } else {
            None
        };
        let url = self.url(path);
        let response = self
            .client
            .request_with_params(Method::GET, url, params, headers, None, None, None)
            .await
            .map_err(Error::from_http_client)?;

        if response.status.is_success() {
            serde_json::from_slice(&response.body).map_err(Error::Serde)
        } else {
            Err(Error::from_status_code(
                response.status.as_u16(),
                &response.body,
            ))
        }
    }

    /// Like [`send_get`] but returns `Ok(None)` for empty or `null` response bodies
    /// instead of a serde deserialization error.
    async fn send_get_optional<P: Serialize, T: DeserializeOwned>(
        &self,
        path: &str,
        params: Option<&P>,
        auth: bool,
    ) -> Result<Option<T>> {
        let headers = if auth {
            Some(self.auth_headers("GET", path, ""))
        } else {
            None
        };
        let url = self.url(path);
        let response = self
            .client
            .request_with_params(Method::GET, url, params, headers, None, None, None)
            .await
            .map_err(Error::from_http_client)?;

        if response.status.is_success() {
            if response.body.is_empty() || response.body.as_ref() == b"null" {
                Ok(None)
            } else {
                serde_json::from_slice(&response.body)
                    .map(Some)
                    .map_err(Error::Serde)
            }
        } else {
            Err(Error::from_status_code(
                response.status.as_u16(),
                &response.body,
            ))
        }
    }

    async fn send_post<T: DeserializeOwned>(
        &self,
        path: &'static str,
        body_bytes: Vec<u8>,
        cost: u32,
    ) -> Result<T> {
        self.send_trading(
            Method::POST,
            path,
            Some(body_bytes),
            TradingBucket::Order,
            cost,
            |_| 0,
        )
        .await
    }

    async fn send_delete<T: DeserializeOwned>(
        &self,
        path: &'static str,
        body_bytes: Option<Vec<u8>>,
        cost: u32,
    ) -> Result<T> {
        self.send_trading(
            Method::DELETE,
            path,
            body_bytes,
            TradingBucket::Cancel,
            cost,
            |_| 0,
        )
        .await
    }

    async fn send_delete_with_cancel_debit(
        &self,
        path: &'static str,
        body_bytes: Option<Vec<u8>>,
    ) -> Result<BatchCancelResponse> {
        self.send_trading(
            Method::DELETE,
            path,
            body_bytes,
            TradingBucket::Cancel,
            1,
            canceled_count,
        )
        .await
    }

    async fn send_trading<T: DeserializeOwned>(
        &self,
        method: Method,
        path: &'static str,
        body_bytes: Option<Vec<u8>>,
        bucket: TradingBucket,
        cost: u32,
        post_response_cost: impl FnOnce(&T) -> u32,
    ) -> Result<T> {
        self.rate_limiter.acquire(path, bucket, cost).await?;

        let body_str = body_bytes
            .as_deref()
            .map(|b| from_utf8(b).map_err(|e| Error::decode(format!("UTF-8 error: {e}"))))
            .transpose()?
            .unwrap_or("");
        let headers = Some(self.auth_headers(method.as_str(), path, body_str));
        let url = self.url(path);
        let response = self
            .client
            .request(method, url, None, headers, body_bytes, None, None)
            .await
            .map_err(Error::from_http_client)?;
        let rate_limit_headers = RateLimitHeaders::parse(&response.headers);

        if response.status.is_success() {
            let decoded = serde_json::from_slice(&response.body);
            let post_response_cost = decoded.as_ref().map_or(0, post_response_cost);
            self.rate_limiter
                .observe_response(
                    path,
                    bucket,
                    cost,
                    post_response_cost,
                    &rate_limit_headers,
                    false,
                )
                .await;
            decoded.map_err(Error::Serde)
        } else {
            let rate_limited = response.status.as_u16() == 429;
            self.rate_limiter
                .observe_response(path, bucket, cost, 0, &rate_limit_headers, rate_limited)
                .await;

            if rate_limited {
                Err(Error::rate_limit(
                    path,
                    cost,
                    rate_limit_headers.retry_after_ms(),
                ))
            } else {
                Err(Error::from_status_code(
                    response.status.as_u16(),
                    &response.body,
                ))
            }
        }
    }

    /// Sends an authenticated order-safety heartbeat.
    pub async fn post_heartbeat(&self, heartbeat_id: &str) -> Result<HeartbeatResponse> {
        let body = HeartbeatRequest { heartbeat_id };
        let body_bytes = serde_json::to_vec(&body).map_err(Error::Serde)?;
        let body_str =
            from_utf8(&body_bytes).map_err(|e| Error::decode(format!("UTF-8 error: {e}")))?;
        let headers = Some(self.auth_headers("POST", PATH_HEARTBEATS, body_str));
        let response = self
            .client
            .request(
                Method::POST,
                self.url(PATH_HEARTBEATS),
                None,
                headers,
                Some(body_bytes),
                None,
                None,
            )
            .await
            .map_err(Error::from_http_client)?;

        let wire = serde_json::from_slice::<HeartbeatWireResponse>(&response.body);
        if response.status.is_success() {
            let wire = wire.map_err(Error::Serde)?;
            if let Some(heartbeat_id) = wire.heartbeat_id.filter(|id| !id.is_empty()) {
                return Ok(HeartbeatResponse::Acknowledged(Some(heartbeat_id)));
            }

            if wire.status.as_deref() == Some("ok") {
                return Ok(HeartbeatResponse::Acknowledged(None));
            }
            return Err(Error::exchange("Heartbeat acknowledgment was invalid"));
        }

        if response.status.as_u16() == 400
            && let Ok(wire) = wire
            && let Some(heartbeat_id) = wire.heartbeat_id.filter(|id| !id.is_empty())
        {
            return Ok(HeartbeatResponse::Resynchronize(heartbeat_id));
        }

        Err(Error::from_status_code(
            response.status.as_u16(),
            &response.body,
        ))
    }

    /// Fetches all open orders matching the given parameters (auto-paginated).
    pub async fn get_orders(
        &self,
        mut params: GetOrdersParams,
    ) -> Result<Vec<PolymarketOpenOrder>> {
        if params.next_cursor.is_none() {
            params.next_cursor = Some(CURSOR_START.to_string());
        }
        let mut all = Vec::new();

        loop {
            let page: PaginatedResponse<PolymarketOpenOrder> =
                self.send_get(PATH_ORDERS, Some(&params), true).await?;
            all.extend(page.data);
            if page.next_cursor == CURSOR_END {
                break;
            }
            params.next_cursor = Some(page.next_cursor);
        }
        Ok(all)
    }

    /// Fetches a single open order by ID, returning `None` for empty/null responses.
    pub async fn get_order_optional(&self, order_id: &str) -> Result<Option<PolymarketOpenOrder>> {
        let path = format!("/data/order/{order_id}");
        self.send_get_optional::<(), _>(&path, None::<&()>, true)
            .await
    }

    /// Fetches a single open order by ID.
    ///
    /// Returns an error if the order is not found (empty/null response).
    pub async fn get_order(&self, order_id: &str) -> Result<PolymarketOpenOrder> {
        self.get_order_optional(order_id)
            .await?
            .ok_or_else(|| Error::decode(format!("Order {order_id} not found (empty response)")))
    }

    /// Fetches all trades matching the given parameters (auto-paginated).
    pub async fn get_trades(
        &self,
        mut params: GetTradesParams,
    ) -> Result<Vec<PolymarketTradeReport>> {
        if params.next_cursor.is_none() {
            params.next_cursor = Some(CURSOR_START.to_string());
        }
        let mut all = Vec::new();

        loop {
            let page: PaginatedResponse<PolymarketTradeReport> =
                self.send_get(PATH_TRADES, Some(&params), true).await?;
            all.extend(page.data);
            if page.next_cursor == CURSOR_END {
                break;
            }
            params.next_cursor = Some(page.next_cursor);
        }
        Ok(all)
    }

    /// Fetches balance and allowance for the given parameters.
    pub async fn get_balance_allowance(
        &self,
        params: GetBalanceAllowanceParams,
    ) -> Result<BalanceAllowance> {
        let headers = Some(self.auth_headers("GET", PATH_BALANCE_ALLOWANCE, ""));
        let url = self.url(PATH_BALANCE_ALLOWANCE);
        let response = self
            .client
            .request_with_params(Method::GET, url, Some(&params), headers, None, None, None)
            .await
            .map_err(Error::from_http_client)?;

        if response.status.is_success() {
            serde_json::from_slice(&response.body).map_err(Error::Serde)
        } else {
            Err(Error::from_status_code(
                response.status.as_u16(),
                &response.body,
            ))
        }
    }

    /// Refreshes the CLOB backend's cached balance and allowance data.
    pub async fn update_balance_allowance(&self, params: GetBalanceAllowanceParams) -> Result<()> {
        self.send_get_optional::<_, serde_json::Value>(
            PATH_BALANCE_ALLOWANCE_UPDATE,
            Some(&params),
            true,
        )
        .await?;
        Ok(())
    }

    /// Submits a single signed order to the exchange.
    pub async fn post_order(
        &self,
        order: &PolymarketOrder,
        order_type: PolymarketOrderType,
        post_only: bool,
    ) -> Result<OrderResponse> {
        let owner = self.credential.api_key().to_string();
        let body = PostOrderBody {
            order,
            owner: &owner,
            order_type,
            post_only,
        };
        let body_bytes = serde_json::to_vec(&body).map_err(Error::Serde)?;
        self.send_post(PATH_POST_ORDER, body_bytes, 1).await
    }

    /// Submits a batch of signed orders to the exchange.
    ///
    /// Each entry is `(order, order_type, post_only)`.
    pub async fn post_orders(
        &self,
        orders: &[(&PolymarketOrder, PolymarketOrderType, bool)],
    ) -> Result<Vec<OrderResponse>> {
        let owner = self.credential.api_key().to_string();
        let entries: Vec<PostOrderBody<'_>> = orders
            .iter()
            .map(|(order, order_type, post_only)| PostOrderBody {
                order,
                owner: &owner,
                order_type: *order_type,
                post_only: *post_only,
            })
            .collect();
        let body_bytes = serde_json::to_vec(&entries).map_err(Error::Serde)?;
        let cost = batch_cost(PATH_POST_ORDERS, entries.len())?;
        self.send_post(PATH_POST_ORDERS, body_bytes, cost).await
    }

    /// Cancels a single order by ID.
    pub async fn cancel_order(&self, order_id: &str) -> Result<CancelResponse> {
        let body = CancelOrderBody { order_id };
        let body_bytes = serde_json::to_vec(&body).map_err(Error::Serde)?;
        self.send_delete(PATH_POST_ORDER, Some(body_bytes), 1).await
    }

    /// Cancels multiple orders by ID.
    pub async fn cancel_orders(&self, order_ids: &[&str]) -> Result<BatchCancelResponse> {
        let body_bytes = serde_json::to_vec(order_ids).map_err(Error::Serde)?;
        let cost = batch_cost(PATH_POST_ORDERS, order_ids.len())?;
        self.send_delete(PATH_POST_ORDERS, Some(body_bytes), cost)
            .await
    }

    pub(crate) async fn cancel_batch_limit(&self) -> usize {
        cancel_batch_limit(self.rate_limiter.burst(TradingBucket::Cancel).await)
    }

    /// Cancels all open orders.
    pub async fn cancel_all(&self) -> Result<BatchCancelResponse> {
        self.send_delete_with_cancel_debit(PATH_CANCEL_ALL, None)
            .await
    }

    /// Cancels all orders for a specific market.
    pub async fn cancel_market_orders(
        &self,
        params: CancelMarketOrdersParams,
    ) -> Result<BatchCancelResponse> {
        let body_bytes = serde_json::to_vec(&params).map_err(Error::Serde)?;
        self.send_delete_with_cancel_debit(PATH_CANCEL_MARKET_ORDERS, Some(body_bytes))
            .await
    }

    /// Fetches the tick size for a token from the CLOB API.
    pub async fn get_tick_size(&self, token_id: &str) -> Result<TickSizeResponse> {
        let params = [("token_id", token_id)];
        self.send_get("/tick-size", Some(&params), false).await
    }

    /// Fetches the fee rate (in basis points) for a token from the CLOB API.
    pub async fn get_fee_rate(&self, token_id: &str) -> Result<FeeRateResponse> {
        let params = [("token_id", token_id)];
        self.send_get("/fee-rate", Some(&params), false).await
    }

    /// Fetches the order book for a token from the CLOB API (public endpoint).
    pub async fn get_book(&self, token_id: &str) -> Result<ClobBookResponse> {
        let params = [("token_id", token_id)];
        self.send_get("/book", Some(&params), false).await
    }
}

/// Provides an unauthenticated HTTP client for public CLOB endpoints.
///
/// Unlike [`PolymarketClobHttpClient`], this client does not require credentials
/// and is suitable for the data client which only needs public market data.
#[derive(Debug, Clone)]
pub struct PolymarketClobPublicClient {
    client: HttpClient,
    base_url: String,
}

impl PolymarketClobPublicClient {
    /// Creates a new [`PolymarketClobPublicClient`].
    ///
    /// # Errors
    ///
    /// Returns an error if the HTTP client cannot be created.
    pub fn new(base_url: Option<String>, timeout_secs: u64) -> StdResult<Self, HttpClientError> {
        Self::new_with_proxy(base_url, timeout_secs, None)
    }

    /// Creates a new public client with an optional validated proxy URL.
    ///
    /// # Errors
    ///
    /// Returns an error if the HTTP client cannot be created.
    pub fn new_with_proxy(
        base_url: Option<String>,
        timeout_secs: u64,
        proxy_url: Option<ProxyUrl>,
    ) -> StdResult<Self, HttpClientError> {
        Ok(Self {
            client: HttpClient::new(
                HashMap::from([
                    (USER_AGENT.to_string(), NAUTILUS_USER_AGENT.to_string()),
                    ("Content-Type".to_string(), "application/json".to_string()),
                ]),
                vec![],
                vec![],
                None,
                Some(timeout_secs),
                proxy_url.map(|url| url.expose().to_string()),
            )?,
            base_url: base_url
                .unwrap_or_else(|| clob_http_url().to_string())
                .trim_end_matches('/')
                .to_string(),
        })
    }

    /// Fetches the order book for a token from the CLOB API.
    pub async fn get_book(&self, token_id: &str) -> Result<ClobBookResponse> {
        let params = [("token_id", token_id)];
        let url = format!("{}/book", self.base_url);
        let response = self
            .client
            .request_with_params(Method::GET, url, Some(&params), None, None, None, None)
            .await
            .map_err(Error::from_http_client)?;

        if response.status.is_success() {
            serde_json::from_slice(&response.body).map_err(Error::Serde)
        } else {
            Err(Error::from_status_code(
                response.status.as_u16(),
                &response.body,
            ))
        }
    }

    /// Fetches a single market by condition ID from the CLOB API.
    pub async fn get_market(&self, condition_id: &str) -> Result<ClobMarketResponse> {
        let url = format!("{}/markets/{condition_id}", self.base_url);
        let response = self
            .client
            .request_with_params(Method::GET, url, None::<&()>, None, None, None, None)
            .await
            .map_err(Error::from_http_client)?;

        if response.status.is_success() {
            serde_json::from_slice(&response.body).map_err(Error::Serde)
        } else {
            Err(Error::from_status_code(
                response.status.as_u16(),
                &response.body,
            ))
        }
    }

    /// Requests an order book snapshot and builds an [`OrderBook`].
    pub async fn request_book_snapshot(
        &self,
        instrument_id: InstrumentId,
        token_id: &str,
        price_precision: u8,
        size_precision: u8,
    ) -> anyhow::Result<OrderBook> {
        let resp = self
            .get_book(token_id)
            .await
            .map_err(|e| anyhow::anyhow!(e))?;

        let mut book = OrderBook::new(instrument_id, BookType::L2_MBP);

        for (i, level) in resp.bids.iter().enumerate() {
            let price = parse_price(&level.price, price_precision)?;
            let size = parse_quantity(&level.size, size_precision)?;
            let order = BookOrder::new(OrderSide::Buy, price, size, i as u64);
            book.add(order, 0, i as u64, Default::default());
        }

        let bids_len = resp.bids.len();
        for (i, level) in resp.asks.iter().enumerate() {
            let price = parse_price(&level.price, price_precision)?;
            let size = parse_quantity(&level.size, size_precision)?;
            let order = BookOrder::new(OrderSide::Sell, price, size, (bids_len + i) as u64);
            book.add(order, 0, (bids_len + i) as u64, Default::default());
        }

        log::debug!(
            "Fetched order book for {} with {} bids and {} asks",
            instrument_id,
            resp.bids.len(),
            resp.asks.len(),
        );

        Ok(book)
    }
}

fn batch_cost(endpoint: &'static str, len: usize) -> Result<u32> {
    let cost = u32::try_from(len)
        .map_err(|_| Error::bad_request(format!("{endpoint} batch length exceeds u32")))?;
    if cost == 0 {
        return Err(Error::bad_request(format!(
            "{endpoint} batch must not be empty"
        )));
    }
    Ok(cost)
}

fn cancel_batch_limit(burst: u32) -> usize {
    usize::try_from(burst)
        .unwrap_or(usize::MAX)
        .min(CLOB_CANCEL_BATCH_LIMIT)
}

fn canceled_count(response: &BatchCancelResponse) -> u32 {
    u32::try_from(response.canceled.len()).unwrap_or(u32::MAX)
}

#[cfg(test)]
mod tests {
    use nautilus_model::{
        enums::{BookType, OrderSide},
        identifiers::InstrumentId,
        types::{Price, Quantity},
    };
    use rstest::rstest;

    use super::*;
    use crate::http::models::{ClobBookLevel, ClobBookResponse};

    fn build_book_from_response(resp: &ClobBookResponse) -> OrderBook {
        let instrument_id = InstrumentId::from("TEST.POLYMARKET");
        let price_precision = 2u8;
        let size_precision = 2u8;
        let mut book = OrderBook::new(instrument_id, BookType::L2_MBP);

        for (i, level) in resp.bids.iter().enumerate() {
            let price = parse_price(&level.price, price_precision).unwrap();
            let size = parse_quantity(&level.size, size_precision).unwrap();
            let order = BookOrder::new(OrderSide::Buy, price, size, i as u64);
            book.add(order, 0, i as u64, Default::default());
        }

        let bids_len = resp.bids.len();
        for (i, level) in resp.asks.iter().enumerate() {
            let price = parse_price(&level.price, price_precision).unwrap();
            let size = parse_quantity(&level.size, size_precision).unwrap();
            let order = BookOrder::new(OrderSide::Sell, price, size, (bids_len + i) as u64);
            book.add(order, 0, (bids_len + i) as u64, Default::default());
        }

        book
    }

    #[rstest]
    fn test_build_order_book_from_clob_response() {
        let resp = ClobBookResponse {
            bids: vec![
                ClobBookLevel {
                    price: "0.48".to_string(),
                    size: "100.00".to_string(),
                },
                ClobBookLevel {
                    price: "0.49".to_string(),
                    size: "200.00".to_string(),
                },
                ClobBookLevel {
                    price: "0.50".to_string(),
                    size: "150.00".to_string(),
                },
            ],
            asks: vec![
                ClobBookLevel {
                    price: "0.51".to_string(),
                    size: "120.00".to_string(),
                },
                ClobBookLevel {
                    price: "0.52".to_string(),
                    size: "180.00".to_string(),
                },
            ],
        };

        let book = build_book_from_response(&resp);

        assert_eq!(book.instrument_id, InstrumentId::from("TEST.POLYMARKET"));
        assert_eq!(book.book_type, BookType::L2_MBP);
        assert_eq!(book.best_bid_price(), Some(Price::from("0.50")));
        assert_eq!(book.best_ask_price(), Some(Price::from("0.51")));
        assert_eq!(book.best_bid_size(), Some(Quantity::from("150.00")));
        assert_eq!(book.best_ask_size(), Some(Quantity::from("120.00")));
        assert_eq!(book.bids(None).count(), 3);
        assert_eq!(book.asks(None).count(), 2);
    }

    #[rstest]
    fn test_build_order_book_empty_response() {
        let resp = ClobBookResponse {
            bids: vec![],
            asks: vec![],
        };

        let book = build_book_from_response(&resp);

        assert!(book.best_bid_price().is_none());
        assert!(book.best_ask_price().is_none());
    }

    #[rstest]
    fn test_batch_cost_uses_entry_count_and_rejects_empty_batch() {
        assert_eq!(batch_cost(PATH_POST_ORDERS, 15).unwrap(), 15);
        assert_eq!(
            batch_cost(PATH_POST_ORDERS, 0).unwrap_err().to_string(),
            "bad request: /orders batch must not be empty"
        );
    }

    #[rstest]
    fn test_canceled_count_uses_only_successful_cancellations() {
        let response = BatchCancelResponse {
            canceled: vec!["order-1".to_string(), "order-2".to_string()],
            not_canceled: ahash::AHashMap::from_iter([(
                "order-3".to_string(),
                Some("already canceled".to_string()),
            )]),
        };

        assert_eq!(canceled_count(&response), 2);
    }

    #[rstest]
    #[case::standard(120, 120)]
    #[case::silver(600, 600)]
    #[case::gold(1_200, 1_000)]
    #[case::elite(1_800, 1_000)]
    fn test_cancel_batch_limit_uses_tier_burst_and_venue_ceiling(
        #[case] burst: u32,
        #[case] expected: usize,
    ) {
        assert_eq!(cancel_batch_limit(burst), expected);
    }
}