Skip to main content

nautilus_polymarket/http/
clob.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Provides the HTTP client for the Polymarket CLOB REST API.
17
18use std::{collections::HashMap, result::Result as StdResult, str::from_utf8, sync::Arc};
19
20use nautilus_core::time::{AtomicTime, get_atomic_clock_realtime};
21use nautilus_model::{
22    data::BookOrder,
23    enums::{BookType, OrderSide},
24    identifiers::InstrumentId,
25    orderbook::OrderBook,
26};
27use nautilus_network::{
28    http::{
29        HttpClient, HttpClientError, HttpRedirectPolicy, Method, create_standard_nautilus_headers,
30    },
31    websocket::proxy::ProxyUrl,
32};
33use rust_decimal::Decimal;
34use serde::{Deserialize, Serialize, de::DeserializeOwned};
35
36use crate::{
37    common::{
38        credential::Credential, enums::PolymarketOrderType, parse::deserialize_decimal_from_str,
39        urls::clob_http_url,
40    },
41    http::{
42        error::{Error, Result, decode_response},
43        models::{
44            ClobBookResponse, ClobMarketResponse, FeeRateResponse, PolymarketOpenOrder,
45            PolymarketOrder, PolymarketTradeReport, TickSizeResponse,
46        },
47        pagination::{CollectAll, Completion, CursorProtocol, FetchOutcome, Paginator},
48        query::{
49            BalanceAllowance, BatchCancelResponse, CancelMarketOrdersParams, CancelResponse,
50            ClobVersionResponse, GetBalanceAllowanceParams, GetOrdersParams, GetTradesParams,
51            OrderResponse, PaginatedResponse,
52        },
53        rate_limits::{PolymarketRateLimiter, RateLimitHeaders, TradingBucket},
54    },
55    websocket::parse::{parse_price, parse_quantity},
56};
57
58const CURSOR_START: &str = "MA==";
59const CURSOR_END: &str = "LTE=";
60
61const PATH_ORDERS: &str = "/data/orders";
62const PATH_TRADES: &str = "/data/trades";
63const PATH_VERSION: &str = "/version";
64const PATH_BALANCE_ALLOWANCE: &str = "/balance-allowance";
65const PATH_BALANCE_ALLOWANCE_UPDATE: &str = "/balance-allowance/update";
66const PATH_POST_ORDER: &str = "/order";
67const PATH_POST_ORDERS: &str = "/orders";
68const PATH_CANCEL_ALL: &str = "/cancel-all";
69const PATH_CANCEL_MARKET_ORDERS: &str = "/cancel-market-orders";
70const PATH_HEARTBEATS: &str = "/v1/heartbeats";
71
72const CLOB_CANCEL_BATCH_LIMIT: usize = 1_000;
73
74#[derive(Serialize)]
75#[serde(rename_all = "camelCase")]
76struct PostOrderBody<'a> {
77    order: &'a PolymarketOrder,
78    owner: &'a str,
79    order_type: PolymarketOrderType,
80    #[serde(skip_serializing_if = "std::ops::Not::not")]
81    post_only: bool,
82}
83
84#[derive(Serialize)]
85struct CancelOrderBody<'a> {
86    #[serde(rename = "orderID")]
87    order_id: &'a str,
88}
89
90#[derive(Serialize)]
91struct HeartbeatRequest<'a> {
92    heartbeat_id: &'a str,
93}
94
95#[derive(Deserialize)]
96struct HeartbeatWireResponse {
97    heartbeat_id: Option<String>,
98}
99
100#[derive(Deserialize)]
101struct BalanceResponse {
102    #[serde(deserialize_with = "deserialize_decimal_from_str")]
103    balance: Decimal,
104}
105
106/// Outcome from an authenticated CLOB order-safety heartbeat.
107#[derive(Clone, Debug, PartialEq, Eq)]
108pub enum HeartbeatResponse {
109    /// The heartbeat was acknowledged and the venue returned the next ID for chaining.
110    Acknowledged(String),
111    /// The supplied ID was stale and the venue returned the current ID.
112    Resynchronize(String),
113}
114
115/// Provides an authenticated HTTP client for the Polymarket CLOB REST API.
116///
117/// Handles HTTP transport, L2 HMAC-SHA256 auth signing, pagination, and raw
118/// API calls that closely match Polymarket endpoint specifications.
119/// Credential is always present: the CLOB API requires authentication.
120#[derive(Debug, Clone)]
121pub struct PolymarketClobHttpClient {
122    client: HttpClient,
123    rate_limiter: Arc<PolymarketRateLimiter>,
124    base_url: String,
125    credential: Credential,
126    address: String,
127    clock: &'static AtomicTime,
128}
129
130impl PolymarketClobHttpClient {
131    /// Creates a new authenticated [`PolymarketClobHttpClient`].
132    ///
133    /// # Errors
134    ///
135    /// Returns an error if the HTTP client cannot be created.
136    pub fn new(
137        credential: Credential,
138        address: String,
139        base_url: Option<String>,
140        timeout_secs: u64,
141    ) -> StdResult<Self, HttpClientError> {
142        Self::new_with_proxy(credential, address, base_url, timeout_secs, None)
143    }
144
145    /// Creates a new authenticated client with an optional validated proxy URL.
146    ///
147    /// # Errors
148    ///
149    /// Returns an error if the HTTP client cannot be created.
150    pub fn new_with_proxy(
151        credential: Credential,
152        address: String,
153        base_url: Option<String>,
154        timeout_secs: u64,
155        proxy_url: Option<ProxyUrl>,
156    ) -> StdResult<Self, HttpClientError> {
157        let rate_limiter = PolymarketRateLimiter::for_signer(&address);
158        Ok(Self {
159            client: HttpClient::builder()
160                .redirect_policy(HttpRedirectPolicy::Reject)
161                .headers(Self::default_headers())
162                .header_keys(RateLimitHeaders::names())
163                .timeout_secs(timeout_secs)
164                .maybe_proxy_url(proxy_url.map(|url| url.expose().to_string()))
165                .build()?,
166            rate_limiter,
167            base_url: base_url
168                .unwrap_or_else(|| clob_http_url().to_string())
169                .trim_end_matches('/')
170                .to_string(),
171            credential,
172            address,
173            clock: get_atomic_clock_realtime(),
174        })
175    }
176
177    fn default_headers() -> HashMap<String, String> {
178        let mut headers: HashMap<String, String> =
179            create_standard_nautilus_headers().into_iter().collect();
180        headers.insert("Content-Type".to_string(), "application/json".to_string());
181        headers
182    }
183
184    fn url(&self, path: &str) -> String {
185        format!("{}{path}", self.base_url)
186    }
187
188    pub(crate) async fn list_session_keys(&self) -> Result<crate::session::SessionKeysResponse> {
189        self.send_get::<(), _>("/v1/user/session-signers", None, true)
190            .await
191    }
192
193    fn timestamp(&self) -> String {
194        (self.clock.get_time_ns().as_u64() / 1_000_000_000).to_string()
195    }
196
197    fn auth_headers(&self, method: &str, path: &str, body: &str) -> HashMap<String, String> {
198        let timestamp = self.timestamp();
199        let signature = self.credential.sign(&timestamp, method, path, body);
200
201        HashMap::from([
202            ("POLY_ADDRESS".to_string(), self.address.clone()),
203            ("POLY_SIGNATURE".to_string(), signature),
204            ("POLY_TIMESTAMP".to_string(), timestamp),
205            (
206                "POLY_API_KEY".to_string(),
207                self.credential.api_key_str().to_string(),
208            ),
209            (
210                "POLY_PASSPHRASE".to_string(),
211                self.credential.passphrase().to_string(),
212            ),
213        ])
214    }
215
216    async fn send_get<P: Serialize, T: DeserializeOwned>(
217        &self,
218        path: &str,
219        params: Option<&P>,
220        auth: bool,
221    ) -> Result<T> {
222        let headers = if auth {
223            Some(self.auth_headers("GET", path, ""))
224        } else {
225            None
226        };
227        let url = self.url(path);
228        let response = self
229            .client
230            .request_with_params(Method::GET, url, params, headers, None, None, None)
231            .await
232            .map_err(Error::from_http_client)?;
233
234        decode_response(&response)
235    }
236
237    /// Like [`send_get`] but returns `Ok(None)` for empty or `null` response bodies
238    /// instead of a serde deserialization error.
239    async fn send_get_optional<P: Serialize, T: DeserializeOwned>(
240        &self,
241        path: &str,
242        params: Option<&P>,
243        auth: bool,
244    ) -> Result<Option<T>> {
245        let headers = if auth {
246            Some(self.auth_headers("GET", path, ""))
247        } else {
248            None
249        };
250        let url = self.url(path);
251        let response = self
252            .client
253            .request_with_params(Method::GET, url, params, headers, None, None, None)
254            .await
255            .map_err(Error::from_http_client)?;
256
257        if response.status.is_success() {
258            let body = response.body.as_ref().trim_ascii();
259            if body.is_empty() || body == b"null" {
260                Ok(None)
261            } else {
262                serde_json::from_slice(body).map(Some).map_err(Error::Serde)
263            }
264        } else {
265            Err(Error::from_status_code(
266                response.status.as_u16(),
267                &response.body,
268            ))
269        }
270    }
271
272    async fn send_post<T: DeserializeOwned>(
273        &self,
274        path: &'static str,
275        body_bytes: Vec<u8>,
276        cost: u32,
277        guard: impl Fn() -> Result<()>,
278    ) -> Result<T> {
279        self.send_trading(
280            Method::POST,
281            path,
282            Some(body_bytes),
283            TradingBucket::Order,
284            cost,
285            |_| 0,
286            guard,
287        )
288        .await
289    }
290
291    async fn send_delete<T: DeserializeOwned>(
292        &self,
293        path: &'static str,
294        body_bytes: Option<Vec<u8>>,
295        cost: u32,
296    ) -> Result<T> {
297        self.send_trading(
298            Method::DELETE,
299            path,
300            body_bytes,
301            TradingBucket::Cancel,
302            cost,
303            |_| 0,
304            || Ok(()),
305        )
306        .await
307    }
308
309    async fn send_delete_with_cancel_debit(
310        &self,
311        path: &'static str,
312        body_bytes: Option<Vec<u8>>,
313    ) -> Result<BatchCancelResponse> {
314        self.send_trading(
315            Method::DELETE,
316            path,
317            body_bytes,
318            TradingBucket::Cancel,
319            1,
320            canceled_count,
321            || Ok(()),
322        )
323        .await
324    }
325
326    #[expect(
327        clippy::too_many_arguments,
328        reason = "trading requests share rate-limit accounting and admission"
329    )]
330    async fn send_trading<T: DeserializeOwned>(
331        &self,
332        method: Method,
333        path: &'static str,
334        body_bytes: Option<Vec<u8>>,
335        bucket: TradingBucket,
336        cost: u32,
337        post_response_cost: impl FnOnce(&T) -> u32,
338        guard: impl Fn() -> Result<()>,
339    ) -> Result<T> {
340        guard()?;
341        self.rate_limiter.acquire(path, bucket, cost).await?;
342
343        let body_str = body_bytes
344            .as_deref()
345            .map(|b| from_utf8(b).map_err(|e| Error::decode(format!("UTF-8 error: {e}"))))
346            .transpose()?
347            .unwrap_or("");
348        let headers = Some(self.auth_headers(method.as_str(), path, body_str));
349        let url = self.url(path);
350        guard()?;
351        let response = self
352            .client
353            .request(method, url, None, headers, body_bytes, None, None)
354            .await
355            .map_err(Error::from_http_client)?;
356        let rate_limit_headers = RateLimitHeaders::parse(&response.headers);
357
358        if response.status.is_success() {
359            let decoded = serde_json::from_slice(&response.body);
360            let post_response_cost = decoded.as_ref().map_or(0, post_response_cost);
361            self.rate_limiter
362                .observe_response(
363                    path,
364                    bucket,
365                    cost,
366                    post_response_cost,
367                    &rate_limit_headers,
368                    false,
369                )
370                .await;
371            decoded.map_err(Error::Serde)
372        } else {
373            let rate_limited = response.status.as_u16() == 429;
374            self.rate_limiter
375                .observe_response(path, bucket, cost, 0, &rate_limit_headers, rate_limited)
376                .await;
377
378            if rate_limited {
379                Err(Error::rate_limit_from_body(
380                    path,
381                    cost,
382                    rate_limit_headers.retry_after_ms(),
383                    &response.body,
384                    rate_limit_headers.has_signer_headers(),
385                ))
386            } else {
387                Err(Error::from_status_code(
388                    response.status.as_u16(),
389                    &response.body,
390                ))
391            }
392        }
393    }
394
395    /// Returns the CLOB service version reported by the venue.
396    pub async fn get_version(&self) -> Result<ClobVersionResponse> {
397        self.send_get::<(), _>(PATH_VERSION, None, false).await
398    }
399
400    pub(crate) async fn get_market(&self, condition_id: &str) -> Result<ClobMarketResponse> {
401        let path = format!("/markets/{condition_id}");
402        self.send_get::<(), _>(&path, None, false).await
403    }
404
405    /// Sends an authenticated order-safety heartbeat.
406    pub async fn post_heartbeat(&self, heartbeat_id: &str) -> Result<HeartbeatResponse> {
407        let body = HeartbeatRequest { heartbeat_id };
408        let body_bytes = serde_json::to_vec(&body).map_err(Error::Serde)?;
409        let body_str =
410            from_utf8(&body_bytes).map_err(|e| Error::decode(format!("UTF-8 error: {e}")))?;
411        let headers = Some(self.auth_headers("POST", PATH_HEARTBEATS, body_str));
412        let response = self
413            .client
414            .request(
415                Method::POST,
416                self.url(PATH_HEARTBEATS),
417                None,
418                headers,
419                Some(body_bytes),
420                None,
421                None,
422            )
423            .await
424            .map_err(Error::from_http_client)?;
425
426        if response.status.as_u16() == 429 {
427            let rate_limit_headers = RateLimitHeaders::parse(&response.headers);
428            return Err(Error::rate_limit_from_body(
429                PATH_HEARTBEATS,
430                0,
431                rate_limit_headers.retry_after_ms(),
432                &response.body,
433                rate_limit_headers.has_signer_headers(),
434            ));
435        }
436
437        let wire = serde_json::from_slice::<HeartbeatWireResponse>(&response.body);
438        let next_id = |wire: HeartbeatWireResponse| {
439            wire.heartbeat_id
440                .filter(|heartbeat_id| !heartbeat_id.is_empty())
441        };
442
443        if response.status.is_success() {
444            if let Some(heartbeat_id) = next_id(wire.map_err(Error::Serde)?) {
445                return Ok(HeartbeatResponse::Acknowledged(heartbeat_id));
446            }
447
448            return Err(Error::exchange("Heartbeat acknowledgment was invalid"));
449        }
450
451        if response.status.as_u16() == 400
452            && let Ok(wire) = wire
453            && let Some(heartbeat_id) = next_id(wire)
454        {
455            return Ok(HeartbeatResponse::Resynchronize(heartbeat_id));
456        }
457
458        Err(Error::from_status_code(
459            response.status.as_u16(),
460            &response.body,
461        ))
462    }
463
464    /// Fetches all open orders matching the given parameters (auto-paginated).
465    pub async fn get_orders(&self, params: GetOrdersParams) -> Result<Vec<PolymarketOpenOrder>> {
466        let initial_cursor = params
467            .next_cursor
468            .clone()
469            .unwrap_or_else(|| CURSOR_START.to_string());
470        let protocol = CursorProtocol::clob(PATH_ORDERS, initial_cursor, CURSOR_END);
471        let paginator = Paginator::new(PATH_ORDERS, protocol, CollectAll::new());
472        let completed = paginator
473            .run(
474                |position| {
475                    let mut request = params.clone();
476                    request.next_cursor =
477                        position.as_ref().map(|cursor| cursor.as_ref().to_string());
478                    async move {
479                        let page: PaginatedResponse<PolymarketOpenOrder> =
480                            self.send_get(PATH_ORDERS, Some(&request), true).await?;
481                        Ok(FetchOutcome {
482                            rows: page.data,
483                            wire: page.next_cursor,
484                        })
485                    }
486                },
487                |e| Error::decode(e.to_string()),
488            )
489            .await?;
490
491        match completed.completion {
492            Completion::WireExhausted => Ok(completed.output),
493            Completion::Stopped(never) => match never {},
494        }
495    }
496
497    /// Fetches a single order by ID, returning `None` for empty/null responses.
498    pub async fn get_order_optional(&self, order_id: &str) -> Result<Option<PolymarketOpenOrder>> {
499        let path = format!("/data/order/{order_id}");
500        self.send_get_optional::<(), _>(&path, None::<&()>, true)
501            .await
502    }
503
504    /// Fetches a single order by ID.
505    ///
506    /// Returns an error if the order is not found (empty/null response).
507    pub async fn get_order(&self, order_id: &str) -> Result<PolymarketOpenOrder> {
508        self.get_order_optional(order_id)
509            .await?
510            .ok_or_else(|| Error::decode(format!("Order {order_id} not found (empty response)")))
511    }
512
513    /// Fetches all trades matching the given parameters (auto-paginated).
514    pub async fn get_trades(&self, params: GetTradesParams) -> Result<Vec<PolymarketTradeReport>> {
515        let initial_cursor = params
516            .next_cursor
517            .clone()
518            .unwrap_or_else(|| CURSOR_START.to_string());
519        let protocol = CursorProtocol::clob(PATH_TRADES, initial_cursor, CURSOR_END);
520        let paginator = Paginator::new(PATH_TRADES, protocol, CollectAll::new());
521        let completed = paginator
522            .run(
523                |position| {
524                    let mut request = params.clone();
525                    request.next_cursor =
526                        position.as_ref().map(|cursor| cursor.as_ref().to_string());
527                    async move {
528                        let page: PaginatedResponse<PolymarketTradeReport> =
529                            self.send_get(PATH_TRADES, Some(&request), true).await?;
530                        Ok(FetchOutcome {
531                            rows: page.data,
532                            wire: page.next_cursor,
533                        })
534                    }
535                },
536                |e| Error::decode(e.to_string()),
537            )
538            .await?;
539
540        match completed.completion {
541            Completion::WireExhausted => Ok(completed.output),
542            Completion::Stopped(never) => match never {},
543        }
544    }
545
546    /// Fetches strict V2 balance and allowance evidence for the given parameters.
547    ///
548    /// The response must contain a plural spender map with canonical, unique EVM addresses.
549    /// A non-null legacy singular allowance is rejected as conflicting authority. Internal
550    /// balance-only consumers use the private projection instead.
551    pub async fn get_balance_allowance(
552        &self,
553        params: GetBalanceAllowanceParams,
554    ) -> Result<BalanceAllowance> {
555        self.send_get(PATH_BALANCE_ALLOWANCE, Some(&params), true)
556            .await
557    }
558
559    /// Fetches balance for internal account refresh and market-buy fee adjustment without consuming
560    /// allowance evidence.
561    ///
562    /// Allowance fields are intentionally ignored and cannot grant authority through this return
563    /// type.
564    pub(crate) async fn get_balance(&self, params: GetBalanceAllowanceParams) -> Result<Decimal> {
565        let response: BalanceResponse = self
566            .send_get(PATH_BALANCE_ALLOWANCE, Some(&params), true)
567            .await?;
568        Ok(response.balance)
569    }
570
571    /// Refreshes the CLOB backend's cached balance and allowance data.
572    pub async fn update_balance_allowance(&self, params: GetBalanceAllowanceParams) -> Result<()> {
573        self.send_get_optional::<_, serde_json::Value>(
574            PATH_BALANCE_ALLOWANCE_UPDATE,
575            Some(&params),
576            true,
577        )
578        .await?;
579        Ok(())
580    }
581
582    /// Submits a single signed order to the exchange.
583    pub async fn post_order(
584        &self,
585        order: &PolymarketOrder,
586        order_type: PolymarketOrderType,
587        post_only: bool,
588    ) -> Result<OrderResponse> {
589        self.post_order_guarded(order, order_type, post_only, || Ok(()))
590            .await
591    }
592
593    pub(crate) async fn post_order_guarded(
594        &self,
595        order: &PolymarketOrder,
596        order_type: PolymarketOrderType,
597        post_only: bool,
598        guard: impl Fn() -> Result<()>,
599    ) -> Result<OrderResponse> {
600        let body = PostOrderBody {
601            order,
602            owner: self.credential.api_key_str(),
603            order_type,
604            post_only,
605        };
606        let body_bytes = serde_json::to_vec(&body).map_err(Error::Serde)?;
607        self.send_post(PATH_POST_ORDER, body_bytes, 1, guard).await
608    }
609
610    /// Submits a batch of signed orders to the exchange.
611    ///
612    /// Each entry is `(order, order_type, post_only)`.
613    pub async fn post_orders(
614        &self,
615        orders: &[(&PolymarketOrder, PolymarketOrderType, bool)],
616    ) -> Result<Vec<OrderResponse>> {
617        self.post_orders_guarded(orders, || Ok(())).await
618    }
619
620    pub(crate) async fn post_orders_guarded(
621        &self,
622        orders: &[(&PolymarketOrder, PolymarketOrderType, bool)],
623        guard: impl Fn() -> Result<()>,
624    ) -> Result<Vec<OrderResponse>> {
625        let owner = self.credential.api_key_str();
626        let entries: Vec<PostOrderBody<'_>> = orders
627            .iter()
628            .map(|(order, order_type, post_only)| PostOrderBody {
629                order,
630                owner,
631                order_type: *order_type,
632                post_only: *post_only,
633            })
634            .collect();
635        let body_bytes = serde_json::to_vec(&entries).map_err(Error::Serde)?;
636        let cost = batch_cost(PATH_POST_ORDERS, entries.len())?;
637        self.send_post(PATH_POST_ORDERS, body_bytes, cost, guard)
638            .await
639    }
640
641    /// Cancels a single order by ID.
642    pub async fn cancel_order(&self, order_id: &str) -> Result<CancelResponse> {
643        let body = CancelOrderBody { order_id };
644        let body_bytes = serde_json::to_vec(&body).map_err(Error::Serde)?;
645        self.send_delete(PATH_POST_ORDER, Some(body_bytes), 1).await
646    }
647
648    /// Cancels multiple orders by ID.
649    pub async fn cancel_orders(&self, order_ids: &[&str]) -> Result<BatchCancelResponse> {
650        let body_bytes = serde_json::to_vec(order_ids).map_err(Error::Serde)?;
651        let cost = batch_cost(PATH_POST_ORDERS, order_ids.len())?;
652        self.send_delete(PATH_POST_ORDERS, Some(body_bytes), cost)
653            .await
654    }
655
656    pub(crate) async fn cancel_batch_limit(&self) -> usize {
657        cancel_batch_limit(self.rate_limiter.burst(TradingBucket::Cancel).await)
658    }
659
660    /// Cancels all open orders.
661    pub async fn cancel_all(&self) -> Result<BatchCancelResponse> {
662        self.send_delete_with_cancel_debit(PATH_CANCEL_ALL, None)
663            .await
664    }
665
666    /// Cancels all orders for a specific market.
667    pub async fn cancel_market_orders(
668        &self,
669        params: CancelMarketOrdersParams,
670    ) -> Result<BatchCancelResponse> {
671        let body_bytes = serde_json::to_vec(&params).map_err(Error::Serde)?;
672        self.send_delete_with_cancel_debit(PATH_CANCEL_MARKET_ORDERS, Some(body_bytes))
673            .await
674    }
675
676    /// Fetches the tick size for a token from the CLOB API.
677    pub async fn get_tick_size(&self, token_id: &str) -> Result<TickSizeResponse> {
678        let params = [("token_id", token_id)];
679        self.send_get("/tick-size", Some(&params), false).await
680    }
681
682    /// Fetches the legacy base fee in basis points, distinct from the effective taker rate.
683    pub async fn get_fee_rate(&self, token_id: &str) -> Result<FeeRateResponse> {
684        let params = [("token_id", token_id)];
685        self.send_get("/fee-rate", Some(&params), false).await
686    }
687
688    /// Fetches the order book for a token from the CLOB API (public endpoint).
689    pub async fn get_book(&self, token_id: &str) -> Result<ClobBookResponse> {
690        let params = [("token_id", token_id)];
691        self.send_get("/book", Some(&params), false).await
692    }
693}
694
695/// Provides an unauthenticated HTTP client for public CLOB endpoints.
696///
697/// Unlike [`PolymarketClobHttpClient`], this client does not require credentials
698/// and is suitable for the data client which only needs public market data.
699#[derive(Debug, Clone)]
700pub struct PolymarketClobPublicClient {
701    client: HttpClient,
702    base_url: String,
703}
704
705impl PolymarketClobPublicClient {
706    /// Creates a new [`PolymarketClobPublicClient`].
707    ///
708    /// # Errors
709    ///
710    /// Returns an error if the HTTP client cannot be created.
711    pub fn new(base_url: Option<String>, timeout_secs: u64) -> StdResult<Self, HttpClientError> {
712        Self::new_with_proxy(base_url, timeout_secs, None)
713    }
714
715    /// Creates a new public client with an optional validated proxy URL.
716    ///
717    /// # Errors
718    ///
719    /// Returns an error if the HTTP client cannot be created.
720    pub fn new_with_proxy(
721        base_url: Option<String>,
722        timeout_secs: u64,
723        proxy_url: Option<ProxyUrl>,
724    ) -> StdResult<Self, HttpClientError> {
725        let mut headers: HashMap<String, String> =
726            create_standard_nautilus_headers().into_iter().collect();
727        headers.insert("Content-Type".to_string(), "application/json".to_string());
728
729        Ok(Self {
730            client: HttpClient::builder()
731                .headers(headers)
732                .timeout_secs(timeout_secs)
733                .maybe_proxy_url(proxy_url.map(|url| url.expose().to_string()))
734                .build()?,
735            base_url: base_url
736                .unwrap_or_else(|| clob_http_url().to_string())
737                .trim_end_matches('/')
738                .to_string(),
739        })
740    }
741
742    /// Fetches the order book for a token from the CLOB API.
743    pub async fn get_book(&self, token_id: &str) -> Result<ClobBookResponse> {
744        let params = [("token_id", token_id)];
745        let url = format!("{}/book", self.base_url);
746        let response = self
747            .client
748            .request_with_params(Method::GET, url, Some(&params), None, None, None, None)
749            .await
750            .map_err(Error::from_http_client)?;
751
752        decode_response(&response)
753    }
754
755    /// Fetches a single market by condition ID from the CLOB API.
756    pub async fn get_market(&self, condition_id: &str) -> Result<ClobMarketResponse> {
757        let url = format!("{}/markets/{condition_id}", self.base_url);
758        let response = self
759            .client
760            .request_with_params(Method::GET, url, None::<&()>, None, None, None, None)
761            .await
762            .map_err(Error::from_http_client)?;
763
764        decode_response(&response)
765    }
766
767    /// Fetches the legacy base fee in basis points, distinct from the effective taker rate.
768    pub async fn get_fee_rate(&self, token_id: &str) -> Result<FeeRateResponse> {
769        let params = [("token_id", token_id)];
770        let url = format!("{}/fee-rate", self.base_url);
771        let response = self
772            .client
773            .request_with_params(Method::GET, url, Some(&params), None, None, None, None)
774            .await
775            .map_err(Error::from_http_client)?;
776
777        decode_response(&response)
778    }
779
780    /// Requests an order book snapshot and builds an [`OrderBook`].
781    pub async fn request_book_snapshot(
782        &self,
783        instrument_id: InstrumentId,
784        token_id: &str,
785        price_precision: u8,
786        size_precision: u8,
787    ) -> anyhow::Result<OrderBook> {
788        let resp = self
789            .get_book(token_id)
790            .await
791            .map_err(|e| anyhow::anyhow!(e))?;
792
793        let mut book = OrderBook::new(instrument_id, BookType::L2_MBP);
794
795        for (i, level) in resp.bids.iter().enumerate() {
796            let price = parse_price(&level.price, price_precision)?;
797            let size = parse_quantity(&level.size, size_precision)?;
798            let order = BookOrder::new(OrderSide::Buy, price, size, i as u64);
799            book.add(order, 0, i as u64, Default::default());
800        }
801
802        let bids_len = resp.bids.len();
803        for (i, level) in resp.asks.iter().enumerate() {
804            let price = parse_price(&level.price, price_precision)?;
805            let size = parse_quantity(&level.size, size_precision)?;
806            let order = BookOrder::new(OrderSide::Sell, price, size, (bids_len + i) as u64);
807            book.add(order, 0, (bids_len + i) as u64, Default::default());
808        }
809
810        log::debug!(
811            "Fetched order book for {} with {} bids and {} asks",
812            instrument_id,
813            resp.bids.len(),
814            resp.asks.len(),
815        );
816
817        Ok(book)
818    }
819}
820
821fn batch_cost(endpoint: &'static str, len: usize) -> Result<u32> {
822    let cost = u32::try_from(len)
823        .map_err(|_| Error::bad_request(format!("{endpoint} batch length exceeds u32")))?;
824    if cost == 0 {
825        return Err(Error::bad_request(format!(
826            "{endpoint} batch must not be empty"
827        )));
828    }
829    Ok(cost)
830}
831
832fn cancel_batch_limit(burst: u32) -> usize {
833    usize::try_from(burst)
834        .unwrap_or(usize::MAX)
835        .min(CLOB_CANCEL_BATCH_LIMIT)
836}
837
838fn canceled_count(response: &BatchCancelResponse) -> u32 {
839    u32::try_from(response.canceled.len()).unwrap_or(u32::MAX)
840}
841
842#[cfg(test)]
843mod tests {
844    use nautilus_model::{
845        enums::{BookType, OrderSide},
846        identifiers::InstrumentId,
847        types::{Price, Quantity},
848    };
849    use rstest::rstest;
850
851    use super::*;
852    use crate::http::models::{ClobBookLevel, ClobBookResponse};
853
854    fn build_book_from_response(resp: &ClobBookResponse) -> OrderBook {
855        let instrument_id = InstrumentId::from("TEST.POLYMARKET");
856        let price_precision = 2u8;
857        let size_precision = 2u8;
858        let mut book = OrderBook::new(instrument_id, BookType::L2_MBP);
859
860        for (i, level) in resp.bids.iter().enumerate() {
861            let price = parse_price(&level.price, price_precision).unwrap();
862            let size = parse_quantity(&level.size, size_precision).unwrap();
863            let order = BookOrder::new(OrderSide::Buy, price, size, i as u64);
864            book.add(order, 0, i as u64, Default::default());
865        }
866
867        let bids_len = resp.bids.len();
868        for (i, level) in resp.asks.iter().enumerate() {
869            let price = parse_price(&level.price, price_precision).unwrap();
870            let size = parse_quantity(&level.size, size_precision).unwrap();
871            let order = BookOrder::new(OrderSide::Sell, price, size, (bids_len + i) as u64);
872            book.add(order, 0, (bids_len + i) as u64, Default::default());
873        }
874
875        book
876    }
877
878    #[rstest]
879    fn test_build_order_book_from_clob_response() {
880        let resp = ClobBookResponse {
881            bids: vec![
882                ClobBookLevel {
883                    price: "0.48".to_string(),
884                    size: "100.00".to_string(),
885                },
886                ClobBookLevel {
887                    price: "0.49".to_string(),
888                    size: "200.00".to_string(),
889                },
890                ClobBookLevel {
891                    price: "0.50".to_string(),
892                    size: "150.00".to_string(),
893                },
894            ],
895            asks: vec![
896                ClobBookLevel {
897                    price: "0.51".to_string(),
898                    size: "120.00".to_string(),
899                },
900                ClobBookLevel {
901                    price: "0.52".to_string(),
902                    size: "180.00".to_string(),
903                },
904            ],
905        };
906
907        let book = build_book_from_response(&resp);
908
909        assert_eq!(book.instrument_id, InstrumentId::from("TEST.POLYMARKET"));
910        assert_eq!(book.book_type, BookType::L2_MBP);
911        assert_eq!(book.best_bid_price(), Some(Price::from("0.50")));
912        assert_eq!(book.best_ask_price(), Some(Price::from("0.51")));
913        assert_eq!(book.best_bid_size(), Some(Quantity::from("150.00")));
914        assert_eq!(book.best_ask_size(), Some(Quantity::from("120.00")));
915        assert_eq!(book.bids(None).count(), 3);
916        assert_eq!(book.asks(None).count(), 2);
917    }
918
919    #[rstest]
920    fn test_build_order_book_empty_response() {
921        let resp = ClobBookResponse {
922            bids: vec![],
923            asks: vec![],
924        };
925
926        let book = build_book_from_response(&resp);
927
928        assert!(book.best_bid_price().is_none());
929        assert!(book.best_ask_price().is_none());
930    }
931
932    #[rstest]
933    fn test_batch_cost_uses_entry_count_and_rejects_empty_batch() {
934        assert_eq!(batch_cost(PATH_POST_ORDERS, 15).unwrap(), 15);
935        assert_eq!(
936            batch_cost(PATH_POST_ORDERS, 0).unwrap_err().to_string(),
937            "bad request: /orders batch must not be empty"
938        );
939    }
940
941    #[rstest]
942    fn test_canceled_count_uses_only_successful_cancellations() {
943        let response = BatchCancelResponse {
944            canceled: vec!["order-1".to_string(), "order-2".to_string()],
945            not_canceled: ahash::AHashMap::from_iter([(
946                "order-3".to_string(),
947                Some("already canceled".to_string()),
948            )]),
949        };
950
951        assert_eq!(canceled_count(&response), 2);
952    }
953
954    #[rstest]
955    #[case::standard(120, 120)]
956    #[case::silver(600, 600)]
957    #[case::gold(1_200, 1_000)]
958    #[case::elite(1_800, 1_000)]
959    fn test_cancel_batch_limit_uses_tier_burst_and_venue_ceiling(
960        #[case] burst: u32,
961        #[case] expected: usize,
962    ) {
963        assert_eq!(cancel_batch_limit(burst), expected);
964    }
965}