1use jiff::Timestamp;
19use nautilus_core::python::{to_pyruntime_err, to_pyvalue_err};
20use nautilus_model::{
21 data::BarType,
22 enums::{OrderSide, OrderType, TimeInForce},
23 identifiers::{AccountId, ClientOrderId, InstrumentId, VenueOrderId},
24 python::instruments::{instrument_any_to_pyobject, pyobject_to_instrument_any},
25 types::{Price, Quantity},
26};
27use pyo3::{
28 conversion::IntoPyObjectExt,
29 prelude::*,
30 types::{PyDict, PyList},
31};
32use ustr::Ustr;
33
34use crate::{
35 common::{
36 enums::{
37 BybitMarginMode, BybitOpenOnly, BybitOrderFilter, BybitPositionIdx, BybitPositionMode,
38 BybitProductType,
39 },
40 parse::{parse_bbo_level, parse_bbo_side_type, parse_smp_type},
41 },
42 http::{
43 client::{BybitHttpClient, BybitRawHttpClient},
44 error::BybitHttpError,
45 models::BybitOrderCursorList,
46 query::BybitNativeTpSlParams as RustNativeTpSlParams,
47 },
48 python::params::BybitNativeTpSlParams,
49};
50
51#[pymethods]
52#[pyo3_stub_gen::derive::gen_stub_pymethods]
53impl BybitRawHttpClient {
54 #[new]
59 #[pyo3(signature = (api_key=None, api_secret=None, base_url=None, demo=false, testnet=false, timeout_secs=60, max_retries=3, retry_delay_ms=1000, retry_delay_max_ms=10_000, recv_window_ms=5_000, proxy_url=None))]
60 #[expect(clippy::too_many_arguments)]
61 fn py_new(
62 api_key: Option<String>,
63 api_secret: Option<String>,
64 base_url: Option<String>,
65 demo: bool,
66 testnet: bool,
67 timeout_secs: u64,
68 max_retries: u32,
69 retry_delay_ms: u64,
70 retry_delay_max_ms: u64,
71 recv_window_ms: u64,
72 proxy_url: Option<String>,
73 ) -> PyResult<Self> {
74 Self::new_with_env(
75 api_key,
76 api_secret,
77 base_url,
78 demo,
79 testnet,
80 timeout_secs,
81 max_retries,
82 retry_delay_ms,
83 retry_delay_max_ms,
84 recv_window_ms,
85 proxy_url,
86 )
87 .map_err(to_pyvalue_err)
88 }
89
90 #[getter]
92 #[pyo3(name = "base_url")]
93 #[must_use]
94 pub fn py_base_url(&self) -> &str {
95 self.base_url()
96 }
97
98 #[getter]
99 #[pyo3(name = "api_key")]
100 #[must_use]
101 pub fn py_api_key(&self) -> Option<String> {
102 self.credential().map(|c| c.api_key().to_string())
103 }
104
105 #[getter]
107 #[pyo3(name = "recv_window_ms")]
108 #[must_use]
109 pub fn py_recv_window_ms(&self) -> u64 {
110 self.recv_window_ms()
111 }
112
113 #[pyo3(name = "cancel_all_requests")]
115 fn py_cancel_all_requests(&self) {
116 self.cancel_all_requests();
117 }
118
119 #[pyo3(name = "get_server_time")]
129 fn py_get_server_time<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
130 let client = self.clone();
131
132 pyo3_async_runtimes::tokio::future_into_py(py, async move {
133 let response = client.get_server_time().await.map_err(to_pyvalue_err)?;
134
135 Python::attach(|py| {
136 let server_time = Py::new(py, response.result)?;
137 Ok(server_time.into_any())
138 })
139 })
140 }
141
142 #[pyo3(name = "get_open_orders")]
152 #[pyo3(signature = (category, symbol=None, base_coin=None, settle_coin=None, order_id=None, order_link_id=None, open_only=None, order_filter=None, limit=None, cursor=None))]
153 #[expect(clippy::too_many_arguments)]
154 fn py_get_open_orders<'py>(
155 &self,
156 py: Python<'py>,
157 category: BybitProductType,
158 symbol: Option<String>,
159 base_coin: Option<String>,
160 settle_coin: Option<String>,
161 order_id: Option<String>,
162 order_link_id: Option<String>,
163 open_only: Option<BybitOpenOnly>,
164 order_filter: Option<BybitOrderFilter>,
165 limit: Option<u32>,
166 cursor: Option<String>,
167 ) -> PyResult<Bound<'py, PyAny>> {
168 let client = self.clone();
169
170 pyo3_async_runtimes::tokio::future_into_py(py, async move {
171 let response = client
172 .get_open_orders(
173 category,
174 symbol,
175 base_coin,
176 settle_coin,
177 order_id,
178 order_link_id,
179 open_only,
180 order_filter,
181 limit,
182 cursor,
183 )
184 .await
185 .map_err(to_pyvalue_err)?;
186
187 Python::attach(|py| {
188 let open_orders = BybitOrderCursorList::from(response.result);
189 let py_open_orders = Py::new(py, open_orders)?;
190 Ok(py_open_orders.into_any())
191 })
192 })
193 }
194}
195
196#[pymethods]
197#[pyo3_stub_gen::derive::gen_stub_pymethods]
198impl BybitHttpClient {
199 #[new]
205 #[pyo3(signature = (api_key=None, api_secret=None, base_url=None, demo=false, testnet=false, timeout_secs=60, max_retries=3, retry_delay_ms=1000, retry_delay_max_ms=10_000, recv_window_ms=5_000, proxy_url=None))]
206 #[expect(clippy::too_many_arguments)]
207 fn py_new(
208 api_key: Option<String>,
209 api_secret: Option<String>,
210 base_url: Option<String>,
211 demo: bool,
212 testnet: bool,
213 timeout_secs: u64,
214 max_retries: u32,
215 retry_delay_ms: u64,
216 retry_delay_max_ms: u64,
217 recv_window_ms: u64,
218 proxy_url: Option<String>,
219 ) -> PyResult<Self> {
220 Self::new_with_env(
221 api_key,
222 api_secret,
223 base_url,
224 demo,
225 testnet,
226 timeout_secs,
227 max_retries,
228 retry_delay_ms,
229 retry_delay_max_ms,
230 recv_window_ms,
231 proxy_url,
232 )
233 .map_err(to_pyvalue_err)
234 }
235
236 #[getter]
237 #[pyo3(name = "base_url")]
238 #[must_use]
239 pub fn py_base_url(&self) -> &str {
240 self.base_url()
241 }
242
243 #[getter]
244 #[pyo3(name = "api_key")]
245 #[must_use]
246 pub fn py_api_key(&self) -> Option<&str> {
247 self.credential().map(|c| c.api_key())
248 }
249
250 #[getter]
251 #[pyo3(name = "api_key_masked")]
252 #[must_use]
253 pub fn py_api_key_masked(&self) -> Option<String> {
254 self.credential().map(|c| c.api_key_masked())
255 }
256
257 #[pyo3(name = "cache_instrument")]
259 fn py_cache_instrument(&self, py: Python, instrument: Py<PyAny>) -> PyResult<()> {
260 let inst_any = pyobject_to_instrument_any(py, instrument)?;
261 self.cache_instrument(inst_any);
262 Ok(())
263 }
264
265 #[pyo3(name = "cancel_all_requests")]
266 fn py_cancel_all_requests(&self) {
267 self.cancel_all_requests();
268 }
269
270 #[pyo3(name = "set_use_spot_position_reports")]
271 fn py_set_use_spot_position_reports(&self, value: bool) {
272 self.set_use_spot_position_reports(value);
273 }
274
275 #[pyo3(name = "set_margin_mode")]
288 fn py_set_margin_mode<'py>(
289 &self,
290 py: Python<'py>,
291 margin_mode: BybitMarginMode,
292 ) -> PyResult<Bound<'py, PyAny>> {
293 let client = self.clone();
294
295 pyo3_async_runtimes::tokio::future_into_py(py, async move {
296 client
297 .set_margin_mode(margin_mode)
298 .await
299 .map_err(to_pyvalue_err)?;
300
301 Python::attach(|py| Ok(py.None()))
302 })
303 }
304
305 #[pyo3(name = "get_account_details")]
317 fn py_get_account_details<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
318 let client = self.clone();
319
320 pyo3_async_runtimes::tokio::future_into_py(py, async move {
321 let response = client.get_account_details().await.map_err(to_pyvalue_err)?;
322
323 Python::attach(|py| {
324 let account_details = Py::new(py, response.result)?;
325 Ok(account_details.into_any())
326 })
327 })
328 }
329
330 #[pyo3(name = "set_leverage")]
343 #[pyo3(signature = (product_type, symbol, buy_leverage, sell_leverage))]
344 fn py_set_leverage<'py>(
345 &self,
346 py: Python<'py>,
347 product_type: BybitProductType,
348 symbol: String,
349 buy_leverage: String,
350 sell_leverage: String,
351 ) -> PyResult<Bound<'py, PyAny>> {
352 let client = self.clone();
353
354 pyo3_async_runtimes::tokio::future_into_py(py, async move {
355 client
356 .set_leverage(product_type, &symbol, &buy_leverage, &sell_leverage)
357 .await
358 .map_err(to_pyvalue_err)?;
359
360 Python::attach(|py| Ok(py.None()))
361 })
362 }
363
364 #[pyo3(name = "switch_mode")]
377 #[pyo3(signature = (product_type, mode, symbol=None, coin=None))]
378 fn py_switch_mode<'py>(
379 &self,
380 py: Python<'py>,
381 product_type: BybitProductType,
382 mode: BybitPositionMode,
383 symbol: Option<String>,
384 coin: Option<String>,
385 ) -> PyResult<Bound<'py, PyAny>> {
386 let client = self.clone();
387
388 pyo3_async_runtimes::tokio::future_into_py(py, async move {
389 client
390 .switch_mode(product_type, mode, symbol, coin)
391 .await
392 .map_err(to_pyvalue_err)?;
393
394 Python::attach(|py| Ok(py.None()))
395 })
396 }
397
398 #[pyo3(name = "get_spot_borrow_amount")]
413 fn py_get_spot_borrow_amount<'py>(
414 &self,
415 py: Python<'py>,
416 coin: String,
417 ) -> PyResult<Bound<'py, PyAny>> {
418 let client = self.clone();
419
420 pyo3_async_runtimes::tokio::future_into_py(py, async move {
421 let borrow_amount = client
422 .get_spot_borrow_amount(&coin)
423 .await
424 .map_err(to_pyvalue_err)?;
425
426 Ok(borrow_amount)
427 })
428 }
429
430 #[pyo3(name = "borrow_spot")]
446 #[pyo3(signature = (coin, amount))]
447 fn py_borrow_spot<'py>(
448 &self,
449 py: Python<'py>,
450 coin: String,
451 amount: Quantity,
452 ) -> PyResult<Bound<'py, PyAny>> {
453 let client = self.clone();
454
455 pyo3_async_runtimes::tokio::future_into_py(py, async move {
456 client
457 .borrow_spot(&coin, amount)
458 .await
459 .map_err(to_pyvalue_err)?;
460
461 Python::attach(|py| Ok(py.None()))
462 })
463 }
464
465 #[pyo3(name = "repay_spot_borrow")]
482 #[pyo3(signature = (coin, amount=None))]
483 fn py_repay_spot_borrow<'py>(
484 &self,
485 py: Python<'py>,
486 coin: String,
487 amount: Option<Quantity>,
488 ) -> PyResult<Bound<'py, PyAny>> {
489 let client = self.clone();
490
491 pyo3_async_runtimes::tokio::future_into_py(py, async move {
492 client
493 .repay_spot_borrow(&coin, amount)
494 .await
495 .map_err(to_pyvalue_err)?;
496
497 Python::attach(|py| Ok(py.None()))
498 })
499 }
500
501 #[pyo3(name = "repay_spot_borrow_with_conversion")]
519 #[pyo3(signature = (coin, amount=None))]
520 fn py_repay_spot_borrow_with_conversion<'py>(
521 &self,
522 py: Python<'py>,
523 coin: String,
524 amount: Option<Quantity>,
525 ) -> PyResult<Bound<'py, PyAny>> {
526 let client = self.clone();
527
528 pyo3_async_runtimes::tokio::future_into_py(py, async move {
529 client
530 .repay_spot_borrow_with_conversion(&coin, amount)
531 .await
532 .map_err(to_pyvalue_err)?;
533
534 Python::attach(|py| Ok(py.None()))
535 })
536 }
537
538 #[pyo3(name = "request_instruments")]
548 #[pyo3(signature = (product_type, symbol=None, base_coin=None))]
549 fn py_request_instruments<'py>(
550 &self,
551 py: Python<'py>,
552 product_type: BybitProductType,
553 symbol: Option<String>,
554 base_coin: Option<String>,
555 ) -> PyResult<Bound<'py, PyAny>> {
556 let client = self.clone();
557 let base_coin = base_coin.map(|s| Ustr::from(&s));
558
559 pyo3_async_runtimes::tokio::future_into_py(py, async move {
560 let instruments = client
561 .request_instruments(product_type, symbol, base_coin)
562 .await
563 .map_err(to_pyvalue_err)?;
564
565 Python::attach(|py| {
566 let py_instruments: PyResult<Vec<_>> = instruments
567 .into_iter()
568 .map(|inst| instrument_any_to_pyobject(py, inst))
569 .collect();
570 let pylist = PyList::new(py, py_instruments?)?.into_any().unbind();
571 Ok(pylist)
572 })
573 })
574 }
575
576 #[pyo3(name = "request_instrument_statuses")]
586 fn py_request_instrument_statuses<'py>(
587 &self,
588 py: Python<'py>,
589 product_type: BybitProductType,
590 ) -> PyResult<Bound<'py, PyAny>> {
591 let client = self.clone();
592
593 pyo3_async_runtimes::tokio::future_into_py(py, async move {
594 let statuses = client
595 .request_instrument_statuses(product_type)
596 .await
597 .map_err(to_pyvalue_err)?;
598
599 Python::attach(|py| {
600 let dict = PyDict::new(py);
601 for (instrument_id, action) in statuses {
602 dict.set_item(
603 instrument_id.into_bound_py_any(py)?,
604 action.into_bound_py_any(py)?,
605 )?;
606 }
607 Ok(dict.into_any().unbind())
608 })
609 })
610 }
611
612 #[pyo3(name = "request_tickers")]
625 fn py_request_tickers<'py>(
626 &self,
627 py: Python<'py>,
628 params: crate::python::params::BybitTickersParams,
629 ) -> PyResult<Bound<'py, PyAny>> {
630 let client = self.clone();
631
632 pyo3_async_runtimes::tokio::future_into_py(py, async move {
633 let tickers = client
634 .request_tickers(¶ms.into())
635 .await
636 .map_err(to_pyvalue_err)?;
637
638 Python::attach(|py| {
639 let py_tickers: PyResult<Vec<_>> = tickers
640 .into_iter()
641 .map(|ticker| Py::new(py, ticker))
642 .collect();
643 let pylist = PyList::new(py, py_tickers?)?.into_any().unbind();
644 Ok(pylist)
645 })
646 })
647 }
648
649 #[pyo3(name = "submit_order")]
660 #[pyo3(signature = (
661 account_id,
662 product_type,
663 instrument_id,
664 client_order_id,
665 order_side,
666 order_type,
667 quantity,
668 time_in_force = None,
669 price = None,
670 trigger_price = None,
671 post_only = None,
672 reduce_only = false,
673 is_quote_quantity = false,
674 is_leverage = false,
675 position_idx = None,
676 bbo_side_type = None,
677 bbo_level = None,
678 smp_type = None,
679 native_tp_sl = None,
680 ))]
681 #[expect(clippy::too_many_arguments)]
682 fn py_submit_order<'py>(
683 &self,
684 py: Python<'py>,
685 account_id: AccountId,
686 product_type: BybitProductType,
687 instrument_id: InstrumentId,
688 client_order_id: ClientOrderId,
689 order_side: OrderSide,
690 order_type: OrderType,
691 quantity: Quantity,
692 time_in_force: Option<TimeInForce>,
693 price: Option<Price>,
694 trigger_price: Option<Price>,
695 post_only: Option<bool>,
696 reduce_only: bool,
697 is_quote_quantity: bool,
698 is_leverage: bool,
699 position_idx: Option<BybitPositionIdx>,
700 bbo_side_type: Option<String>,
701 bbo_level: Option<String>,
702 smp_type: Option<String>,
703 native_tp_sl: Option<BybitNativeTpSlParams>,
704 ) -> PyResult<Bound<'py, PyAny>> {
705 let client = self.clone();
706 let bbo_side_type = bbo_side_type
707 .map(|value| parse_bbo_side_type(&value))
708 .transpose()
709 .map_err(to_pyvalue_err)?;
710 let bbo_level = bbo_level
711 .map(parse_bbo_level)
712 .transpose()
713 .map_err(to_pyvalue_err)?;
714 if bbo_side_type.is_some() != bbo_level.is_some() {
715 return Err(to_pyvalue_err(anyhow::anyhow!(
716 "'bbo_side_type' and 'bbo_level' must be provided together"
717 )));
718 }
719
720 let smp_type = smp_type
721 .map(|value| parse_smp_type(&value))
722 .transpose()
723 .map_err(to_pyvalue_err)?;
724
725 let native_tp_sl: Option<RustNativeTpSlParams> = native_tp_sl
726 .map(RustNativeTpSlParams::try_from)
727 .transpose()
728 .map_err(to_pyvalue_err)?;
729
730 pyo3_async_runtimes::tokio::future_into_py(py, async move {
731 let report = client
732 .submit_order(
733 account_id,
734 product_type,
735 instrument_id,
736 client_order_id,
737 order_side,
738 order_type,
739 quantity,
740 time_in_force,
741 price,
742 trigger_price,
743 post_only,
744 reduce_only,
745 is_quote_quantity,
746 is_leverage,
747 position_idx,
748 bbo_side_type,
749 bbo_level,
750 smp_type,
751 native_tp_sl.as_ref(),
752 )
753 .await
754 .map_err(to_pyvalue_err)?;
755
756 Python::attach(|py| report.into_py_any(py))
757 })
758 }
759
760 #[pyo3(name = "modify_order")]
771 #[pyo3(signature = (
772 account_id,
773 product_type,
774 instrument_id,
775 client_order_id=None,
776 venue_order_id=None,
777 quantity=None,
778 price=None,
779 trigger_price=None
780 ))]
781 #[expect(clippy::too_many_arguments)]
782 fn py_modify_order<'py>(
783 &self,
784 py: Python<'py>,
785 account_id: AccountId,
786 product_type: BybitProductType,
787 instrument_id: InstrumentId,
788 client_order_id: Option<ClientOrderId>,
789 venue_order_id: Option<VenueOrderId>,
790 quantity: Option<Quantity>,
791 price: Option<Price>,
792 trigger_price: Option<Price>,
793 ) -> PyResult<Bound<'py, PyAny>> {
794 let client = self.clone();
795
796 pyo3_async_runtimes::tokio::future_into_py(py, async move {
797 let report = client
798 .modify_order(
799 account_id,
800 product_type,
801 instrument_id,
802 client_order_id,
803 venue_order_id,
804 quantity,
805 price,
806 trigger_price,
807 )
808 .await
809 .map_err(to_pyvalue_err)?;
810
811 Python::attach(|py| report.into_py_any(py))
812 })
813 }
814
815 #[pyo3(name = "cancel_order")]
828 #[pyo3(signature = (account_id, product_type, instrument_id, client_order_id=None, venue_order_id=None))]
829 fn py_cancel_order<'py>(
830 &self,
831 py: Python<'py>,
832 account_id: AccountId,
833 product_type: BybitProductType,
834 instrument_id: InstrumentId,
835 client_order_id: Option<ClientOrderId>,
836 venue_order_id: Option<VenueOrderId>,
837 ) -> PyResult<Bound<'py, PyAny>> {
838 let client = self.clone();
839
840 pyo3_async_runtimes::tokio::future_into_py(py, async move {
841 let report = client
842 .cancel_order(
843 account_id,
844 product_type,
845 instrument_id,
846 client_order_id,
847 venue_order_id,
848 )
849 .await
850 .map_err(to_pyvalue_err)?;
851
852 Python::attach(|py| report.into_py_any(py))
853 })
854 }
855
856 #[pyo3(name = "cancel_all_orders")]
865 fn py_cancel_all_orders<'py>(
866 &self,
867 py: Python<'py>,
868 account_id: AccountId,
869 product_type: BybitProductType,
870 instrument_id: InstrumentId,
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 .cancel_all_orders(account_id, product_type, instrument_id)
877 .await
878 .map_err(to_pyvalue_err)?;
879
880 Python::attach(|py| {
881 let py_reports: PyResult<Vec<_>> = reports
882 .into_iter()
883 .map(|report| report.into_py_any(py))
884 .collect();
885 let pylist = PyList::new(py, py_reports?)?.into_any().unbind();
886 Ok(pylist)
887 })
888 })
889 }
890
891 #[pyo3(name = "query_order")]
900 #[pyo3(signature = (account_id, product_type, instrument_id, client_order_id=None, venue_order_id=None))]
901 fn py_query_order<'py>(
902 &self,
903 py: Python<'py>,
904 account_id: AccountId,
905 product_type: BybitProductType,
906 instrument_id: InstrumentId,
907 client_order_id: Option<ClientOrderId>,
908 venue_order_id: Option<VenueOrderId>,
909 ) -> PyResult<Bound<'py, PyAny>> {
910 let client = self.clone();
911
912 pyo3_async_runtimes::tokio::future_into_py(py, async move {
913 match client
914 .query_order(
915 account_id,
916 product_type,
917 instrument_id,
918 client_order_id,
919 venue_order_id,
920 )
921 .await
922 {
923 Ok(Some(report)) => Python::attach(|py| report.into_py_any(py)),
924 Ok(None) => Ok(Python::attach(|py| py.None())),
925 Err(e) => Err(to_pyvalue_err(e)),
926 }
927 })
928 }
929
930 #[pyo3(name = "request_trades")]
950 #[pyo3(signature = (product_type, instrument_id, limit=None))]
951 fn py_request_trades<'py>(
952 &self,
953 py: Python<'py>,
954 product_type: BybitProductType,
955 instrument_id: InstrumentId,
956 limit: Option<u32>,
957 ) -> PyResult<Bound<'py, PyAny>> {
958 let client = self.clone();
959
960 pyo3_async_runtimes::tokio::future_into_py(py, async move {
961 let trades = client
962 .request_trades(product_type, instrument_id, limit)
963 .await
964 .map_err(to_pyvalue_err)?;
965
966 Python::attach(|py| {
967 let py_trades: PyResult<Vec<_>> = trades
968 .into_iter()
969 .map(|trade| trade.into_py_any(py))
970 .collect();
971 let pylist = PyList::new(py, py_trades?)?.into_any().unbind();
972 Ok(pylist)
973 })
974 })
975 }
976
977 #[pyo3(name = "request_funding_rates")]
990 #[pyo3(signature = (product_type, instrument_id, start=None, end=None, limit=None))]
991 fn py_request_funding_rates<'py>(
992 &self,
993 py: Python<'py>,
994 product_type: BybitProductType,
995 instrument_id: InstrumentId,
996 start: Option<Timestamp>,
997 end: Option<Timestamp>,
998 limit: Option<u32>,
999 ) -> PyResult<Bound<'py, PyAny>> {
1000 let client = self.clone();
1001
1002 pyo3_async_runtimes::tokio::future_into_py(py, async move {
1003 let funding_rates = client
1004 .request_funding_rates(product_type, instrument_id, start, end, limit)
1005 .await
1006 .map_err(to_pyvalue_err)?;
1007
1008 Python::attach(|py| {
1009 let py_funding_rates: PyResult<Vec<_>> = funding_rates
1010 .into_iter()
1011 .map(|funding_rate| funding_rate.into_py_any(py))
1012 .collect();
1013 let pylist = PyList::new(py, py_funding_rates?)?.into_any().unbind();
1014 Ok(pylist)
1015 })
1016 })
1017 }
1018
1019 #[pyo3(name = "request_orderbook_snapshot")]
1037 #[pyo3(signature = (product_type, instrument_id, limit=None))]
1038 fn py_request_orderbook_snapshot<'py>(
1039 &self,
1040 py: Python<'py>,
1041 product_type: BybitProductType,
1042 instrument_id: InstrumentId,
1043 limit: Option<u32>,
1044 ) -> PyResult<Bound<'py, PyAny>> {
1045 let client = self.clone();
1046
1047 pyo3_async_runtimes::tokio::future_into_py(py, async move {
1048 let deltas = client
1049 .request_orderbook_snapshot(product_type, instrument_id, limit)
1050 .await
1051 .map_err(to_pyvalue_err)?;
1052
1053 Python::attach(|py| deltas.into_py_any(py))
1054 })
1055 }
1056
1057 #[pyo3(name = "request_bars")]
1070 #[pyo3(signature = (product_type, bar_type, start=None, end=None, limit=None, timestamp_on_close=true))]
1071 #[expect(clippy::too_many_arguments)]
1072 fn py_request_bars<'py>(
1073 &self,
1074 py: Python<'py>,
1075 product_type: BybitProductType,
1076 bar_type: BarType,
1077 start: Option<Timestamp>,
1078 end: Option<Timestamp>,
1079 limit: Option<u32>,
1080 timestamp_on_close: bool,
1081 ) -> PyResult<Bound<'py, PyAny>> {
1082 let client = self.clone();
1083
1084 pyo3_async_runtimes::tokio::future_into_py(py, async move {
1085 let bars = client
1086 .request_bars(
1087 product_type,
1088 bar_type,
1089 start,
1090 end,
1091 limit,
1092 timestamp_on_close,
1093 )
1094 .await
1095 .map_err(to_pyvalue_err)?;
1096
1097 Python::attach(|py| {
1098 let py_bars: PyResult<Vec<_>> =
1099 bars.into_iter().map(|bar| bar.into_py_any(py)).collect();
1100 let pylist = PyList::new(py, py_bars?)?.into_any().unbind();
1101 Ok(pylist)
1102 })
1103 })
1104 }
1105
1106 #[pyo3(name = "request_fee_rates")]
1118 #[pyo3(signature = (product_type, symbol=None, base_coin=None))]
1119 fn py_request_fee_rates<'py>(
1120 &self,
1121 py: Python<'py>,
1122 product_type: BybitProductType,
1123 symbol: Option<String>,
1124 base_coin: Option<String>,
1125 ) -> PyResult<Bound<'py, PyAny>> {
1126 let client = self.clone();
1127
1128 pyo3_async_runtimes::tokio::future_into_py(py, async move {
1129 let fee_rates = client
1130 .request_fee_rates(product_type, symbol, base_coin)
1131 .await
1132 .map_err(to_pyvalue_err)?;
1133
1134 Python::attach(|py| {
1135 let py_fee_rates: PyResult<Vec<_>> = fee_rates
1136 .into_iter()
1137 .map(|rate| Py::new(py, rate))
1138 .collect();
1139 let pylist = PyList::new(py, py_fee_rates?)?.into_any().unbind();
1140 Ok(pylist)
1141 })
1142 })
1143 }
1144
1145 #[pyo3(name = "request_account_state")]
1157 fn py_request_account_state<'py>(
1158 &self,
1159 py: Python<'py>,
1160 account_type: crate::common::enums::BybitAccountType,
1161 account_id: AccountId,
1162 ) -> PyResult<Bound<'py, PyAny>> {
1163 let client = self.clone();
1164
1165 pyo3_async_runtimes::tokio::future_into_py(py, async move {
1166 let account_state = client
1167 .request_account_state(account_type, account_id)
1168 .await
1169 .map_err(to_pyvalue_err)?;
1170
1171 Python::attach(|py| account_state.into_py_any(py))
1172 })
1173 }
1174
1175 #[pyo3(name = "request_order_status_reports")]
1192 #[pyo3(signature = (account_id, product_type, instrument_id=None, open_only=false, start=None, end=None, limit=None))]
1193 #[expect(clippy::too_many_arguments)]
1194 fn py_request_order_status_reports<'py>(
1195 &self,
1196 py: Python<'py>,
1197 account_id: AccountId,
1198 product_type: BybitProductType,
1199 instrument_id: Option<InstrumentId>,
1200 open_only: bool,
1201 start: Option<Timestamp>,
1202 end: Option<Timestamp>,
1203 limit: Option<u32>,
1204 ) -> PyResult<Bound<'py, PyAny>> {
1205 let client = self.clone();
1206
1207 pyo3_async_runtimes::tokio::future_into_py(py, async move {
1208 let reports = client
1209 .request_order_status_reports(
1210 account_id,
1211 product_type,
1212 instrument_id,
1213 open_only,
1214 start,
1215 end,
1216 limit,
1217 )
1218 .await
1219 .map_err(to_pyvalue_err)?;
1220
1221 Python::attach(|py| {
1222 let py_reports: PyResult<Vec<_>> = reports
1223 .into_iter()
1224 .map(|report| report.into_py_any(py))
1225 .collect();
1226 let pylist = PyList::new(py, py_reports?)?.into_any().unbind();
1227 Ok(pylist)
1228 })
1229 })
1230 }
1231
1232 #[pyo3(name = "request_fill_reports")]
1248 #[pyo3(signature = (account_id, product_type, instrument_id=None, start=None, end=None, limit=None))]
1249 #[expect(clippy::too_many_arguments)]
1250 fn py_request_fill_reports<'py>(
1251 &self,
1252 py: Python<'py>,
1253 account_id: AccountId,
1254 product_type: BybitProductType,
1255 instrument_id: Option<InstrumentId>,
1256 start: Option<i64>,
1257 end: Option<i64>,
1258 limit: Option<u32>,
1259 ) -> PyResult<Bound<'py, PyAny>> {
1260 let client = self.clone();
1261
1262 pyo3_async_runtimes::tokio::future_into_py(py, async move {
1263 let reports = client
1264 .request_fill_reports(account_id, product_type, instrument_id, start, end, limit)
1265 .await
1266 .map_err(to_pyvalue_err)?;
1267
1268 Python::attach(|py| {
1269 let py_reports: PyResult<Vec<_>> = reports
1270 .into_iter()
1271 .map(|report| report.into_py_any(py))
1272 .collect();
1273 let pylist = PyList::new(py, py_reports?)?.into_any().unbind();
1274 Ok(pylist)
1275 })
1276 })
1277 }
1278
1279 #[pyo3(name = "request_position_status_reports")]
1300 #[pyo3(signature = (account_id, product_type, instrument_id=None))]
1301 fn py_request_position_status_reports<'py>(
1302 &self,
1303 py: Python<'py>,
1304 account_id: AccountId,
1305 product_type: BybitProductType,
1306 instrument_id: Option<InstrumentId>,
1307 ) -> PyResult<Bound<'py, PyAny>> {
1308 let client = self.clone();
1309
1310 pyo3_async_runtimes::tokio::future_into_py(py, async move {
1311 let reports = client
1312 .request_position_status_reports(account_id, product_type, instrument_id)
1313 .await
1314 .map_err(to_pyvalue_err)?;
1315
1316 Python::attach(|py| {
1317 let py_reports: PyResult<Vec<_>> = reports
1318 .into_iter()
1319 .map(|report| report.into_py_any(py))
1320 .collect();
1321 let pylist = PyList::new(py, py_reports?)?.into_any().unbind();
1322 Ok(pylist)
1323 })
1324 })
1325 }
1326}
1327
1328impl From<BybitHttpError> for PyErr {
1329 fn from(error: BybitHttpError) -> Self {
1330 match error {
1331 BybitHttpError::Canceled(msg) => to_pyruntime_err(format!("Request canceled: {msg}")),
1333 BybitHttpError::NetworkError(msg) => to_pyruntime_err(format!("Network error: {msg}")),
1334 BybitHttpError::UnexpectedStatus { status, body } => {
1335 to_pyruntime_err(format!("Unexpected HTTP status code {status}: {body}"))
1336 }
1337 BybitHttpError::MissingCredentials => {
1339 to_pyvalue_err("Missing credentials for authenticated request")
1340 }
1341 BybitHttpError::ValidationError(msg) => {
1342 to_pyvalue_err(format!("Parameter validation error: {msg}"))
1343 }
1344 BybitHttpError::JsonError(msg) => to_pyvalue_err(format!("JSON error: {msg}")),
1345 BybitHttpError::BuildError(e) => to_pyvalue_err(format!("Build error: {e}")),
1346 BybitHttpError::BybitError {
1347 error_code,
1348 message,
1349 } => to_pyvalue_err(format!("Bybit error {error_code}: {message}")),
1350 }
1351 }
1352}