1use jiff::Timestamp;
19use nautilus_core::python::{
20 IntoPyObjectNautilusExt, params::value_to_pyobject, to_pyruntime_err, to_pyvalue_err,
21};
22use nautilus_model::{
23 data::BarType,
24 enums::{AccountType, OrderSide, OrderType, PositionSide, TimeInForce, TriggerType},
25 identifiers::{AccountId, ClientOrderId, InstrumentId, StrategyId, TraderId, VenueOrderId},
26 python::instruments::{instrument_any_to_pyobject, pyobject_to_instrument_any},
27 types::{Price, Quantity},
28};
29use pyo3::{
30 conversion::IntoPyObjectExt,
31 prelude::*,
32 types::{PyDict, PyList, PyTuple},
33};
34
35use super::{extract_optional_string, extract_optional_trigger_type};
36use crate::{
37 common::enums::{
38 OKXAlgoOrderStatus, OKXEnvironment, OKXInstrumentType, OKXPositionMode, OKXTradeMode,
39 },
40 http::{
41 client::OKXHttpClient,
42 error::OKXHttpError,
43 models::{OKXAttachAlgoOrdRequest, OKXCancelAlgoOrderRequest},
44 query::{
45 GetEventContractEventsParams, GetEventContractMarketsParams,
46 GetEventContractSeriesParams, GetSpreadsParams,
47 },
48 },
49};
50
51fn serializable_items_to_pylist<T>(py: Python<'_>, items: Vec<T>) -> PyResult<Py<PyAny>>
52where
53 T: serde::Serialize,
54{
55 let py_items: PyResult<Vec<_>> = items
56 .into_iter()
57 .map(|item| {
58 let value = serde_json::to_value(item).map_err(to_pyvalue_err)?;
59 value_to_pyobject(py, &value)
60 })
61 .collect();
62 Ok(PyList::new(py, py_items?)?.into_py_any_unwrap(py))
63}
64
65fn parse_attach_algo_ords(
66 py: Python<'_>,
67 attach_algo_ords: Option<Vec<Py<PyDict>>>,
68) -> PyResult<Option<Vec<OKXAttachAlgoOrdRequest>>> {
69 attach_algo_ords
70 .map(|items| {
71 items
72 .into_iter()
73 .map(|item| {
74 let dict = item.bind(py);
75 Ok(OKXAttachAlgoOrdRequest {
76 attach_algo_cl_ord_id: extract_optional_string(
77 dict,
78 "attach_algo_cl_ord_id",
79 )?,
80 sl_trigger_px: extract_optional_string(dict, "sl_trigger_px")?,
81 sl_ord_px: extract_optional_string(dict, "sl_ord_px")?,
82 sl_trigger_px_type: extract_optional_trigger_type(
83 dict,
84 "sl_trigger_px_type",
85 )?,
86 tp_trigger_px: extract_optional_string(dict, "tp_trigger_px")?,
87 tp_ord_px: extract_optional_string(dict, "tp_ord_px")?,
88 tp_trigger_px_type: extract_optional_trigger_type(
89 dict,
90 "tp_trigger_px_type",
91 )?,
92 callback_ratio: extract_optional_string(dict, "callback_ratio")?,
93 callback_spread: extract_optional_string(dict, "callback_spread")?,
94 active_px: extract_optional_string(dict, "active_px")?,
95 new_callback_ratio: extract_optional_string(dict, "new_callback_ratio")?,
96 new_callback_spread: extract_optional_string(dict, "new_callback_spread")?,
97 new_active_px: extract_optional_string(dict, "new_active_px")?,
98 })
99 })
100 .collect::<PyResult<Vec<_>>>()
101 })
102 .transpose()
103}
104
105#[pymethods]
106#[pyo3_stub_gen::derive::gen_stub_pymethods]
107impl OKXHttpClient {
108 #[new]
113 #[pyo3(signature = (
114 api_key=None,
115 api_secret=None,
116 api_passphrase=None,
117 base_url=None,
118 timeout_secs=60,
119 max_retries=3,
120 retry_delay_ms=1_000,
121 retry_delay_max_ms=10_000,
122 environment=OKXEnvironment::Live,
123 proxy_url=None,
124 ))]
125 #[expect(clippy::too_many_arguments)]
126 fn py_new(
127 api_key: Option<String>,
128 api_secret: Option<String>,
129 api_passphrase: Option<String>,
130 base_url: Option<String>,
131 timeout_secs: u64,
132 max_retries: u32,
133 retry_delay_ms: u64,
134 retry_delay_max_ms: u64,
135 environment: OKXEnvironment,
136 proxy_url: Option<String>,
137 ) -> PyResult<Self> {
138 Self::with_credentials(
139 api_key,
140 api_secret,
141 api_passphrase,
142 base_url,
143 timeout_secs,
144 max_retries,
145 retry_delay_ms,
146 retry_delay_max_ms,
147 environment,
148 proxy_url,
149 )
150 .map_err(to_pyvalue_err)
151 }
152
153 #[staticmethod]
160 #[pyo3(name = "from_env")]
161 fn py_from_env() -> PyResult<Self> {
162 Self::from_env().map_err(to_pyvalue_err)
163 }
164
165 #[getter]
167 #[pyo3(name = "base_url")]
168 #[must_use]
169 pub fn py_base_url(&self) -> &str {
170 self.base_url()
171 }
172
173 #[getter]
175 #[pyo3(name = "api_key")]
176 #[must_use]
177 pub fn py_api_key(&self) -> Option<&str> {
178 self.api_key()
179 }
180
181 #[getter]
183 #[pyo3(name = "api_key_masked")]
184 #[must_use]
185 pub fn py_api_key_masked(&self) -> Option<String> {
186 self.api_key_masked()
187 }
188
189 #[pyo3(name = "is_initialized")]
193 #[must_use]
194 pub fn py_is_initialized(&self) -> bool {
195 self.is_initialized()
196 }
197
198 #[pyo3(name = "get_cached_symbols")]
201 #[must_use]
202 pub fn py_get_cached_symbols(&self) -> Vec<String> {
203 self.get_cached_symbols()
204 }
205
206 #[pyo3(name = "cancel_all_requests")]
208 pub fn py_cancel_all_requests(&self) {
209 self.cancel_all_requests();
210 }
211
212 #[pyo3(name = "cache_instruments")]
216 pub fn py_cache_instruments(
217 &self,
218 py: Python<'_>,
219 instruments: Vec<Py<PyAny>>,
220 ) -> PyResult<()> {
221 let instruments: Result<Vec<_>, _> = instruments
222 .into_iter()
223 .map(|inst| pyobject_to_instrument_any(py, inst))
224 .collect();
225 self.cache_instruments(&instruments?);
226 Ok(())
227 }
228
229 #[pyo3(name = "cache_instrument")]
233 pub fn py_cache_instrument(&self, py: Python<'_>, instrument: Py<PyAny>) -> PyResult<()> {
234 self.cache_instrument(pyobject_to_instrument_any(py, instrument)?);
235 Ok(())
236 }
237
238 #[pyo3(name = "set_position_mode")]
251 fn py_set_position_mode<'py>(
252 &self,
253 py: Python<'py>,
254 position_mode: OKXPositionMode,
255 ) -> PyResult<Bound<'py, PyAny>> {
256 let client = self.clone();
257
258 pyo3_async_runtimes::tokio::future_into_py(py, async move {
259 client
260 .set_position_mode(position_mode)
261 .await
262 .map_err(to_pyvalue_err)?;
263
264 Python::attach(|py| Ok(py.None()))
265 })
266 }
267
268 #[pyo3(name = "activate_feature")]
285 fn py_activate_feature<'py>(
286 &self,
287 py: Python<'py>,
288 feature: String,
289 ) -> PyResult<Bound<'py, PyAny>> {
290 let client = self.clone();
291
292 pyo3_async_runtimes::tokio::future_into_py(py, async move {
293 client
294 .activate_feature(&feature)
295 .await
296 .map_err(to_pyvalue_err)?;
297
298 Python::attach(|py| Ok(py.None()))
299 })
300 }
301
302 #[pyo3(name = "set_spot_trade_quote_ccy")]
304 fn py_set_spot_trade_quote_ccy(&self, ccy: Option<String>) {
305 self.set_spot_trade_quote_ccy(ccy);
306 }
307
308 #[pyo3(name = "request_instruments")]
325 #[pyo3(signature = (instrument_type, instrument_family=None))]
326 fn py_request_instruments<'py>(
327 &self,
328 py: Python<'py>,
329 instrument_type: OKXInstrumentType,
330 instrument_family: Option<String>,
331 ) -> PyResult<Bound<'py, PyAny>> {
332 let client = self.clone();
333
334 pyo3_async_runtimes::tokio::future_into_py(py, async move {
335 let (instruments, inst_id_codes) = client
336 .request_instruments(instrument_type, instrument_family)
337 .await
338 .map_err(to_pyvalue_err)?;
339
340 Python::attach(|py| {
341 let py_instruments: PyResult<Vec<_>> = instruments
342 .into_iter()
343 .map(|inst| instrument_any_to_pyobject(py, inst))
344 .collect();
345 let instruments_list = PyList::new(py, py_instruments?)?;
346
347 let py_codes: Vec<_> = inst_id_codes
349 .into_iter()
350 .map(|(inst_id, code)| (inst_id.to_string(), code))
351 .collect();
352 let codes_list = PyList::new(py, py_codes)?;
353
354 let result = PyTuple::new(py, [instruments_list.as_any(), codes_list.as_any()])?
355 .into_any()
356 .unbind();
357 Ok(result)
358 })
359 })
360 }
361
362 #[pyo3(name = "request_spread_instruments")]
370 #[pyo3(signature = (base_currency=None, instrument_id=None, spread_id=None, state=None))]
371 fn py_request_spread_instruments<'py>(
372 &self,
373 py: Python<'py>,
374 base_currency: Option<String>,
375 instrument_id: Option<InstrumentId>,
376 spread_id: Option<String>,
377 state: Option<String>,
378 ) -> PyResult<Bound<'py, PyAny>> {
379 let client = self.clone();
380
381 pyo3_async_runtimes::tokio::future_into_py(py, async move {
382 let instruments = client
383 .request_spread_instruments(GetSpreadsParams {
384 base_ccy: base_currency,
385 inst_id: instrument_id.map(|id| id.symbol.to_string()),
386 sprd_id: spread_id,
387 state,
388 })
389 .await
390 .map_err(to_pyvalue_err)?;
391
392 Python::attach(|py| {
393 let py_instruments: PyResult<Vec<_>> = instruments
394 .into_iter()
395 .map(|inst| instrument_any_to_pyobject(py, inst))
396 .collect();
397 Ok(PyList::new(py, py_instruments?)?.into_py_any_unwrap(py))
398 })
399 })
400 }
401
402 #[pyo3(name = "request_instrument")]
413 fn py_request_instrument<'py>(
414 &self,
415 py: Python<'py>,
416 instrument_id: InstrumentId,
417 ) -> PyResult<Bound<'py, PyAny>> {
418 let client = self.clone();
419
420 pyo3_async_runtimes::tokio::future_into_py(py, async move {
421 let instrument = client
422 .request_instrument(instrument_id)
423 .await
424 .map_err(to_pyvalue_err)?;
425
426 Python::attach(|py| instrument_any_to_pyobject(py, instrument))
427 })
428 }
429
430 #[pyo3(name = "request_event_contract_series")]
436 #[pyo3(signature = (series_id=None))]
437 fn py_request_event_contract_series<'py>(
438 &self,
439 py: Python<'py>,
440 series_id: Option<String>,
441 ) -> PyResult<Bound<'py, PyAny>> {
442 let client = self.clone();
443
444 pyo3_async_runtimes::tokio::future_into_py(py, async move {
445 let series = client
446 .request_event_contract_series(GetEventContractSeriesParams { series_id })
447 .await
448 .map_err(to_pyvalue_err)?;
449
450 Python::attach(|py| serializable_items_to_pylist(py, series))
451 })
452 }
453
454 #[expect(clippy::too_many_arguments)]
460 #[pyo3(name = "request_event_contract_events")]
461 #[pyo3(signature = (series_id, event_id=None, state=None, limit=None, before=None, after=None))]
462 fn py_request_event_contract_events<'py>(
463 &self,
464 py: Python<'py>,
465 series_id: String,
466 event_id: Option<String>,
467 state: Option<String>,
468 limit: Option<String>,
469 before: Option<String>,
470 after: Option<String>,
471 ) -> PyResult<Bound<'py, PyAny>> {
472 let client = self.clone();
473
474 pyo3_async_runtimes::tokio::future_into_py(py, async move {
475 let events = client
476 .request_event_contract_events(GetEventContractEventsParams {
477 series_id,
478 event_id,
479 state,
480 limit,
481 before,
482 after,
483 })
484 .await
485 .map_err(to_pyvalue_err)?;
486
487 Python::attach(|py| serializable_items_to_pylist(py, events))
488 })
489 }
490
491 #[expect(clippy::too_many_arguments)]
497 #[pyo3(name = "request_event_contract_markets")]
498 #[pyo3(signature = (series_id, event_id=None, inst_id=None, state=None, limit=None, before=None, after=None))]
499 fn py_request_event_contract_markets<'py>(
500 &self,
501 py: Python<'py>,
502 series_id: String,
503 event_id: Option<String>,
504 inst_id: Option<String>,
505 state: Option<String>,
506 limit: Option<String>,
507 before: Option<String>,
508 after: Option<String>,
509 ) -> PyResult<Bound<'py, PyAny>> {
510 let client = self.clone();
511
512 pyo3_async_runtimes::tokio::future_into_py(py, async move {
513 let markets = client
514 .request_event_contract_markets(GetEventContractMarketsParams {
515 series_id,
516 event_id,
517 inst_id,
518 state,
519 limit,
520 before,
521 after,
522 })
523 .await
524 .map_err(to_pyvalue_err)?;
525
526 Python::attach(|py| serializable_items_to_pylist(py, markets))
527 })
528 }
529
530 #[pyo3(name = "request_account_state")]
539 #[pyo3(signature = (account_id, account_type=AccountType::Margin))]
540 fn py_request_account_state<'py>(
541 &self,
542 py: Python<'py>,
543 account_id: AccountId,
544 account_type: AccountType,
545 ) -> PyResult<Bound<'py, PyAny>> {
546 let client = self.clone();
547
548 pyo3_async_runtimes::tokio::future_into_py(py, async move {
549 let account_state = client
550 .request_account_state(account_id, account_type)
551 .await
552 .map_err(to_pyvalue_err)?;
553
554 Python::attach(|py| account_state.into_py_any(py))
555 })
556 }
557
558 #[pyo3(name = "request_trades")]
567 #[pyo3(signature = (instrument_id, start=None, end=None, limit=None))]
568 fn py_request_trades<'py>(
569 &self,
570 py: Python<'py>,
571 instrument_id: InstrumentId,
572 start: Option<Timestamp>,
573 end: Option<Timestamp>,
574 limit: Option<u32>,
575 ) -> PyResult<Bound<'py, PyAny>> {
576 let client = self.clone();
577
578 pyo3_async_runtimes::tokio::future_into_py(py, async move {
579 let trades = client
580 .request_trades(instrument_id, start, end, limit)
581 .await
582 .map_err(to_pyvalue_err)?;
583
584 Python::attach(|py| {
585 let py_trades = trades
586 .into_iter()
587 .map(|trade| trade.into_py_any(py))
588 .collect::<PyResult<Vec<_>>>()?;
589 let pylist = PyList::new(py, py_trades)?;
590 Ok(pylist.into_py_any_unwrap(py))
591 })
592 })
593 }
594
595 #[pyo3(name = "request_bars")]
643 #[pyo3(signature = (bar_type, start=None, end=None, limit=None))]
644 fn py_request_bars<'py>(
645 &self,
646 py: Python<'py>,
647 bar_type: BarType,
648 start: Option<Timestamp>,
649 end: Option<Timestamp>,
650 limit: Option<u32>,
651 ) -> PyResult<Bound<'py, PyAny>> {
652 let client = self.clone();
653
654 pyo3_async_runtimes::tokio::future_into_py(py, async move {
655 let bars = client
656 .request_bars(bar_type, start, end, limit)
657 .await
658 .map_err(to_pyvalue_err)?;
659
660 Python::attach(|py| {
661 let py_bars = bars
662 .into_iter()
663 .map(|bar| bar.into_py_any(py))
664 .collect::<PyResult<Vec<_>>>()?;
665 let pylist = PyList::new(py, py_bars)?;
666 Ok(pylist.into_py_any_unwrap(py))
667 })
668 })
669 }
670
671 #[pyo3(name = "request_orderbook_snapshot")]
677 #[pyo3(signature = (instrument_id, depth=None))]
678 fn py_request_orderbook_snapshot<'py>(
679 &self,
680 py: Python<'py>,
681 instrument_id: InstrumentId,
682 depth: Option<u32>,
683 ) -> PyResult<Bound<'py, PyAny>> {
684 let client = self.clone();
685
686 pyo3_async_runtimes::tokio::future_into_py(py, async move {
687 let deltas = client
688 .request_orderbook_snapshot(instrument_id, depth)
689 .await
690 .map_err(to_pyvalue_err)?;
691
692 Python::attach(|py| deltas.into_py_any(py))
693 })
694 }
695
696 #[pyo3(name = "request_funding_rates")]
702 #[pyo3(signature = (instrument_id, start=None, end=None, limit=None))]
703 fn py_request_funding_rates<'py>(
704 &self,
705 py: Python<'py>,
706 instrument_id: InstrumentId,
707 start: Option<Timestamp>,
708 end: Option<Timestamp>,
709 limit: Option<u32>,
710 ) -> PyResult<Bound<'py, PyAny>> {
711 let client = self.clone();
712
713 pyo3_async_runtimes::tokio::future_into_py(py, async move {
714 let rates = client
715 .request_funding_rates(instrument_id, start, end, limit)
716 .await
717 .map_err(to_pyvalue_err)?;
718
719 Python::attach(|py| {
720 let py_rates = rates
721 .into_iter()
722 .map(|rate| rate.into_py_any(py))
723 .collect::<PyResult<Vec<_>>>()?;
724 let pylist = PyList::new(py, py_rates)?;
725 Ok(pylist.into_py_any_unwrap(py))
726 })
727 })
728 }
729
730 #[pyo3(name = "request_mark_price")]
736 fn py_request_mark_price<'py>(
737 &self,
738 py: Python<'py>,
739 instrument_id: InstrumentId,
740 ) -> PyResult<Bound<'py, PyAny>> {
741 let client = self.clone();
742
743 pyo3_async_runtimes::tokio::future_into_py(py, async move {
744 let mark_price = client
745 .request_mark_price(instrument_id)
746 .await
747 .map_err(to_pyvalue_err)?;
748
749 Python::attach(|py| mark_price.into_py_any(py))
750 })
751 }
752
753 #[pyo3(name = "request_price_limit")]
759 fn py_request_price_limit<'py>(
760 &self,
761 py: Python<'py>,
762 instrument_id: InstrumentId,
763 ) -> PyResult<Bound<'py, PyAny>> {
764 let client = self.clone();
765
766 pyo3_async_runtimes::tokio::future_into_py(py, async move {
767 let price_limit = client
768 .request_price_limit(instrument_id)
769 .await
770 .map_err(to_pyvalue_err)?;
771
772 Python::attach(|py| {
773 let value = serde_json::to_value(price_limit).map_err(to_pyvalue_err)?;
774 value_to_pyobject(py, &value)
775 })
776 })
777 }
778
779 #[pyo3(name = "request_index_price")]
785 fn py_request_index_price<'py>(
786 &self,
787 py: Python<'py>,
788 instrument_id: InstrumentId,
789 ) -> PyResult<Bound<'py, PyAny>> {
790 let client = self.clone();
791
792 pyo3_async_runtimes::tokio::future_into_py(py, async move {
793 let index_price = client
794 .request_index_price(instrument_id)
795 .await
796 .map_err(to_pyvalue_err)?;
797
798 Python::attach(|py| index_price.into_py_any(py))
799 })
800 }
801
802 #[pyo3(name = "request_order_status_reports")]
813 #[pyo3(signature = (account_id, instrument_type=None, instrument_id=None, start=None, end=None, open_only=false, limit=None))]
814 #[expect(clippy::too_many_arguments)]
815 fn py_request_order_status_reports<'py>(
816 &self,
817 py: Python<'py>,
818 account_id: AccountId,
819 instrument_type: Option<OKXInstrumentType>,
820 instrument_id: Option<InstrumentId>,
821 start: Option<Timestamp>,
822 end: Option<Timestamp>,
823 open_only: bool,
824 limit: Option<u32>,
825 ) -> PyResult<Bound<'py, PyAny>> {
826 let client = self.clone();
827
828 pyo3_async_runtimes::tokio::future_into_py(py, async move {
829 let reports = client
830 .request_order_status_reports(
831 account_id,
832 instrument_type,
833 instrument_id,
834 start,
835 end,
836 open_only,
837 limit,
838 )
839 .await
840 .map_err(to_pyvalue_err)?;
841
842 Python::attach(|py| {
843 let py_reports = reports
844 .into_iter()
845 .map(|report| report.into_py_any(py))
846 .collect::<PyResult<Vec<_>>>()?;
847 let pylist = PyList::new(py, py_reports)?;
848 Ok(pylist.into_py_any_unwrap(py))
849 })
850 })
851 }
852
853 #[pyo3(name = "request_algo_order_status_reports")]
859 #[pyo3(signature = (account_id, instrument_type=None, instrument_id=None, algo_id=None, algo_client_order_id=None, state=None, limit=None))]
860 #[expect(clippy::too_many_arguments)]
861 fn py_request_algo_order_status_reports<'py>(
862 &self,
863 py: Python<'py>,
864 account_id: AccountId,
865 instrument_type: Option<OKXInstrumentType>,
866 instrument_id: Option<InstrumentId>,
867 algo_id: Option<String>,
868 algo_client_order_id: Option<ClientOrderId>,
869 state: Option<OKXAlgoOrderStatus>,
870 limit: Option<u32>,
871 ) -> PyResult<Bound<'py, PyAny>> {
872 let client = self.clone();
873
874 pyo3_async_runtimes::tokio::future_into_py(py, async move {
875 let reports = client
876 .request_algo_order_status_reports(
877 account_id,
878 instrument_type,
879 instrument_id,
880 algo_id,
881 algo_client_order_id,
882 state,
883 limit,
884 )
885 .await
886 .map_err(to_pyvalue_err)?;
887
888 Python::attach(|py| {
889 let py_reports = reports
890 .into_iter()
891 .map(|report| report.into_py_any(py))
892 .collect::<PyResult<Vec<_>>>()?;
893 let pylist = PyList::new(py, py_reports)?;
894 Ok(pylist.into_py_any_unwrap(py))
895 })
896 })
897 }
898
899 #[pyo3(name = "request_algo_order_status_report")]
905 fn py_request_algo_order_status_report<'py>(
906 &self,
907 py: Python<'py>,
908 account_id: AccountId,
909 instrument_id: InstrumentId,
910 client_order_id: ClientOrderId,
911 ) -> PyResult<Bound<'py, PyAny>> {
912 let client = self.clone();
913
914 pyo3_async_runtimes::tokio::future_into_py(py, async move {
915 let report = client
916 .request_algo_order_status_report(account_id, instrument_id, client_order_id)
917 .await
918 .map_err(to_pyvalue_err)?;
919
920 Python::attach(|py| match report {
921 Some(report) => report.into_py_any(py),
922 None => Ok(py.None()),
923 })
924 })
925 }
926
927 #[pyo3(name = "request_fill_reports")]
937 #[pyo3(signature = (account_id, instrument_type=None, instrument_id=None, start=None, end=None, limit=None))]
938 #[expect(clippy::too_many_arguments)]
939 fn py_request_fill_reports<'py>(
940 &self,
941 py: Python<'py>,
942 account_id: AccountId,
943 instrument_type: Option<OKXInstrumentType>,
944 instrument_id: Option<InstrumentId>,
945 start: Option<Timestamp>,
946 end: Option<Timestamp>,
947 limit: Option<u32>,
948 ) -> PyResult<Bound<'py, PyAny>> {
949 let client = self.clone();
950
951 pyo3_async_runtimes::tokio::future_into_py(py, async move {
952 let trades = client
953 .request_fill_reports(
954 account_id,
955 instrument_type,
956 instrument_id,
957 start,
958 end,
959 limit,
960 )
961 .await
962 .map_err(to_pyvalue_err)?;
963
964 Python::attach(|py| {
965 let py_trades = trades
966 .into_iter()
967 .map(|trade| trade.into_py_any(py))
968 .collect::<PyResult<Vec<_>>>()?;
969 let pylist = PyList::new(py, py_trades)?;
970 Ok(pylist.into_py_any_unwrap(py))
971 })
972 })
973 }
974
975 #[pyo3(name = "request_position_status_reports")]
1003 #[pyo3(signature = (account_id, instrument_type=None, instrument_id=None))]
1004 fn py_request_position_status_reports<'py>(
1005 &self,
1006 py: Python<'py>,
1007 account_id: AccountId,
1008 instrument_type: Option<OKXInstrumentType>,
1009 instrument_id: Option<InstrumentId>,
1010 ) -> PyResult<Bound<'py, PyAny>> {
1011 let client = self.clone();
1012
1013 pyo3_async_runtimes::tokio::future_into_py(py, async move {
1014 let reports = client
1015 .request_position_status_reports(account_id, instrument_type, instrument_id)
1016 .await
1017 .map_err(to_pyvalue_err)?;
1018
1019 Python::attach(|py| {
1020 let py_reports = reports
1021 .into_iter()
1022 .map(|report| report.into_py_any(py))
1023 .collect::<PyResult<Vec<_>>>()?;
1024 let pylist = PyList::new(py, py_reports)?;
1025 Ok(pylist.into_py_any_unwrap(py))
1026 })
1027 })
1028 }
1029
1030 #[pyo3(name = "place_order")]
1040 #[pyo3(signature = (
1041 trader_id,
1042 strategy_id,
1043 instrument_id,
1044 td_mode,
1045 client_order_id,
1046 order_side,
1047 order_type,
1048 quantity,
1049 time_in_force=None,
1050 price=None,
1051 post_only=None,
1052 reduce_only=None,
1053 quote_quantity=None,
1054 position_side=None,
1055 attach_algo_ords=None,
1056 px_usd=None,
1057 px_vol=None,
1058 outcome=None,
1059 slippage_pct=None,
1060 ))]
1061 #[expect(clippy::too_many_arguments)]
1062 fn py_place_order<'py>(
1063 &self,
1064 py: Python<'py>,
1065 trader_id: TraderId,
1066 strategy_id: StrategyId,
1067 instrument_id: InstrumentId,
1068 td_mode: OKXTradeMode,
1069 client_order_id: ClientOrderId,
1070 order_side: OrderSide,
1071 order_type: OrderType,
1072 quantity: Quantity,
1073 time_in_force: Option<TimeInForce>,
1074 price: Option<Price>,
1075 post_only: Option<bool>,
1076 reduce_only: Option<bool>,
1077 quote_quantity: Option<bool>,
1078 position_side: Option<PositionSide>,
1079 attach_algo_ords: Option<Vec<Py<PyDict>>>,
1080 px_usd: Option<String>,
1081 px_vol: Option<String>,
1082 outcome: Option<String>,
1083 slippage_pct: Option<String>,
1084 ) -> PyResult<Bound<'py, PyAny>> {
1085 let attach_algo_ords = parse_attach_algo_ords(py, attach_algo_ords)?;
1086 let client = self.clone();
1087
1088 let _ = (trader_id, strategy_id);
1089
1090 pyo3_async_runtimes::tokio::future_into_py(py, async move {
1091 let resp = client
1092 .place_order_with_domain_types(
1093 instrument_id,
1094 td_mode,
1095 client_order_id,
1096 order_side,
1097 order_type,
1098 quantity,
1099 time_in_force,
1100 price,
1101 post_only,
1102 reduce_only,
1103 quote_quantity,
1104 position_side,
1105 attach_algo_ords,
1106 px_usd,
1107 px_vol,
1108 outcome,
1109 slippage_pct,
1110 None,
1111 None,
1112 None,
1113 )
1114 .await
1115 .map_err(to_pyvalue_err)?;
1116
1117 Python::attach(|py| {
1118 let dict = PyDict::new(py);
1119
1120 if let Some(ord_id) = resp.ord_id {
1121 dict.set_item("ord_id", ord_id.as_str())?;
1122 }
1123
1124 if let Some(cl_ord_id) = resp.cl_ord_id {
1125 dict.set_item("cl_ord_id", cl_ord_id.as_str())?;
1126 }
1127
1128 if let Some(s_code) = resp.s_code {
1129 dict.set_item("s_code", s_code)?;
1130 }
1131
1132 if let Some(s_msg) = resp.s_msg {
1133 dict.set_item("s_msg", s_msg)?;
1134 }
1135
1136 if let Some(sub_code) = resp.sub_code {
1137 dict.set_item("sub_code", sub_code)?;
1138 }
1139
1140 Ok(dict.into_py_any_unwrap(py))
1141 })
1142 })
1143 }
1144
1145 #[pyo3(name = "place_algo_order")]
1155 #[pyo3(signature = (
1156 trader_id,
1157 strategy_id,
1158 instrument_id,
1159 td_mode,
1160 client_order_id,
1161 order_side,
1162 order_type,
1163 quantity,
1164 trigger_price=None,
1165 trigger_type=None,
1166 limit_price=None,
1167 reduce_only=None,
1168 close_fraction=None,
1169 callback_ratio=None,
1170 callback_spread=None,
1171 activation_price=None,
1172 quote_quantity=false,
1173 ))]
1174 #[expect(clippy::too_many_arguments)]
1175 fn py_place_algo_order<'py>(
1176 &self,
1177 py: Python<'py>,
1178 trader_id: TraderId,
1179 strategy_id: StrategyId,
1180 instrument_id: InstrumentId,
1181 td_mode: OKXTradeMode,
1182 client_order_id: ClientOrderId,
1183 order_side: OrderSide,
1184 order_type: OrderType,
1185 quantity: Quantity,
1186 trigger_price: Option<Price>,
1187 trigger_type: Option<TriggerType>,
1188 limit_price: Option<Price>,
1189 reduce_only: Option<bool>,
1190 close_fraction: Option<String>,
1191 callback_ratio: Option<String>,
1192 callback_spread: Option<String>,
1193 activation_price: Option<Price>,
1194 quote_quantity: bool,
1195 ) -> PyResult<Bound<'py, PyAny>> {
1196 let client = self.clone();
1197
1198 let _ = (trader_id, strategy_id);
1200
1201 pyo3_async_runtimes::tokio::future_into_py(py, async move {
1202 let resp = client
1203 .place_algo_order_with_domain_types(
1204 instrument_id,
1205 td_mode,
1206 client_order_id,
1207 order_side,
1208 order_type,
1209 quantity,
1210 quote_quantity,
1211 trigger_price,
1212 trigger_type,
1213 limit_price,
1214 reduce_only,
1215 None,
1216 close_fraction,
1217 callback_ratio,
1218 callback_spread,
1219 activation_price,
1220 )
1221 .await
1222 .map_err(to_pyvalue_err)?;
1223
1224 Python::attach(|py| {
1225 let dict = PyDict::new(py);
1226 dict.set_item("algo_id", resp.algo_id)?;
1227 if let Some(algo_cl_ord_id) = resp.algo_cl_ord_id {
1228 dict.set_item("algo_cl_ord_id", algo_cl_ord_id)?;
1229 }
1230
1231 if let Some(s_code) = resp.s_code {
1232 dict.set_item("s_code", s_code)?;
1233 }
1234
1235 if let Some(s_msg) = resp.s_msg {
1236 dict.set_item("s_msg", s_msg)?;
1237 }
1238
1239 if let Some(req_id) = resp.req_id {
1240 dict.set_item("req_id", req_id)?;
1241 }
1242 Ok(dict.into_py_any_unwrap(py))
1243 })
1244 })
1245 }
1246
1247 #[pyo3(name = "cancel_algo_order")]
1257 fn py_cancel_algo_order<'py>(
1258 &self,
1259 py: Python<'py>,
1260 instrument_id: InstrumentId,
1261 algo_id: String,
1262 ) -> PyResult<Bound<'py, PyAny>> {
1263 let client = self.clone();
1264
1265 pyo3_async_runtimes::tokio::future_into_py(py, async move {
1266 let resp = client
1267 .cancel_algo_order_with_domain_types(instrument_id, algo_id)
1268 .await
1269 .map_err(to_pyvalue_err)?;
1270
1271 Python::attach(|py| {
1272 let dict = PyDict::new(py);
1273 dict.set_item("algo_id", resp.algo_id)?;
1274 if let Some(s_code) = resp.s_code {
1275 dict.set_item("s_code", s_code)?;
1276 }
1277
1278 if let Some(s_msg) = resp.s_msg {
1279 dict.set_item("s_msg", s_msg)?;
1280 }
1281 Ok(dict.into_py_any_unwrap(py))
1282 })
1283 })
1284 }
1285
1286 #[pyo3(name = "cancel_order")]
1292 #[pyo3(signature = (instrument_id, client_order_id=None, venue_order_id=None))]
1293 fn py_cancel_order<'py>(
1294 &self,
1295 py: Python<'py>,
1296 instrument_id: InstrumentId,
1297 client_order_id: Option<ClientOrderId>,
1298 venue_order_id: Option<VenueOrderId>,
1299 ) -> PyResult<Bound<'py, PyAny>> {
1300 let client = self.clone();
1301
1302 pyo3_async_runtimes::tokio::future_into_py(py, async move {
1303 let resp = client
1304 .cancel_order(instrument_id, client_order_id, venue_order_id)
1305 .await
1306 .map_err(to_pyvalue_err)?;
1307
1308 Python::attach(|py| {
1309 let dict = PyDict::new(py);
1310 dict.set_item("ord_id", resp.ord_id)?;
1311
1312 if let Some(cl_ord_id) = resp.cl_ord_id {
1313 dict.set_item("cl_ord_id", cl_ord_id)?;
1314 }
1315
1316 if let Some(s_code) = resp.s_code {
1317 dict.set_item("s_code", s_code)?;
1318 }
1319
1320 if let Some(s_msg) = resp.s_msg {
1321 dict.set_item("s_msg", s_msg)?;
1322 }
1323
1324 if let Some(ts) = resp.ts {
1325 dict.set_item("ts", ts)?;
1326 }
1327
1328 Ok(dict.into_py_any_unwrap(py))
1329 })
1330 })
1331 }
1332
1333 #[pyo3(name = "cancel_all_orders")]
1339 fn py_cancel_all_orders<'py>(
1340 &self,
1341 py: Python<'py>,
1342 instrument_id: InstrumentId,
1343 ) -> PyResult<Bound<'py, PyAny>> {
1344 let client = self.clone();
1345
1346 pyo3_async_runtimes::tokio::future_into_py(py, async move {
1347 let responses = client
1348 .cancel_all_orders(instrument_id)
1349 .await
1350 .map_err(to_pyvalue_err)?;
1351
1352 Python::attach(|py| {
1353 let results: PyResult<Vec<_>> = responses
1354 .into_iter()
1355 .map(|resp| {
1356 let dict = PyDict::new(py);
1357 dict.set_item("ord_id", resp.ord_id)?;
1358
1359 if let Some(cl_ord_id) = resp.cl_ord_id {
1360 dict.set_item("cl_ord_id", cl_ord_id)?;
1361 }
1362
1363 if let Some(s_code) = resp.s_code {
1364 dict.set_item("s_code", s_code)?;
1365 }
1366
1367 if let Some(s_msg) = resp.s_msg {
1368 dict.set_item("s_msg", s_msg)?;
1369 }
1370
1371 if let Some(ts) = resp.ts {
1372 dict.set_item("ts", ts)?;
1373 }
1374
1375 Ok(dict)
1376 })
1377 .collect();
1378 Ok(PyList::new(py, results?)?.into_py_any_unwrap(py))
1379 })
1380 })
1381 }
1382
1383 #[expect(clippy::too_many_arguments)]
1393 #[pyo3(name = "amend_algo_order")]
1394 #[pyo3(signature = (
1395 instrument_id,
1396 algo_id,
1397 new_trigger_price=None,
1398 new_limit_price=None,
1399 new_quantity=None,
1400 new_callback_ratio=None,
1401 new_callback_spread=None,
1402 new_activation_price=None,
1403 new_sl_trigger_price=None,
1404 new_tp_trigger_price=None,
1405 new_tp_order_price=None,
1406 new_tp_trigger_px_type=None,
1407 new_sl_order_price=None,
1408 new_sl_trigger_px_type=None,
1409 ))]
1410 fn py_amend_algo_order<'py>(
1411 &self,
1412 py: Python<'py>,
1413 instrument_id: InstrumentId,
1414 algo_id: String,
1415 new_trigger_price: Option<Price>,
1416 new_limit_price: Option<Price>,
1417 new_quantity: Option<Quantity>,
1418 new_callback_ratio: Option<String>,
1419 new_callback_spread: Option<String>,
1420 new_activation_price: Option<Price>,
1421 new_sl_trigger_price: Option<Price>,
1422 new_tp_trigger_price: Option<Price>,
1423 new_tp_order_price: Option<String>,
1424 new_tp_trigger_px_type: Option<String>,
1425 new_sl_order_price: Option<String>,
1426 new_sl_trigger_px_type: Option<String>,
1427 ) -> PyResult<Bound<'py, PyAny>> {
1428 let client = self.clone();
1429
1430 pyo3_async_runtimes::tokio::future_into_py(py, async move {
1431 let resp = client
1432 .amend_algo_order_with_domain_types(
1433 instrument_id,
1434 algo_id,
1435 new_trigger_price,
1436 new_sl_trigger_price,
1437 new_limit_price,
1438 new_quantity,
1439 new_callback_ratio,
1440 new_callback_spread,
1441 new_activation_price,
1442 new_tp_trigger_price,
1443 new_tp_order_price,
1444 new_tp_trigger_px_type,
1445 new_sl_order_price,
1446 new_sl_trigger_px_type,
1447 )
1448 .await
1449 .map_err(to_pyvalue_err)?;
1450
1451 Python::attach(|py| {
1452 let dict = PyDict::new(py);
1453 dict.set_item("algo_id", resp.algo_id)?;
1454 if let Some(s_code) = resp.s_code {
1455 dict.set_item("s_code", s_code)?;
1456 }
1457
1458 if let Some(s_msg) = resp.s_msg {
1459 dict.set_item("s_msg", s_msg)?;
1460 }
1461 Ok(dict.into_py_any_unwrap(py))
1462 })
1463 })
1464 }
1465
1466 #[pyo3(name = "cancel_algo_orders")]
1479 fn py_cancel_algo_orders<'py>(
1480 &self,
1481 py: Python<'py>,
1482 orders: Vec<(InstrumentId, String)>,
1483 ) -> PyResult<Bound<'py, PyAny>> {
1484 let client = self.clone();
1485
1486 pyo3_async_runtimes::tokio::future_into_py(py, async move {
1487 let requests: Vec<_> = orders
1488 .into_iter()
1489 .map(|(instrument_id, algo_id)| OKXCancelAlgoOrderRequest {
1490 inst_id: instrument_id.symbol.to_string(),
1491 inst_id_code: None,
1492 algo_id: Some(algo_id),
1493 algo_cl_ord_id: None,
1494 })
1495 .collect();
1496
1497 let responses = client
1498 .cancel_algo_orders(requests)
1499 .await
1500 .map_err(to_pyvalue_err)?;
1501
1502 Python::attach(|py| {
1503 let results = responses
1504 .into_iter()
1505 .map(|resp| {
1506 let dict = PyDict::new(py);
1507 dict.set_item("algo_id", resp.algo_id)?;
1508 if let Some(s_code) = resp.s_code {
1509 dict.set_item("s_code", s_code)?;
1510 }
1511
1512 if let Some(s_msg) = resp.s_msg {
1513 dict.set_item("s_msg", s_msg)?;
1514 }
1515 Ok(dict)
1516 })
1517 .collect::<PyResult<Vec<_>>>()?;
1518 Ok(PyList::new(py, results)?.into_any().unbind())
1519 })
1520 })
1521 }
1522
1523 #[pyo3(name = "cancel_advance_algo_order")]
1524 fn py_cancel_advance_algo_order<'py>(
1525 &self,
1526 py: Python<'py>,
1527 instrument_id: InstrumentId,
1528 algo_id: String,
1529 ) -> PyResult<Bound<'py, PyAny>> {
1530 let client = self.clone();
1531
1532 pyo3_async_runtimes::tokio::future_into_py(py, async move {
1533 let request = OKXCancelAlgoOrderRequest {
1534 inst_id: instrument_id.symbol.to_string(),
1535 inst_id_code: None,
1536 algo_id: Some(algo_id),
1537 algo_cl_ord_id: None,
1538 };
1539
1540 let mut responses = client
1541 .cancel_advance_algo_orders(vec![request])
1542 .await
1543 .map_err(to_pyvalue_err)?;
1544
1545 let resp = responses
1546 .pop()
1547 .ok_or_else(|| to_pyvalue_err("Empty response"))?;
1548
1549 Python::attach(|py| {
1550 let dict = PyDict::new(py);
1551 dict.set_item("algo_id", resp.algo_id)?;
1552
1553 if let Some(s_code) = resp.s_code {
1554 dict.set_item("s_code", s_code)?;
1555 }
1556
1557 if let Some(s_msg) = resp.s_msg {
1558 dict.set_item("s_msg", s_msg)?;
1559 }
1560 Ok(dict.into_py_any_unwrap(py))
1561 })
1562 })
1563 }
1564
1565 #[pyo3(name = "get_server_time")]
1573 fn py_get_server_time<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
1574 let client = self.clone();
1575
1576 pyo3_async_runtimes::tokio::future_into_py(py, async move {
1577 let timestamp = client.get_server_time().await.map_err(to_pyvalue_err)?;
1578
1579 Python::attach(|py| timestamp.into_py_any(py))
1580 })
1581 }
1582
1583 #[pyo3(name = "get_balance")]
1584 fn py_get_balance<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
1585 let client = self.clone();
1586
1587 pyo3_async_runtimes::tokio::future_into_py(py, async move {
1588 let accounts = client.inner.get_balance().await.map_err(to_pyvalue_err)?;
1589
1590 let details: Vec<_> = accounts
1591 .into_iter()
1592 .flat_map(|account| account.details)
1593 .collect();
1594
1595 Python::attach(|py| {
1596 let pylist = PyList::new(py, details)?;
1597 Ok(pylist.into_py_any_unwrap(py))
1598 })
1599 })
1600 }
1601}
1602
1603impl From<OKXHttpError> for PyErr {
1604 fn from(error: OKXHttpError) -> Self {
1605 match error {
1606 OKXHttpError::Canceled(msg) => to_pyruntime_err(format!("Request canceled: {msg}")),
1608 OKXHttpError::HttpClientError(e) => to_pyruntime_err(format!("Network error: {e}")),
1609 OKXHttpError::RetryableStatus { status, body, .. } => {
1610 to_pyruntime_err(format!("Temporary HTTP status code {status}: {body}"))
1611 }
1612 OKXHttpError::UnexpectedStatus { status, body } => {
1613 to_pyruntime_err(format!("Unexpected HTTP status code {status}: {body}"))
1614 }
1615 OKXHttpError::RetryableOkxError {
1616 error_code,
1617 message,
1618 ..
1619 } => to_pyruntime_err(format!("Temporary OKX error {error_code}: {message}")),
1620 OKXHttpError::MalformedResponse(msg) => {
1621 to_pyruntime_err(format!("Malformed response: {msg}"))
1622 }
1623 OKXHttpError::ResponseDecoding(msg) => {
1624 to_pyruntime_err(format!("Response decoding error: {msg}"))
1625 }
1626 OKXHttpError::OperationTimeout { timeout_ms } => {
1627 to_pyruntime_err(format!("Operation timed out after {timeout_ms}ms"))
1628 }
1629 OKXHttpError::RetryBudgetExceeded(msg) => {
1630 to_pyruntime_err(format!("Retry budget exceeded: {msg}"))
1631 }
1632 OKXHttpError::EmptyResponse => to_pyruntime_err("Empty response"),
1633 OKXHttpError::MissingCredentials => {
1635 to_pyvalue_err("Missing credentials for authenticated request")
1636 }
1637 OKXHttpError::ValidationError(msg) => {
1638 to_pyvalue_err(format!("Parameter validation error: {msg}"))
1639 }
1640 OKXHttpError::RequestSerialization(msg) => {
1641 to_pyvalue_err(format!("Request serialization error: {msg}"))
1642 }
1643 OKXHttpError::OkxError {
1644 error_code,
1645 message,
1646 } => to_pyvalue_err(format!("OKX error {error_code}: {message}")),
1647 }
1648 }
1649}