Skip to main content

nautilus_polymarket/
factories.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//! Factory functions for creating Polymarket clients and components.
17
18#[cfg(test)]
19#[path = "../tests/integration/harness/proxy.rs"]
20pub(crate) mod proxy;
21
22use std::{any::Any, cell::RefCell, rc::Rc, sync::Arc};
23
24use nautilus_common::{
25    cache::CacheView,
26    clients::{DataClient, ExecutionClient},
27    clock::Clock,
28    factories::{ClientConfig, DataClientFactory, ExecutionClientFactory},
29};
30use nautilus_live::ExecutionClientCore;
31use nautilus_model::{
32    enums::{AccountType, OmsType},
33    identifiers::{ClientId, TraderId},
34};
35use nautilus_network::retry::RetryConfig;
36
37use crate::{
38    common::consts::{POLYMARKET, POLYMARKET_VENUE},
39    config::{PolymarketDataClientConfig, PolymarketExecutionClientConfig},
40    data::PolymarketDataClient,
41    execution::PolymarketExecutionClient,
42    http::{
43        clob::PolymarketClobPublicClient, data_api::PolymarketDataApiHttpClient,
44        gamma::PolymarketGammaHttpClient,
45    },
46    websocket::pool::PolymarketMarketConnectionPool,
47};
48
49impl ClientConfig for PolymarketDataClientConfig {
50    fn as_any(&self) -> &dyn Any {
51        self
52    }
53}
54
55/// Factory for creating Polymarket data clients.
56#[cfg_attr(
57    feature = "python",
58    pyo3::pyclass(module = "nautilus_trader.adapters.polymarket", from_py_object)
59)]
60#[cfg_attr(
61    feature = "python",
62    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.polymarket")
63)]
64#[derive(Debug, Clone)]
65pub struct PolymarketDataClientFactory;
66
67impl DataClientFactory for PolymarketDataClientFactory {
68    fn create(
69        &self,
70        name: &str,
71        config: &dyn ClientConfig,
72        _cache: CacheView,
73        _clock: Rc<RefCell<dyn Clock>>,
74    ) -> anyhow::Result<Box<dyn DataClient>> {
75        let polymarket_config = config
76            .as_any()
77            .downcast_ref::<PolymarketDataClientConfig>()
78            .ok_or_else(|| {
79                anyhow::anyhow!(
80                    "Invalid config type for PolymarketDataClientFactory. Expected PolymarketDataClientConfig, was {config:?}",
81                )
82            })?;
83
84        Ok(Box::new(Self::create_client(name, polymarket_config)?))
85    }
86
87    fn name(&self) -> &'static str {
88        POLYMARKET
89    }
90
91    fn config_type(&self) -> &'static str {
92        "PolymarketDataClientConfig"
93    }
94}
95
96impl PolymarketDataClientFactory {
97    fn create_client(
98        name: &str,
99        polymarket_config: &PolymarketDataClientConfig,
100    ) -> anyhow::Result<PolymarketDataClient> {
101        polymarket_config.validate()?;
102
103        let client_id = ClientId::from(name);
104        let proxy_url = polymarket_config.validated_proxy_url()?;
105        // Fail fast on malformed credentials; the client resolves them again for its feed.
106        polymarket_config.polybolt_credential()?;
107
108        let gamma_client = PolymarketGammaHttpClient::new_with_proxy(
109            Some(polymarket_config.gamma_url()),
110            polymarket_config.http_timeout_secs,
111            RetryConfig {
112                max_retries: 10,
113                initial_delay_ms: 5_000,
114                max_delay_ms: 30_000,
115                backoff_factor: 1.5,
116                jitter_ms: 2_000,
117                operation_timeout_ms: None,
118                immediate_first: true,
119                max_elapsed_ms: Some(300_000),
120            },
121            proxy_url.clone(),
122        )?;
123
124        let clob_public_client = PolymarketClobPublicClient::new_with_proxy(
125            polymarket_config.base_url_http.clone(),
126            polymarket_config.http_timeout_secs,
127            proxy_url.clone(),
128        )?;
129
130        let data_api_client = PolymarketDataApiHttpClient::new_with_proxy(
131            Some(polymarket_config.data_api_url()),
132            polymarket_config.http_timeout_secs,
133            proxy_url.clone(),
134        )?;
135
136        let ws_client = PolymarketMarketConnectionPool::new_with_proxy(
137            polymarket_config.base_url_ws.clone(),
138            polymarket_config.subscribe_new_markets,
139            polymarket_config.transport_backend,
140            polymarket_config.ws_max_subscriptions,
141            proxy_url.clone(),
142        );
143
144        let mut client = PolymarketDataClient::new_with_proxy(
145            client_id,
146            polymarket_config.clone(),
147            gamma_client,
148            clob_public_client,
149            data_api_client,
150            ws_client,
151            proxy_url,
152        )?;
153
154        for filter in &polymarket_config.filters {
155            client.add_instrument_filter(Arc::clone(filter));
156        }
157
158        Ok(client)
159    }
160}
161
162impl ClientConfig for PolymarketExecutionClientConfig {
163    fn as_any(&self) -> &dyn Any {
164        self
165    }
166}
167
168/// Factory for creating Polymarket execution clients.
169#[cfg_attr(
170    feature = "python",
171    pyo3::pyclass(module = "nautilus_trader.adapters.polymarket", from_py_object)
172)]
173#[cfg_attr(
174    feature = "python",
175    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.adapters.polymarket")
176)]
177#[derive(Debug, Clone)]
178pub struct PolymarketExecutionClientFactory;
179
180impl ExecutionClientFactory for PolymarketExecutionClientFactory {
181    fn create(
182        &self,
183        trader_id: TraderId,
184        name: &str,
185        config: &dyn ClientConfig,
186        cache: CacheView,
187        _clock: Rc<RefCell<dyn Clock>>,
188    ) -> anyhow::Result<Box<dyn ExecutionClient>> {
189        let polymarket_config = config
190            .as_any()
191            .downcast_ref::<PolymarketExecutionClientConfig>()
192            .ok_or_else(|| {
193                anyhow::anyhow!(
194                    "Invalid config type for PolymarketExecutionClientFactory. Expected PolymarketExecutionClientConfig, was {config:?}",
195                )
196            })?
197            .clone();
198
199        let oms_type = OmsType::Netting;
200        let account_type = AccountType::Cash;
201
202        let client_id = ClientId::from(name);
203        let core = ExecutionClientCore::new(
204            trader_id,
205            client_id,
206            *POLYMARKET_VENUE,
207            oms_type,
208            polymarket_config.account_id,
209            account_type,
210            None, // base_currency
211            cache,
212        );
213
214        let client = PolymarketExecutionClient::new(core, polymarket_config)?;
215
216        Ok(Box::new(client))
217    }
218
219    fn name(&self) -> &'static str {
220        POLYMARKET
221    }
222
223    fn config_type(&self) -> &'static str {
224        "PolymarketExecutionClientConfig"
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use std::{cell::RefCell, rc::Rc, time::Duration};
231
232    use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
233    use nautilus_common::{
234        cache::Cache,
235        clock::VirtualClock,
236        config::ConfigError,
237        factories::{ClientConfig, DataClientFactory, ExecutionClientFactory},
238        live::runner::replace_data_event_sender,
239        messages::DataEvent,
240        testing::wait_until_async,
241    };
242    use rstest::rstest;
243
244    use super::{proxy::spawn_rejecting_proxy, *};
245    use crate::config::{PolymarketDataClientConfig, PolymarketExecutionClientConfig};
246
247    #[derive(Debug)]
248    struct WrongConfig;
249
250    impl ClientConfig for WrongConfig {
251        fn as_any(&self) -> &dyn std::any::Any {
252            self
253        }
254    }
255
256    #[rstest]
257    fn test_polymarket_data_client_factory_creation() {
258        let factory = PolymarketDataClientFactory;
259        assert_eq!(factory.name(), POLYMARKET);
260        assert_eq!(factory.config_type(), "PolymarketDataClientConfig");
261    }
262
263    #[rstest]
264    fn test_polymarket_data_client_config_implements_client_config() {
265        let config = PolymarketDataClientConfig::default();
266        let boxed_config: Box<dyn ClientConfig> = Box::new(config);
267        let downcasted = boxed_config
268            .as_any()
269            .downcast_ref::<PolymarketDataClientConfig>();
270        assert!(downcasted.is_some());
271    }
272
273    #[rstest]
274    fn test_polymarket_data_client_factory_rejects_wrong_config_type() {
275        let factory = PolymarketDataClientFactory;
276        let wrong_config = WrongConfig;
277        let cache = Rc::new(RefCell::new(Cache::default()));
278        let clock = Rc::new(RefCell::new(VirtualClock::new()));
279
280        let result = factory.create(POLYMARKET, &wrong_config, cache.into(), clock);
281        assert!(result.is_err());
282        assert!(
283            result
284                .err()
285                .unwrap()
286                .to_string()
287                .contains("Invalid config type")
288        );
289    }
290
291    #[rstest]
292    fn test_polymarket_execution_client_factory_creation() {
293        let factory = PolymarketExecutionClientFactory;
294        assert_eq!(factory.name(), POLYMARKET);
295        assert_eq!(factory.config_type(), "PolymarketExecutionClientConfig");
296    }
297
298    #[rstest]
299    fn test_polymarket_exec_client_config_implements_client_config() {
300        let config = PolymarketExecutionClientConfig::default();
301        let boxed_config: Box<dyn ClientConfig> = Box::new(config);
302        let downcasted = boxed_config
303            .as_any()
304            .downcast_ref::<PolymarketExecutionClientConfig>();
305        assert!(downcasted.is_some());
306    }
307
308    #[rstest]
309    fn test_polymarket_execution_client_factory_rejects_wrong_config_type() {
310        let factory = PolymarketExecutionClientFactory;
311        let wrong_config = WrongConfig;
312        let cache = Rc::new(RefCell::new(Cache::default()));
313
314        let result = factory.create(
315            TraderId::from("TRADER-001"),
316            POLYMARKET,
317            &wrong_config,
318            cache.into(),
319            Rc::new(RefCell::new(VirtualClock::new())),
320        );
321        assert!(result.is_err());
322        assert!(
323            result
324                .err()
325                .unwrap()
326                .to_string()
327                .contains("Invalid config type")
328        );
329    }
330
331    #[rstest]
332    fn data_factory_invalid_proxy_error_redacts_credentials() {
333        const SECRET: &str = "data-factory-proxy-secret";
334        let factory = PolymarketDataClientFactory;
335        let config = PolymarketDataClientConfig {
336            proxy_url: Some(format!("http://proxy-user:{SECRET}@[::1").into()),
337            ..PolymarketDataClientConfig::default()
338        };
339        let cache = Rc::new(RefCell::new(Cache::default()));
340        let clock = Rc::new(RefCell::new(VirtualClock::new()));
341        let Err(e) = factory.create(POLYMARKET, &config, cache.into(), clock) else {
342            panic!("malformed proxy URL should fail");
343        };
344
345        assert!(!e.to_string().contains(SECRET));
346    }
347
348    #[rstest]
349    fn execution_factory_invalid_proxy_error_redacts_credentials() {
350        const SECRET: &str = "execution-factory-proxy-secret";
351        let factory = PolymarketExecutionClientFactory;
352        let config = PolymarketExecutionClientConfig {
353            proxy_url: Some(format!("http://proxy-user:{SECRET}@[::1").into()),
354            ..PolymarketExecutionClientConfig::default()
355        };
356        let cache = Rc::new(RefCell::new(Cache::default()));
357        let Err(e) = factory.create(
358            TraderId::from("TRADER-001"),
359            POLYMARKET,
360            &config,
361            cache.into(),
362            Rc::new(RefCell::new(VirtualClock::new())),
363        ) else {
364            panic!("malformed proxy URL should fail");
365        };
366
367        assert!(!e.to_string().contains(SECRET));
368    }
369
370    #[rstest]
371    #[tokio::test]
372    async fn data_factory_propagates_configured_proxy() {
373        const USERNAME: &str = "proxytest";
374        const SECRET: &str = "http-client-proxy-secret";
375        let (proxy_addr, requests) = spawn_rejecting_proxy(6).await;
376        let proxy_url = format!("http://{USERNAME}:{SECRET}@{proxy_addr}");
377        let (data_tx, _data_rx) = tokio::sync::mpsc::unbounded_channel::<DataEvent>();
378        replace_data_event_sender(data_tx);
379        let config = PolymarketDataClientConfig {
380            base_url_http: Some("https://clob-public.fixture".to_string()),
381            base_url_ws: Some("wss://market.fixture/ws".to_string()),
382            base_url_gamma: Some("https://gamma.fixture".to_string()),
383            base_url_data_api: Some("https://data.fixture".to_string()),
384            base_url_reference_prices: Some("wss://polybolt.fixture/ws".to_string()),
385            proxy_url: Some(proxy_url.clone().into()),
386            http_timeout_secs: 2,
387            ..PolymarketDataClientConfig::default()
388        };
389        let client = PolymarketDataClientFactory::create_client(POLYMARKET, &config).unwrap();
390
391        let mut gamma = Box::pin(client.provider().http_client().request_tags());
392
393        // Advance backoff after completed CONNECT attempts; keep socket I/O on the real clock
394        for completed in 1..=3 {
395            tokio::select! {
396                biased;
397                result = &mut gamma => panic!("Gamma retries ended early: {result:?}"),
398                () = wait_until_async(
399                    || async { requests.lock().await.len() >= completed },
400                    Duration::from_secs(5),
401                ) => {}
402            }
403            assert!(futures_util::poll!(&mut gamma).is_pending());
404            tokio::time::pause();
405            tokio::time::advance(Duration::from_secs(10)).await;
406            tokio::time::resume();
407        }
408
409        let errors = [
410            tokio::time::timeout(Duration::from_secs(5), gamma)
411                .await
412                .unwrap()
413                .unwrap_err()
414                .to_string(),
415            client
416                .clob_public_client()
417                .get_book("public-token")
418                .await
419                .unwrap_err()
420                .to_string(),
421            client
422                .data_api_client()
423                .get_positions("0x0000000000000000000000000000000000000002")
424                .await
425                .unwrap_err()
426                .to_string(),
427        ];
428        let configured_proxy = client.config().validated_proxy_url().unwrap().unwrap();
429
430        assert_eq!(client.ws_client().proxy_url().unwrap().expose(), proxy_url);
431        assert_eq!(
432            client.polybolt_feed().proxy_url().unwrap().expose(),
433            proxy_url
434        );
435        assert_eq!(configured_proxy.expose(), proxy_url);
436
437        let requests = requests.lock().await;
438        let request_lines = requests
439            .iter()
440            .map(|request| request.lines().next().unwrap().to_string())
441            .collect::<Vec<_>>();
442        let expected_auth = format!("Basic {}", BASE64.encode(format!("{USERNAME}:{SECRET}")));
443
444        assert_eq!(
445            request_lines,
446            std::iter::repeat_n("CONNECT gamma.fixture:443 HTTP/1.1", 4)
447                .chain([
448                    "CONNECT clob-public.fixture:443 HTTP/1.1",
449                    "CONNECT data.fixture:443 HTTP/1.1",
450                ])
451                .collect::<Vec<_>>()
452        );
453
454        for request in requests.iter() {
455            let auth = request
456                .lines()
457                .find_map(|line| {
458                    let (name, value) = line.split_once(':')?;
459                    name.eq_ignore_ascii_case("proxy-authorization")
460                        .then_some(value.trim())
461                })
462                .expect("Proxy-Authorization header");
463            assert_eq!(auth, expected_auth);
464        }
465
466        for error in errors {
467            assert!(!error.contains(SECRET));
468            assert!(!error.contains(&BASE64.encode(SECRET)));
469            assert!(!error.contains(&expected_auth));
470        }
471    }
472
473    #[rstest]
474    fn test_factory_rejects_duplicate_selections_before_setup() {
475        let config = PolymarketDataClientConfig {
476            instrument_config: Some(crate::config::PolymarketInstrumentProviderConfig {
477                event_slugs: Some(vec!["event-one".to_string(), "event-one".to_string()]),
478                ..Default::default()
479            }),
480            ..Default::default()
481        };
482
483        let cache = Rc::new(RefCell::new(Cache::default()));
484        let clock = Rc::new(RefCell::new(VirtualClock::new()));
485        let error = PolymarketDataClientFactory
486            .create("POLYMARKET", &config, cache.into(), clock)
487            .err()
488            .expect("duplicate config must fail before client setup");
489
490        assert_eq!(
491            error.downcast_ref::<ConfigError>(),
492            Some(&ConfigError::duplicate("event_slugs", None))
493        );
494    }
495}