Skip to main content

nautilus_bybit/python/
http.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 the Bybit HTTP client.
17
18use 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    /// Raw HTTP client for low-level Bybit API operations.
55    ///
56    /// This client handles request/response operations with the Bybit API,
57    /// returning venue-specific response types. It does not parse to Nautilus domain types.
58    #[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    /// Returns the base URL used for requests.
91    #[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    /// Returns the configured receive window in milliseconds.
106    #[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    /// Cancels all pending HTTP requests.
114    #[pyo3(name = "cancel_all_requests")]
115    fn py_cancel_all_requests(&self) {
116        self.cancel_all_requests();
117    }
118
119    /// Fetches the current server time from Bybit.
120    ///
121    /// # Errors
122    ///
123    /// Returns an error if the request fails or the response cannot be parsed.
124    ///
125    /// # References
126    ///
127    /// - <https://bybit-exchange.github.io/docs/v5/market/time>
128    #[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    /// Fetches open orders (requires authentication).
143    ///
144    /// # Errors
145    ///
146    /// Returns an error if the request fails or the response cannot be parsed.
147    ///
148    /// # References
149    ///
150    /// - <https://bybit-exchange.github.io/docs/v5/order/open-order>
151    #[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    /// Provides a HTTP client for connecting to the [Bybit](https://bybit.com) REST API.
200    /// High-level HTTP client that wraps the raw client and provides Nautilus domain types.
201    ///
202    /// This client maintains an instrument cache and uses it to parse venue responses
203    /// into Nautilus domain objects.
204    #[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    /// Any existing instrument with the same symbol will be replaced.
258    #[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    /// Sets margin mode (requires authentication).
276    ///
277    /// # Errors
278    ///
279    /// Returns an error if:
280    /// - Credentials are missing.
281    /// - The request fails.
282    /// - The API returns an error.
283    ///
284    /// # References
285    ///
286    /// - <https://bybit-exchange.github.io/docs/v5/account/set-margin-mode>
287    #[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    /// Fetches API key information including account details (requires authentication).
306    ///
307    /// # Errors
308    ///
309    /// Returns an error if:
310    /// - The request fails.
311    /// - The response cannot be parsed.
312    ///
313    /// # References
314    ///
315    /// - <https://bybit-exchange.github.io/docs/v5/user/apikey-info>
316    #[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    /// Sets leverage for a symbol (requires authentication).
331    ///
332    /// # Errors
333    ///
334    /// Returns an error if:
335    /// - Credentials are missing.
336    /// - The request fails.
337    /// - The API returns an error.
338    ///
339    /// # References
340    ///
341    /// - <https://bybit-exchange.github.io/docs/v5/position/leverage>
342    #[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    /// Switches position mode (requires authentication).
365    ///
366    /// # Errors
367    ///
368    /// Returns an error if:
369    /// - Credentials are missing.
370    /// - The request fails.
371    /// - The API returns an error.
372    ///
373    /// # References
374    ///
375    /// - <https://bybit-exchange.github.io/docs/v5/position/position-mode>
376    #[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    /// Get the outstanding spot borrow amount for a specific coin.
399    ///
400    /// Returns zero if no borrow exists.
401    ///
402    /// # Parameters
403    ///
404    /// - `coin`: The coin to check (e.g., "BTC", "ETH")
405    ///
406    /// # Errors
407    ///
408    /// Returns an error if:
409    /// - Credentials are missing.
410    /// - The request fails.
411    /// - The coin is not found in the wallet.
412    #[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    /// Borrows coins for spot margin trading.
431    ///
432    /// This should be called before opening short spot positions.
433    ///
434    /// # Parameters
435    ///
436    /// - `coin`: The coin to repay (e.g., "BTC", "ETH")
437    /// - `amount`: Optional amount to borrow. If None, repays all outstanding borrows.
438    ///
439    /// # Errors
440    ///
441    /// Returns an error if:
442    /// - Credentials are missing.
443    /// - The request fails.
444    /// - Insufficient collateral for the borrow.
445    #[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    /// Repays spot borrows for a specific coin.
466    ///
467    /// This should be called after closing short spot positions to avoid accruing interest.
468    ///
469    /// # Parameters
470    ///
471    /// - `coin`: The coin to repay (e.g., "BTC", "ETH")
472    /// - `amount`: Optional amount to repay. If None, repays all outstanding borrows.
473    ///
474    /// # Errors
475    ///
476    /// Returns an error if:
477    /// - Credentials are missing.
478    /// - The request fails.
479    /// - Called during the hourly interest-calculation window (mm:04:00-mm:05:30 UTC each hour).
480    /// - Insufficient spot balance for repayment.
481    #[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    /// Repays spot borrows for a specific coin, converting other assets if required.
502    ///
503    /// Unlike `Self.repay_spot_borrow`, this uses the venue's manual repay endpoint,
504    /// which may draw on other holdings when the debt coin's spot balance is insufficient.
505    ///
506    /// # Parameters
507    ///
508    /// - `coin`: The coin to repay (e.g., "BTC", "ETH")
509    /// - `amount`: Optional amount to repay. If None, repays all outstanding borrows.
510    ///
511    /// # Errors
512    ///
513    /// Returns an error if:
514    /// - Credentials are missing.
515    /// - The request fails.
516    /// - Called during the hourly interest-calculation window (mm:04:00-mm:05:30 UTC each hour).
517    /// - Insufficient balance for repayment.
518    #[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    /// Request instruments for a given product type.
539    ///
540    /// When `base_coin` is provided, the request is narrowed to that base coin.
541    /// `Option` requests with neither `symbol` nor `base_coin` load all listed
542    /// base coins.
543    ///
544    /// # Errors
545    ///
546    /// Returns an error if the request fails or parsing fails.
547    #[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    /// Fetches instrument info and returns the current status of each symbol.
577    ///
578    /// Paginates through the instruments endpoint collecting only
579    /// `(InstrumentId, MarketStatusAction)` pairs. This avoids full instrument
580    /// parsing.
581    ///
582    /// # Errors
583    ///
584    /// Returns an error if the request fails.
585    #[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    /// Request ticker information for market data.
613    ///
614    /// Fetches ticker data from Bybit's `/v5/market/tickers` endpoint and returns
615    /// a unified `BybitTickerData` structure compatible with all product types.
616    ///
617    /// # Errors
618    ///
619    /// Returns an error if the request fails or parsing fails.
620    ///
621    /// # References
622    ///
623    /// <https://bybit-exchange.github.io/docs/v5/market/tickers>
624    #[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(&params.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    /// Submit a new order.
650    ///
651    /// # Errors
652    ///
653    /// Returns an error if:
654    /// - Credentials are missing.
655    /// - The request fails.
656    /// - Order validation fails.
657    /// - The order is rejected.
658    /// - The API returns an error.
659    #[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    /// Modify an existing order.
761    ///
762    /// # Errors
763    ///
764    /// Returns an error if:
765    /// - Credentials are missing.
766    /// - The request fails.
767    /// - The order doesn't exist.
768    /// - The order is already closed.
769    /// - The API returns an error.
770    #[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    /// Cancels an order and returns its confirmed terminal status.
816    ///
817    /// Polls until the order closes, bounded by the configured HTTP timeout.
818    ///
819    /// # Errors
820    ///
821    /// Returns an error if:
822    /// - Credentials are missing.
823    /// - The request fails.
824    /// - The order doesn't exist.
825    /// - The API returns an error.
826    /// - Terminal status confirmation times out.
827    #[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    /// Cancel all orders for an instrument.
857    ///
858    /// # Errors
859    ///
860    /// Returns an error if:
861    /// - Credentials are missing.
862    /// - The request fails.
863    /// - The API returns an error.
864    #[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    /// Query a single order by client order ID or venue order ID.
892    ///
893    /// # Errors
894    ///
895    /// Returns an error if:
896    /// - Credentials are missing.
897    /// - The request fails.
898    /// - The API returns an error.
899    #[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    /// Request recent trade tick history for a given symbol.
931    ///
932    /// Returns the most recent public trades from Bybit's `/v5/market/recent-trade` endpoint.
933    /// This endpoint only provides recent trades (up to 1000 most recent), typically covering
934    /// only the last few minutes for active markets.
935    ///
936    /// **Note**: For historical trade data with time ranges, use the klines endpoint instead.
937    /// The Bybit public API does not support fetching historical trades by time range.
938    ///
939    /// # Errors
940    ///
941    /// Returns an error if:
942    /// - The instrument is not found in cache.
943    /// - The request fails.
944    /// - Parsing fails.
945    ///
946    /// # References
947    ///
948    /// <https://bybit-exchange.github.io/docs/v5/market/recent-trade>
949    #[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    /// Request funding rate history for a given symbol.
978    ///
979    /// # Errors
980    ///
981    /// Returns an error if:
982    /// - The instrument is not found in cache.
983    /// - The request fails.
984    /// - Parsing fails.
985    ///
986    /// # References
987    ///
988    /// <https://bybit-exchange.github.io/docs/v5/market/history-fund-rate>
989    #[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    /// Request an orderbook snapshot for a given symbol.
1020    ///
1021    /// Bybit limits the amount of levels (depth) for each product type to:
1022    /// - Spot: `1..=200` (default: `1`)
1023    /// - Linear & Inverse: `1..=500` (default: `25`)
1024    /// - Options: `1..=25` (default: `1`)
1025    ///
1026    /// # Errors
1027    ///
1028    /// Returns an error if:
1029    /// - The instrument is not found in cache.
1030    /// - The request fails.
1031    /// - Parsing fails.
1032    ///
1033    /// # References
1034    ///
1035    /// <https://bybit-exchange.github.io/docs/v5/market/orderbook>
1036    #[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    /// Request bar/kline history for a given symbol.
1058    ///
1059    /// # Errors
1060    ///
1061    /// Returns an error if:
1062    /// - The instrument is not found in cache.
1063    /// - The request fails.
1064    /// - Parsing fails.
1065    ///
1066    /// # References
1067    ///
1068    /// <https://bybit-exchange.github.io/docs/v5/market/kline>
1069    #[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    /// Requests trading fee rates for the specified product type and optional filters.
1107    ///
1108    /// # Errors
1109    ///
1110    /// Returns an error if:
1111    /// - The request fails.
1112    /// - Parsing fails.
1113    ///
1114    /// # References
1115    ///
1116    /// <https://bybit-exchange.github.io/docs/v5/account/fee-rate>
1117    #[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    /// Requests the current account state for the specified account type.
1146    ///
1147    /// # Errors
1148    ///
1149    /// Returns an error if:
1150    /// - The request fails.
1151    /// - Parsing fails.
1152    ///
1153    /// # References
1154    ///
1155    /// <https://bybit-exchange.github.io/docs/v5/account/wallet-balance>
1156    #[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    /// Requests multiple order status reports.
1176    ///
1177    /// When `open_only` is true the realtime endpoint is queried for currently
1178    /// open orders and again for recently closed orders, so terminal reports
1179    /// are included. The closed pass fetches the most recent page only.
1180    ///
1181    /// Terminal orders are filtered by `updatedTime` against `start` and `end`.
1182    /// Open orders are returned regardless of age.
1183    ///
1184    /// # Errors
1185    ///
1186    /// Returns an error if:
1187    /// - Credentials are missing.
1188    /// - The request fails.
1189    /// - The API returns an error.
1190    /// - A returned order has no symbol, has no cached instrument, or cannot be parsed.
1191    #[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    /// Fetches execution history (fills) for the account and returns a list of `FillReport`s.
1233    ///
1234    /// Funding executions are skipped.
1235    ///
1236    /// # Errors
1237    ///
1238    /// Returns an error if:
1239    /// - The request fails.
1240    /// - The instrument ID is invalid.
1241    /// - Pagination cannot advance.
1242    /// - A returned fill has no symbol, has no cached instrument, or cannot be parsed.
1243    ///
1244    /// # References
1245    ///
1246    /// <https://bybit-exchange.github.io/docs/v5/order/execution>
1247    #[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    /// Fetches position information for the account and returns a list of `PositionStatusReport`s.
1280    ///
1281    /// Derivative position reports fail as a set if any row cannot be resolved or parsed.
1282    /// When SPOT position reports are enabled, the requested instrument must be cached.
1283    ///
1284    /// # Errors
1285    ///
1286    /// Returns an error if:
1287    /// - The request fails.
1288    /// - The instrument ID is invalid.
1289    /// - Pagination cannot advance.
1290    /// - A derivative position row has no symbol.
1291    /// - A derivative position's instrument, or the requested SPOT instrument, is not cached.
1292    /// - A derivative position row cannot be parsed.
1293    /// - SPOT position reports are enabled and no instrument is specified, because wallet balances
1294    ///   carry no pair identity.
1295    ///
1296    /// # References
1297    ///
1298    /// <https://bybit-exchange.github.io/docs/v5/position>
1299    #[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            // Runtime/operational errors
1332            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            // Validation/configuration errors
1338            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}