1use 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 #[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 #[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 ))]
166 #[expect(clippy::too_many_arguments)]
167 fn py_new(
168 account_id: AccountId,
169 instrument_types: Option<Vec<OKXInstrumentType>>,
170 environment: Option<OKXEnvironment>,
171 region: Option<OKXRegion>,
172 api_key: Option<String>,
173 api_secret: Option<String>,
174 api_passphrase: Option<String>,
175 base_url_http: Option<String>,
176 base_url_ws_private: Option<String>,
177 base_url_ws_business: Option<String>,
178 proxy_url: Option<String>,
179 http_timeout_secs: Option<u64>,
180 max_retries: Option<u32>,
181 retry_delay_initial_ms: Option<u64>,
182 retry_delay_max_ms: Option<u64>,
183 margin_mode: Option<OKXMarginMode>,
184 load_spreads: bool,
185 auth_timeout_secs: Option<u64>,
186 transport_backend: Option<TransportBackend>,
187 spot_trade_quote_ccy: Option<String>,
188 oms_type: Option<OmsType>,
189 max_reconciliation_history_pages: Option<u32>,
190 instrument_families: Option<Vec<String>>,
191 contract_types: Option<Vec<OKXContractType>>,
192 use_spot_margin: bool,
193 ) -> PyResult<Self> {
194 let defaults = Self::default();
195
196 let config = Self {
197 account_id,
198 oms_type,
199 api_key: api_key.map(SecretString::from),
200 api_secret: api_secret.map(SecretString::from),
201 api_passphrase: api_passphrase.map(SecretString::from),
202 instrument_types: instrument_types.unwrap_or(defaults.instrument_types),
203 contract_types,
204 instrument_families,
205 base_url_http,
206 base_url_ws_private,
207 base_url_ws_business,
208 proxy_url: proxy_url.map(SecretString::from),
209 environment: environment.unwrap_or(defaults.environment),
210 region: region.unwrap_or(defaults.region),
211 http_timeout_secs: http_timeout_secs.unwrap_or(defaults.http_timeout_secs),
212 use_mm_mass_cancel: defaults.use_mm_mass_cancel,
213 max_retries: max_retries.unwrap_or(defaults.max_retries),
214 retry_delay_initial_ms: retry_delay_initial_ms
215 .unwrap_or(defaults.retry_delay_initial_ms),
216 retry_delay_max_ms: retry_delay_max_ms.unwrap_or(defaults.retry_delay_max_ms),
217 margin_mode,
218 load_spreads,
219 use_spot_margin,
220 auth_timeout_secs,
221 transport_backend: transport_backend.unwrap_or(defaults.transport_backend),
222 spot_trade_quote_ccy,
223 max_reconciliation_history_pages,
224 };
225
226 config.validate().map_err(config_error_to_pyvalue_err)?;
227 Ok(config)
228 }
229
230 #[getter]
231 const fn has_proxy_url(&self) -> bool {
232 self.proxy_url.is_some()
233 }
234
235 fn __repr__(&self) -> String {
236 stringify!(OKXExecutionClientConfig).to_string()
237 }
238}
239
240#[cfg(test)]
241mod tests {
242 use pyo3::{
243 Python,
244 exceptions::{PyTypeError, PyValueError},
245 types::{PyDict, PyList},
246 };
247 use rstest::rstest;
248
249 use super::*;
250
251 #[rstest]
252 #[case(false)]
253 #[case(true)]
254 fn test_python_does_not_expose_mmp_only_mass_cancel(#[case] value: bool) {
255 Python::initialize();
256 Python::attach(|py| {
257 let kwargs = PyDict::new(py);
258 kwargs
259 .set_item(
260 "account_id",
261 Py::new(py, AccountId::from("OKX-MMP")).unwrap(),
262 )
263 .unwrap();
264 kwargs.set_item("use_mm_mass_cancel", value).unwrap();
265 let error = py
266 .get_type::<OKXExecutionClientConfig>()
267 .call((), Some(&kwargs))
268 .unwrap_err();
269 assert!(error.is_instance_of::<PyTypeError>(py));
270 assert_eq!(
271 error.value(py).str().unwrap().to_str().unwrap(),
272 "OKXExecutionClientConfig.__new__() got an unexpected keyword argument 'use_mm_mass_cancel'"
273 );
274 });
275 }
276
277 #[rstest]
278 #[case::data(false)]
279 #[case::execution(true)]
280 fn test_python_config_selection_parity(#[case] execution: bool) {
281 Python::initialize();
282 Python::attach(|py| {
283 let kwargs = PyDict::new(py);
284 if execution {
285 kwargs
286 .set_item(
287 "account_id",
288 Py::new(py, AccountId::from("OKX-PARITY")).unwrap(),
289 )
290 .unwrap();
291 kwargs.set_item("use_spot_margin", true).unwrap();
292 }
293
294 kwargs
295 .set_item(
296 "instrument_types",
297 vec![Py::new(py, OKXInstrumentType::Option).unwrap()],
298 )
299 .unwrap();
300 kwargs
301 .set_item("instrument_families", vec!["ETH-USD"])
302 .unwrap();
303 kwargs
304 .set_item(
305 "contract_types",
306 vec![Py::new(py, OKXContractType::Inverse).unwrap()],
307 )
308 .unwrap();
309
310 let config_type = if execution {
311 py.get_type::<OKXExecutionClientConfig>()
312 } else {
313 py.get_type::<OKXDataClientConfig>()
314 };
315
316 let config = config_type.call((), Some(&kwargs)).unwrap();
317 assert_eq!(
318 config
319 .getattr("instrument_types")
320 .unwrap()
321 .extract::<Vec<OKXInstrumentType>>()
322 .unwrap(),
323 vec![OKXInstrumentType::Option]
324 );
325 assert_eq!(
326 config
327 .getattr("instrument_families")
328 .unwrap()
329 .extract::<Vec<String>>()
330 .unwrap(),
331 vec!["ETH-USD"]
332 );
333 assert_eq!(
334 config
335 .getattr("contract_types")
336 .unwrap()
337 .extract::<Vec<OKXContractType>>()
338 .unwrap(),
339 vec![OKXContractType::Inverse]
340 );
341
342 if execution {
343 assert!(
344 config
345 .getattr("use_spot_margin")
346 .unwrap()
347 .extract::<bool>()
348 .unwrap()
349 );
350 assert!(!config.hasattr("use_mm_mass_cancel").unwrap());
351 }
352 });
353 }
354
355 #[rstest]
356 #[case::data(false)]
357 #[case::execution(true)]
358 fn test_python_config_duplicate_types(
359 #[case] execution: bool,
360 #[values(false, true)] duplicate: bool,
361 ) {
362 Python::initialize();
363 Python::attach(|py| {
364 let values = if duplicate {
365 vec![
366 OKXInstrumentType::Swap,
367 OKXInstrumentType::Spot,
368 OKXInstrumentType::Swap,
369 ]
370 } else {
371 vec![OKXInstrumentType::Swap, OKXInstrumentType::Spot]
372 };
373
374 let objects: Vec<_> = values
375 .iter()
376 .map(|value| Py::new(py, *value).unwrap())
377 .collect();
378 let list = PyList::new(py, objects).unwrap();
379 let kwargs = PyDict::new(py);
380 kwargs.set_item("instrument_types", list).unwrap();
381 if execution {
382 kwargs
383 .set_item(
384 "account_id",
385 Py::new(py, AccountId::from("OKX-001")).unwrap(),
386 )
387 .unwrap();
388 }
389
390 let config_type = if execution {
391 py.get_type::<OKXExecutionClientConfig>()
392 } else {
393 py.get_type::<OKXDataClientConfig>()
394 };
395
396 let result = config_type.call((), Some(&kwargs));
397 if duplicate {
398 let error = result.unwrap_err();
399 assert!(error.is_instance_of::<PyValueError>(py));
400 assert_eq!(
401 error.value(py).str().unwrap().to_str().unwrap(),
402 "duplicate instrument_types"
403 );
404 } else {
405 let config = result.unwrap();
406 let actual: Vec<OKXInstrumentType> = config
407 .getattr("instrument_types")
408 .unwrap()
409 .extract()
410 .unwrap();
411 assert_eq!(actual, values);
412 }
413 });
414 }
415
416 #[rstest]
417 fn test_data_config_py_new() {
418 let config = OKXDataClientConfig::py_new(
419 None,
420 None,
421 None,
422 None,
423 None,
424 None,
425 None,
426 None,
427 None,
428 None,
429 None,
430 None,
431 None,
432 None,
433 None,
434 None,
435 None,
436 None,
437 None,
438 true,
439 None,
440 Some(vec!["BTC-USD".to_string()]),
441 None,
442 )
443 .unwrap();
444
445 assert_eq!(
446 config.instrument_families,
447 Some(vec!["BTC-USD".to_string()]),
448 );
449 assert!(config.load_spreads);
450 assert_eq!(config.book_stale_check_interval_secs, 5);
451 assert_eq!(config.book_stale_threshold_secs, 30);
452 assert_eq!(config.book_snapshot_timeout_secs, 10);
453 }
454
455 #[rstest]
456 #[case(None)]
457 #[case(Some(0))]
458 #[case(Some(2))]
459 #[case(Some(51))]
460 #[case(Some(u32::MAX))]
461 fn test_exec_config_python_history_pages(#[case] pages: Option<u32>) {
462 Python::initialize();
463 Python::attach(|py| {
464 let kwargs = PyDict::new(py);
465 kwargs
466 .set_item(
467 "account_id",
468 Py::new(py, AccountId::from("OKX-001")).unwrap(),
469 )
470 .unwrap();
471
472 if let Some(pages) = pages {
473 kwargs
474 .set_item("max_reconciliation_history_pages", pages)
475 .unwrap();
476 }
477
478 let config = py
479 .get_type::<OKXExecutionClientConfig>()
480 .call((), Some(&kwargs))
481 .unwrap();
482 let actual: Option<u32> = config
483 .getattr("max_reconciliation_history_pages")
484 .unwrap()
485 .extract()
486 .unwrap();
487
488 assert_eq!(actual, pages);
489 });
490 }
491
492 #[rstest]
493 fn test_exec_config_py_new_load_spreads() {
494 let config = OKXExecutionClientConfig::py_new(
495 AccountId::from("OKX-001"),
496 None,
497 None,
498 None,
499 None,
500 None,
501 None,
502 None,
503 None,
504 None,
505 None,
506 None,
507 None,
508 None,
509 None,
510 None,
511 true,
512 None,
513 None,
514 Some("USD".to_string()),
515 Some(OmsType::Hedging),
516 Some(7),
517 None,
518 None,
519 false,
520 )
521 .unwrap();
522
523 assert!(config.load_spreads);
524 assert_eq!(config.auth_timeout_secs, None);
525 assert_eq!(config.spot_trade_quote_ccy.as_deref(), Some("USD"));
526 assert_eq!(config.oms_type, Some(OmsType::Hedging));
527 assert_eq!(config.max_reconciliation_history_pages, Some(7));
528 }
529}