Skip to main content

nautilus_okx/python/
config.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//! Python bindings for OKX configuration.
17
18use nautilus_common::python::config_error_to_pyvalue_err;
19use nautilus_core::string::secret::SecretString;
20use nautilus_model::{enums::OmsType, identifiers::AccountId};
21use nautilus_network::websocket::TransportBackend;
22use pyo3::prelude::*;
23
24use crate::{
25    common::enums::{
26        OKXContractType, OKXEnvironment, OKXInstrumentType, OKXMarginMode, OKXRegion, OKXVipLevel,
27    },
28    config::{OKXDataClientConfig, OKXExecutionClientConfig},
29};
30
31#[pymethods]
32#[pyo3_stub_gen::derive::gen_stub_pymethods]
33impl OKXDataClientConfig {
34    /// Configuration for the OKX data client.
35    #[new]
36    #[pyo3(signature = (
37        instrument_types = None,
38        environment = None,
39        region = None,
40        api_key = None,
41        api_secret = None,
42        api_passphrase = None,
43        base_url_http = None,
44        base_url_ws_public = None,
45        base_url_ws_business = None,
46        proxy_url = None,
47        http_timeout_secs = None,
48        max_retries = None,
49        retry_delay_initial_ms = None,
50        retry_delay_max_ms = None,
51        update_instruments_interval_mins = None,
52        book_stale_check_interval_secs = None,
53        book_stale_threshold_secs = None,
54        book_snapshot_timeout_secs = None,
55        vip_level = None,
56        load_spreads = false,
57        transport_backend = None,
58        instrument_families = None,
59        contract_types = None,
60    ))]
61    #[expect(clippy::too_many_arguments)]
62    fn py_new(
63        instrument_types: Option<Vec<OKXInstrumentType>>,
64        environment: Option<OKXEnvironment>,
65        region: Option<OKXRegion>,
66        api_key: Option<String>,
67        api_secret: Option<String>,
68        api_passphrase: Option<String>,
69        base_url_http: Option<String>,
70        base_url_ws_public: Option<String>,
71        base_url_ws_business: Option<String>,
72        proxy_url: Option<String>,
73        http_timeout_secs: Option<u64>,
74        max_retries: Option<u32>,
75        retry_delay_initial_ms: Option<u64>,
76        retry_delay_max_ms: Option<u64>,
77        update_instruments_interval_mins: Option<u64>,
78        book_stale_check_interval_secs: Option<u64>,
79        book_stale_threshold_secs: Option<u64>,
80        book_snapshot_timeout_secs: Option<u64>,
81        vip_level: Option<OKXVipLevel>,
82        load_spreads: bool,
83        transport_backend: Option<TransportBackend>,
84        instrument_families: Option<Vec<String>>,
85        contract_types: Option<Vec<OKXContractType>>,
86    ) -> PyResult<Self> {
87        let defaults = Self::default();
88
89        let config = Self {
90            api_key: api_key.map(SecretString::from),
91            api_secret: api_secret.map(SecretString::from),
92            api_passphrase: api_passphrase.map(SecretString::from),
93            instrument_types: instrument_types.unwrap_or(defaults.instrument_types),
94            contract_types,
95            load_spreads,
96            instrument_families,
97            base_url_http,
98            base_url_ws_public,
99            base_url_ws_business,
100            proxy_url: proxy_url.map(SecretString::from),
101            environment: environment.unwrap_or(defaults.environment),
102            region: region.unwrap_or(defaults.region),
103            http_timeout_secs: http_timeout_secs.unwrap_or(defaults.http_timeout_secs),
104            max_retries: max_retries.unwrap_or(defaults.max_retries),
105            retry_delay_initial_ms: retry_delay_initial_ms
106                .unwrap_or(defaults.retry_delay_initial_ms),
107            retry_delay_max_ms: retry_delay_max_ms.unwrap_or(defaults.retry_delay_max_ms),
108            update_instruments_interval_mins: update_instruments_interval_mins
109                .unwrap_or(defaults.update_instruments_interval_mins),
110            book_stale_check_interval_secs: book_stale_check_interval_secs
111                .unwrap_or(defaults.book_stale_check_interval_secs),
112            book_stale_threshold_secs: book_stale_threshold_secs
113                .unwrap_or(defaults.book_stale_threshold_secs),
114            book_snapshot_timeout_secs: book_snapshot_timeout_secs
115                .unwrap_or(defaults.book_snapshot_timeout_secs),
116            vip_level,
117            transport_backend: transport_backend.unwrap_or(defaults.transport_backend),
118        };
119
120        config.validate().map_err(config_error_to_pyvalue_err)?;
121        Ok(config)
122    }
123
124    #[getter]
125    const fn has_proxy_url(&self) -> bool {
126        self.proxy_url.is_some()
127    }
128
129    fn __repr__(&self) -> String {
130        stringify!(OKXDataClientConfig).to_string()
131    }
132}
133
134#[pymethods]
135#[pyo3_stub_gen::derive::gen_stub_pymethods]
136impl OKXExecutionClientConfig {
137    /// Configuration for the OKX execution client.
138    #[new]
139    #[pyo3(signature = (
140        account_id,
141        instrument_types = None,
142        environment = None,
143        region = None,
144        api_key = None,
145        api_secret = None,
146        api_passphrase = None,
147        base_url_http = None,
148        base_url_ws_private = None,
149        base_url_ws_business = None,
150        proxy_url = None,
151        http_timeout_secs = None,
152        max_retries = None,
153        retry_delay_initial_ms = None,
154        retry_delay_max_ms = None,
155        margin_mode = None,
156        load_spreads = false,
157        auth_timeout_secs = None,
158        transport_backend = None,
159        spot_trade_quote_ccy = None,
160        oms_type = None,
161        max_reconciliation_history_pages = None,
162        instrument_families = None,
163        contract_types = None,
164        use_spot_margin = false,
165        order_request_ttl_ms = None,
166        use_spot_position_reports = false,
167        spot_positions_quote_currency = None,
168    ))]
169    #[expect(clippy::too_many_arguments)]
170    fn py_new(
171        account_id: AccountId,
172        instrument_types: Option<Vec<OKXInstrumentType>>,
173        environment: Option<OKXEnvironment>,
174        region: Option<OKXRegion>,
175        api_key: Option<String>,
176        api_secret: Option<String>,
177        api_passphrase: Option<String>,
178        base_url_http: Option<String>,
179        base_url_ws_private: Option<String>,
180        base_url_ws_business: Option<String>,
181        proxy_url: Option<String>,
182        http_timeout_secs: Option<u64>,
183        max_retries: Option<u32>,
184        retry_delay_initial_ms: Option<u64>,
185        retry_delay_max_ms: Option<u64>,
186        margin_mode: Option<OKXMarginMode>,
187        load_spreads: bool,
188        auth_timeout_secs: Option<u64>,
189        transport_backend: Option<TransportBackend>,
190        spot_trade_quote_ccy: Option<String>,
191        oms_type: Option<OmsType>,
192        max_reconciliation_history_pages: Option<u32>,
193        instrument_families: Option<Vec<String>>,
194        contract_types: Option<Vec<OKXContractType>>,
195        use_spot_margin: bool,
196        order_request_ttl_ms: Option<u64>,
197        use_spot_position_reports: bool,
198        spot_positions_quote_currency: Option<String>,
199    ) -> PyResult<Self> {
200        let defaults = Self::default();
201
202        let config = Self {
203            account_id,
204            oms_type,
205            api_key: api_key.map(SecretString::from),
206            api_secret: api_secret.map(SecretString::from),
207            api_passphrase: api_passphrase.map(SecretString::from),
208            instrument_types: instrument_types.unwrap_or(defaults.instrument_types),
209            contract_types,
210            instrument_families,
211            base_url_http,
212            base_url_ws_private,
213            base_url_ws_business,
214            proxy_url: proxy_url.map(SecretString::from),
215            environment: environment.unwrap_or(defaults.environment),
216            region: region.unwrap_or(defaults.region),
217            http_timeout_secs: http_timeout_secs.unwrap_or(defaults.http_timeout_secs),
218            use_mm_mass_cancel: defaults.use_mm_mass_cancel,
219            max_retries: max_retries.unwrap_or(defaults.max_retries),
220            retry_delay_initial_ms: retry_delay_initial_ms
221                .unwrap_or(defaults.retry_delay_initial_ms),
222            retry_delay_max_ms: retry_delay_max_ms.unwrap_or(defaults.retry_delay_max_ms),
223            margin_mode,
224            load_spreads,
225            use_spot_margin,
226            auth_timeout_secs,
227            transport_backend: transport_backend.unwrap_or(defaults.transport_backend),
228            spot_trade_quote_ccy,
229            use_spot_position_reports,
230            spot_positions_quote_currency: spot_positions_quote_currency
231                .unwrap_or(defaults.spot_positions_quote_currency),
232            max_reconciliation_history_pages,
233            order_request_ttl_ms,
234        };
235
236        config.validate().map_err(config_error_to_pyvalue_err)?;
237        Ok(config)
238    }
239
240    #[getter]
241    const fn has_proxy_url(&self) -> bool {
242        self.proxy_url.is_some()
243    }
244
245    fn __repr__(&self) -> String {
246        stringify!(OKXExecutionClientConfig).to_string()
247    }
248}
249
250#[cfg(test)]
251mod tests {
252    use pyo3::{
253        Python,
254        exceptions::{PyTypeError, PyValueError},
255        types::{PyDict, PyList},
256    };
257    use rstest::rstest;
258
259    use super::*;
260
261    #[rstest]
262    #[case(false)]
263    #[case(true)]
264    fn test_python_does_not_expose_mmp_only_mass_cancel(#[case] value: bool) {
265        Python::initialize();
266        Python::attach(|py| {
267            let kwargs = PyDict::new(py);
268            kwargs
269                .set_item(
270                    "account_id",
271                    Py::new(py, AccountId::from("OKX-MMP")).unwrap(),
272                )
273                .unwrap();
274            kwargs.set_item("use_mm_mass_cancel", value).unwrap();
275            let error = py
276                .get_type::<OKXExecutionClientConfig>()
277                .call((), Some(&kwargs))
278                .unwrap_err();
279            assert!(error.is_instance_of::<PyTypeError>(py));
280            assert_eq!(
281                error.value(py).str().unwrap().to_str().unwrap(),
282                "OKXExecutionClientConfig.__new__() got an unexpected keyword argument 'use_mm_mass_cancel'"
283            );
284        });
285    }
286
287    #[rstest]
288    #[case::data(false)]
289    #[case::execution(true)]
290    fn test_python_config_selection_parity(#[case] execution: bool) {
291        Python::initialize();
292        Python::attach(|py| {
293            let kwargs = PyDict::new(py);
294            if execution {
295                kwargs
296                    .set_item(
297                        "account_id",
298                        Py::new(py, AccountId::from("OKX-PARITY")).unwrap(),
299                    )
300                    .unwrap();
301                kwargs.set_item("use_spot_margin", true).unwrap();
302            }
303
304            kwargs
305                .set_item(
306                    "instrument_types",
307                    vec![Py::new(py, OKXInstrumentType::Option).unwrap()],
308                )
309                .unwrap();
310            kwargs
311                .set_item("instrument_families", vec!["ETH-USD"])
312                .unwrap();
313            kwargs
314                .set_item(
315                    "contract_types",
316                    vec![Py::new(py, OKXContractType::Inverse).unwrap()],
317                )
318                .unwrap();
319
320            let config_type = if execution {
321                py.get_type::<OKXExecutionClientConfig>()
322            } else {
323                py.get_type::<OKXDataClientConfig>()
324            };
325
326            let config = config_type.call((), Some(&kwargs)).unwrap();
327            assert_eq!(
328                config
329                    .getattr("instrument_types")
330                    .unwrap()
331                    .extract::<Vec<OKXInstrumentType>>()
332                    .unwrap(),
333                vec![OKXInstrumentType::Option]
334            );
335            assert_eq!(
336                config
337                    .getattr("instrument_families")
338                    .unwrap()
339                    .extract::<Vec<String>>()
340                    .unwrap(),
341                vec!["ETH-USD"]
342            );
343            assert_eq!(
344                config
345                    .getattr("contract_types")
346                    .unwrap()
347                    .extract::<Vec<OKXContractType>>()
348                    .unwrap(),
349                vec![OKXContractType::Inverse]
350            );
351
352            if execution {
353                assert!(
354                    config
355                        .getattr("use_spot_margin")
356                        .unwrap()
357                        .extract::<bool>()
358                        .unwrap()
359                );
360                assert!(!config.hasattr("use_mm_mass_cancel").unwrap());
361            }
362        });
363    }
364
365    #[rstest]
366    #[case::data(false)]
367    #[case::execution(true)]
368    fn test_python_config_duplicate_types(
369        #[case] execution: bool,
370        #[values(false, true)] duplicate: bool,
371    ) {
372        Python::initialize();
373        Python::attach(|py| {
374            let values = if duplicate {
375                vec![
376                    OKXInstrumentType::Swap,
377                    OKXInstrumentType::Spot,
378                    OKXInstrumentType::Swap,
379                ]
380            } else {
381                vec![OKXInstrumentType::Swap, OKXInstrumentType::Spot]
382            };
383
384            let objects: Vec<_> = values
385                .iter()
386                .map(|value| Py::new(py, *value).unwrap())
387                .collect();
388            let list = PyList::new(py, objects).unwrap();
389            let kwargs = PyDict::new(py);
390            kwargs.set_item("instrument_types", list).unwrap();
391            if execution {
392                kwargs
393                    .set_item(
394                        "account_id",
395                        Py::new(py, AccountId::from("OKX-001")).unwrap(),
396                    )
397                    .unwrap();
398            }
399
400            let config_type = if execution {
401                py.get_type::<OKXExecutionClientConfig>()
402            } else {
403                py.get_type::<OKXDataClientConfig>()
404            };
405
406            let result = config_type.call((), Some(&kwargs));
407            if duplicate {
408                let error = result.unwrap_err();
409                assert!(error.is_instance_of::<PyValueError>(py));
410                assert_eq!(
411                    error.value(py).str().unwrap().to_str().unwrap(),
412                    "duplicate instrument_types"
413                );
414            } else {
415                let config = result.unwrap();
416                let actual: Vec<OKXInstrumentType> = config
417                    .getattr("instrument_types")
418                    .unwrap()
419                    .extract()
420                    .unwrap();
421                assert_eq!(actual, values);
422            }
423        });
424    }
425
426    #[rstest]
427    fn test_data_config_py_new() {
428        let config = OKXDataClientConfig::py_new(
429            None,
430            None,
431            None,
432            None,
433            None,
434            None,
435            None,
436            None,
437            None,
438            None,
439            None,
440            None,
441            None,
442            None,
443            None,
444            None,
445            None,
446            None,
447            None,
448            true,
449            None,
450            Some(vec!["BTC-USD".to_string()]),
451            None,
452        )
453        .unwrap();
454
455        assert_eq!(
456            config.instrument_families,
457            Some(vec!["BTC-USD".to_string()]),
458        );
459        assert!(config.load_spreads);
460        assert_eq!(config.book_stale_check_interval_secs, 5);
461        assert_eq!(config.book_stale_threshold_secs, 30);
462        assert_eq!(config.book_snapshot_timeout_secs, 10);
463    }
464
465    #[rstest]
466    #[case(None)]
467    #[case(Some(0))]
468    #[case(Some(2))]
469    #[case(Some(51))]
470    #[case(Some(u32::MAX))]
471    fn test_exec_config_python_history_pages(#[case] pages: Option<u32>) {
472        Python::initialize();
473        Python::attach(|py| {
474            let kwargs = PyDict::new(py);
475            kwargs
476                .set_item(
477                    "account_id",
478                    Py::new(py, AccountId::from("OKX-001")).unwrap(),
479                )
480                .unwrap();
481
482            if let Some(pages) = pages {
483                kwargs
484                    .set_item("max_reconciliation_history_pages", pages)
485                    .unwrap();
486            }
487
488            let config = py
489                .get_type::<OKXExecutionClientConfig>()
490                .call((), Some(&kwargs))
491                .unwrap();
492            let actual: Option<u32> = config
493                .getattr("max_reconciliation_history_pages")
494                .unwrap()
495                .extract()
496                .unwrap();
497
498            assert_eq!(actual, pages);
499        });
500    }
501
502    #[rstest]
503    fn test_exec_config_py_new_load_spreads() {
504        let config = OKXExecutionClientConfig::py_new(
505            AccountId::from("OKX-001"),
506            None,
507            None,
508            None,
509            None,
510            None,
511            None,
512            None,
513            None,
514            None,
515            None,
516            None,
517            None,
518            None,
519            None,
520            None,
521            true,
522            None,
523            None,
524            Some("USD".to_string()),
525            Some(OmsType::Hedging),
526            Some(7),
527            None,
528            None,
529            false,
530            Some(5_000),
531            true,
532            Some("USDC".to_string()),
533        )
534        .unwrap();
535
536        assert!(config.load_spreads);
537        assert_eq!(config.auth_timeout_secs, None);
538        assert_eq!(config.spot_trade_quote_ccy.as_deref(), Some("USD"));
539        assert_eq!(config.oms_type, Some(OmsType::Hedging));
540        assert_eq!(config.max_reconciliation_history_pages, Some(7));
541        assert_eq!(config.order_request_ttl_ms, Some(5_000));
542        assert!(config.use_spot_position_reports);
543        assert_eq!(config.spot_positions_quote_currency, "USDC");
544    }
545
546    #[rstest]
547    fn test_exec_config_python_spot_position_reports() {
548        Python::initialize();
549        Python::attach(|py| {
550            let kwargs = PyDict::new(py);
551            kwargs
552                .set_item(
553                    "account_id",
554                    Py::new(py, AccountId::from("OKX-001")).unwrap(),
555                )
556                .unwrap();
557            let config_type = py.get_type::<OKXExecutionClientConfig>();
558
559            let defaults = config_type.call((), Some(&kwargs)).unwrap();
560            kwargs.set_item("use_spot_position_reports", true).unwrap();
561            kwargs
562                .set_item("spot_positions_quote_currency", "USDC")
563                .unwrap();
564            let config = config_type.call((), Some(&kwargs)).unwrap();
565            kwargs.set_item("use_spot_margin", true).unwrap();
566            let margin_config = config_type.call((), Some(&kwargs)).unwrap();
567            kwargs
568                .set_item("spot_positions_quote_currency", "usdc")
569                .unwrap();
570            let err = config_type.call((), Some(&kwargs)).unwrap_err();
571
572            let read = |config: &Bound<'_, PyAny>| {
573                (
574                    config
575                        .getattr("use_spot_position_reports")
576                        .unwrap()
577                        .extract::<bool>()
578                        .unwrap(),
579                    config
580                        .getattr("spot_positions_quote_currency")
581                        .unwrap()
582                        .extract::<String>()
583                        .unwrap(),
584                )
585            };
586
587            assert_eq!(read(&defaults), (false, "USDT".to_string()));
588            assert_eq!(read(&config), (true, "USDC".to_string()));
589            assert_eq!(read(&margin_config), (true, "USDC".to_string()));
590            assert!(
591                margin_config
592                    .getattr("use_spot_margin")
593                    .unwrap()
594                    .extract::<bool>()
595                    .unwrap()
596            );
597            assert!(err.is_instance_of::<PyValueError>(py), "{err}");
598            assert!(
599                err.to_string().contains("spot_positions_quote_currency"),
600                "{err}"
601            );
602        });
603    }
604
605    #[rstest]
606    fn test_exec_config_python_rejects_zero_order_request_ttl() {
607        Python::initialize();
608        Python::attach(|py| {
609            let kwargs = PyDict::new(py);
610            kwargs
611                .set_item(
612                    "account_id",
613                    Py::new(py, AccountId::from("OKX-001")).unwrap(),
614                )
615                .unwrap();
616            kwargs.set_item("order_request_ttl_ms", 0u64).unwrap();
617
618            let err = py
619                .get_type::<OKXExecutionClientConfig>()
620                .call((), Some(&kwargs))
621                .unwrap_err();
622
623            assert!(err.is_instance_of::<PyValueError>(py), "{err}");
624            assert!(err.to_string().contains("order_request_ttl_ms"), "{err}");
625        });
626    }
627}