nautilus-bybit 0.57.0

Bybit exchange integration adapter for the Nautilus trading engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Python bindings for the Bybit HTTP client.

use std::collections::HashSet;

use chrono::{DateTime, Utc};
use nautilus_core::{
    UnixNanos,
    python::{to_pyruntime_err, to_pyvalue_err},
};
use nautilus_model::{
    data::{BarType, forward::ForwardPrice},
    enums::{OrderSide, OrderType, TimeInForce},
    identifiers::{AccountId, ClientOrderId, InstrumentId, Symbol, VenueOrderId},
    python::instruments::{instrument_any_to_pyobject, pyobject_to_instrument_any},
    types::{Price, Quantity},
};
use pyo3::{
    conversion::IntoPyObjectExt,
    prelude::*,
    types::{PyDict, PyList},
};
use ustr::Ustr;

use crate::{
    common::{
        enums::{
            BybitMarginMode, BybitOpenOnly, BybitOrderFilter, BybitPositionIdx, BybitPositionMode,
            BybitProductType,
        },
        parse::{extract_raw_symbol, parse_bbo_level, parse_bbo_side_type},
    },
    http::{
        client::{BybitHttpClient, BybitRawHttpClient},
        error::BybitHttpError,
        models::BybitOrderCursorList,
    },
};

#[pymethods]
#[pyo3_stub_gen::derive::gen_stub_pymethods]
impl BybitRawHttpClient {
    /// Raw HTTP client for low-level Bybit API operations.
    ///
    /// This client handles request/response operations with the Bybit API,
    /// returning venue-specific response types. It does not parse to Nautilus domain types.
    #[new]
    #[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))]
    #[expect(clippy::too_many_arguments)]
    fn py_new(
        api_key: Option<String>,
        api_secret: Option<String>,
        base_url: Option<String>,
        demo: bool,
        testnet: bool,
        timeout_secs: u64,
        max_retries: u32,
        retry_delay_ms: u64,
        retry_delay_max_ms: u64,
        recv_window_ms: u64,
        proxy_url: Option<String>,
    ) -> PyResult<Self> {
        Self::new_with_env(
            api_key,
            api_secret,
            base_url,
            demo,
            testnet,
            timeout_secs,
            max_retries,
            retry_delay_ms,
            retry_delay_max_ms,
            recv_window_ms,
            proxy_url,
        )
        .map_err(to_pyvalue_err)
    }

    /// Returns the base URL used for requests.
    #[getter]
    #[pyo3(name = "base_url")]
    #[must_use]
    pub fn py_base_url(&self) -> &str {
        self.base_url()
    }

    #[getter]
    #[pyo3(name = "api_key")]
    #[must_use]
    pub fn py_api_key(&self) -> Option<String> {
        self.credential().map(|c| c.api_key().to_string())
    }

    /// Returns the configured receive window in milliseconds.
    #[getter]
    #[pyo3(name = "recv_window_ms")]
    #[must_use]
    pub fn py_recv_window_ms(&self) -> u64 {
        self.recv_window_ms()
    }

    /// Cancels all pending HTTP requests.
    #[pyo3(name = "cancel_all_requests")]
    fn py_cancel_all_requests(&self) {
        self.cancel_all_requests();
    }

    /// Fetches the current server time from Bybit.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or the response cannot be parsed.
    ///
    /// # References
    ///
    /// - <https://bybit-exchange.github.io/docs/v5/market/time>
    #[pyo3(name = "get_server_time")]
    fn py_get_server_time<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let response = client.get_server_time().await.map_err(to_pyvalue_err)?;

            Python::attach(|py| {
                let server_time = Py::new(py, response.result)?;
                Ok(server_time.into_any())
            })
        })
    }

    /// Fetches open orders (requires authentication).
    ///
    /// # References
    ///
    /// - <https://bybit-exchange.github.io/docs/v5/order/open-order>
    #[pyo3(name = "get_open_orders")]
    #[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))]
    #[expect(clippy::too_many_arguments)]
    fn py_get_open_orders<'py>(
        &self,
        py: Python<'py>,
        category: BybitProductType,
        symbol: Option<String>,
        base_coin: Option<String>,
        settle_coin: Option<String>,
        order_id: Option<String>,
        order_link_id: Option<String>,
        open_only: Option<BybitOpenOnly>,
        order_filter: Option<BybitOrderFilter>,
        limit: Option<u32>,
        cursor: Option<String>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let response = client
                .get_open_orders(
                    category,
                    symbol,
                    base_coin,
                    settle_coin,
                    order_id,
                    order_link_id,
                    open_only,
                    order_filter,
                    limit,
                    cursor,
                )
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| {
                let open_orders = BybitOrderCursorList::from(response.result);
                let py_open_orders = Py::new(py, open_orders)?;
                Ok(py_open_orders.into_any())
            })
        })
    }
}

#[pymethods]
#[pyo3_stub_gen::derive::gen_stub_pymethods]
impl BybitHttpClient {
    /// Provides a HTTP client for connecting to the [Bybit](https://bybit.com) REST API.
    /// High-level HTTP client that wraps the raw client and provides Nautilus domain types.
    ///
    /// This client maintains an instrument cache and uses it to parse venue responses
    /// into Nautilus domain objects.
    #[new]
    #[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))]
    #[expect(clippy::too_many_arguments)]
    fn py_new(
        api_key: Option<String>,
        api_secret: Option<String>,
        base_url: Option<String>,
        demo: bool,
        testnet: bool,
        timeout_secs: u64,
        max_retries: u32,
        retry_delay_ms: u64,
        retry_delay_max_ms: u64,
        recv_window_ms: u64,
        proxy_url: Option<String>,
    ) -> PyResult<Self> {
        Self::new_with_env(
            api_key,
            api_secret,
            base_url,
            demo,
            testnet,
            timeout_secs,
            max_retries,
            retry_delay_ms,
            retry_delay_max_ms,
            recv_window_ms,
            proxy_url,
        )
        .map_err(to_pyvalue_err)
    }

    #[getter]
    #[pyo3(name = "base_url")]
    #[must_use]
    pub fn py_base_url(&self) -> &str {
        self.base_url()
    }

    #[getter]
    #[pyo3(name = "api_key")]
    #[must_use]
    pub fn py_api_key(&self) -> Option<&str> {
        self.credential().map(|c| c.api_key())
    }

    #[getter]
    #[pyo3(name = "api_key_masked")]
    #[must_use]
    pub fn py_api_key_masked(&self) -> Option<String> {
        self.credential().map(|c| c.api_key_masked())
    }

    /// Any existing instrument with the same symbol will be replaced.
    #[pyo3(name = "cache_instrument")]
    fn py_cache_instrument(&self, py: Python, instrument: Py<PyAny>) -> PyResult<()> {
        let inst_any = pyobject_to_instrument_any(py, instrument)?;
        self.cache_instrument(inst_any);
        Ok(())
    }

    #[pyo3(name = "cancel_all_requests")]
    fn py_cancel_all_requests(&self) {
        self.cancel_all_requests();
    }

    #[pyo3(name = "set_use_spot_position_reports")]
    fn py_set_use_spot_position_reports(&self, value: bool) {
        self.set_use_spot_position_reports(value);
    }

    /// Sets margin mode (requires authentication).
    ///
    /// # References
    ///
    /// - <https://bybit-exchange.github.io/docs/v5/account/set-margin-mode>
    #[pyo3(name = "set_margin_mode")]
    fn py_set_margin_mode<'py>(
        &self,
        py: Python<'py>,
        margin_mode: BybitMarginMode,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            client
                .set_margin_mode(margin_mode)
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| Ok(py.None()))
        })
    }

    /// Fetches API key information including account details (requires authentication).
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The request fails.
    /// - The response cannot be parsed.
    ///
    /// # References
    ///
    /// - <https://bybit-exchange.github.io/docs/v5/user/apikey-info>
    #[pyo3(name = "get_account_details")]
    fn py_get_account_details<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let response = client.get_account_details().await.map_err(to_pyvalue_err)?;

            Python::attach(|py| {
                let account_details = Py::new(py, response.result)?;
                Ok(account_details.into_any())
            })
        })
    }

    /// Sets leverage for a symbol (requires authentication).
    ///
    /// # References
    ///
    /// - <https://bybit-exchange.github.io/docs/v5/position/leverage>
    #[pyo3(name = "set_leverage")]
    #[pyo3(signature = (product_type, symbol, buy_leverage, sell_leverage))]
    fn py_set_leverage<'py>(
        &self,
        py: Python<'py>,
        product_type: BybitProductType,
        symbol: String,
        buy_leverage: String,
        sell_leverage: String,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            client
                .set_leverage(product_type, &symbol, &buy_leverage, &sell_leverage)
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| Ok(py.None()))
        })
    }

    /// Switches position mode (requires authentication).
    ///
    /// # References
    ///
    /// - <https://bybit-exchange.github.io/docs/v5/position/position-mode>
    #[pyo3(name = "switch_mode")]
    #[pyo3(signature = (product_type, mode, symbol=None, coin=None))]
    fn py_switch_mode<'py>(
        &self,
        py: Python<'py>,
        product_type: BybitProductType,
        mode: BybitPositionMode,
        symbol: Option<String>,
        coin: Option<String>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            client
                .switch_mode(product_type, mode, symbol, coin)
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| Ok(py.None()))
        })
    }

    /// Get the outstanding spot borrow amount for a specific coin.
    ///
    /// Returns zero if no borrow exists.
    ///
    /// # Parameters
    ///
    /// - `coin`: The coin to check (e.g., "BTC", "ETH")
    #[pyo3(name = "get_spot_borrow_amount")]
    fn py_get_spot_borrow_amount<'py>(
        &self,
        py: Python<'py>,
        coin: String,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let borrow_amount = client
                .get_spot_borrow_amount(&coin)
                .await
                .map_err(to_pyvalue_err)?;

            Ok(borrow_amount)
        })
    }

    /// Borrows coins for spot margin trading.
    ///
    /// This should be called before opening short spot positions.
    ///
    /// # Parameters
    ///
    /// - `coin`: The coin to repay (e.g., "BTC", "ETH")
    /// - `amount`: Optional amount to borrow. If None, repays all outstanding borrows.
    #[pyo3(name = "borrow_spot")]
    #[pyo3(signature = (coin, amount))]
    fn py_borrow_spot<'py>(
        &self,
        py: Python<'py>,
        coin: String,
        amount: Quantity,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            client
                .borrow_spot(&coin, amount)
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| Ok(py.None()))
        })
    }

    /// Repays spot borrows for a specific coin.
    ///
    /// This should be called after closing short spot positions to avoid accruing interest.
    ///
    /// # Parameters
    ///
    /// - `coin`: The coin to repay (e.g., "BTC", "ETH")
    /// - `amount`: Optional amount to repay. If None, repays all outstanding borrows.
    #[pyo3(name = "repay_spot_borrow")]
    #[pyo3(signature = (coin, amount=None))]
    fn py_repay_spot_borrow<'py>(
        &self,
        py: Python<'py>,
        coin: String,
        amount: Option<Quantity>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            client
                .repay_spot_borrow(&coin, amount)
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| Ok(py.None()))
        })
    }

    /// Request instruments for a given product type.
    ///
    /// When `base_coin` is provided, the request is narrowed to that base coin.
    /// This is required for `Option`: Bybit's API returns only `BTC` options when
    /// `baseCoin` is omitted.
    #[pyo3(name = "request_instruments")]
    #[pyo3(signature = (product_type, symbol=None, base_coin=None))]
    fn py_request_instruments<'py>(
        &self,
        py: Python<'py>,
        product_type: BybitProductType,
        symbol: Option<String>,
        base_coin: Option<String>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();
        let base_coin = base_coin.map(|s| Ustr::from(&s));

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let instruments = client
                .request_instruments(product_type, symbol, base_coin)
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| {
                let py_instruments: PyResult<Vec<_>> = instruments
                    .into_iter()
                    .map(|inst| instrument_any_to_pyobject(py, inst))
                    .collect();
                let pylist = PyList::new(py, py_instruments?)
                    .unwrap()
                    .into_any()
                    .unbind();
                Ok(pylist)
            })
        })
    }

    /// Fetches instrument info and returns the current status of each symbol.
    ///
    /// Paginates through the instruments endpoint collecting only
    /// `(InstrumentId, MarketStatusAction)` pairs. This avoids fee-rate
    /// fetching and full instrument parsing.
    #[pyo3(name = "request_instrument_statuses")]
    fn py_request_instrument_statuses<'py>(
        &self,
        py: Python<'py>,
        product_type: BybitProductType,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let statuses = client
                .request_instrument_statuses(product_type)
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| {
                let dict = PyDict::new(py);
                for (instrument_id, action) in statuses {
                    dict.set_item(
                        instrument_id.into_bound_py_any(py)?,
                        action.into_bound_py_any(py)?,
                    )?;
                }
                Ok(dict.into_any().unbind())
            })
        })
    }

    /// Request ticker information for market data.
    ///
    /// Fetches ticker data from Bybit's `/v5/market/tickers` endpoint and returns
    /// a unified `BybitTickerData` structure compatible with all product types.
    ///
    /// # References
    ///
    /// <https://bybit-exchange.github.io/docs/v5/market/tickers>
    #[pyo3(name = "request_tickers")]
    fn py_request_tickers<'py>(
        &self,
        py: Python<'py>,
        params: crate::python::params::BybitTickersParams,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let tickers = client
                .request_tickers(&params.into())
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| {
                let py_tickers: PyResult<Vec<_>> = tickers
                    .into_iter()
                    .map(|ticker| Py::new(py, ticker))
                    .collect();
                let pylist = PyList::new(py, py_tickers?).unwrap().into_any().unbind();
                Ok(pylist)
            })
        })
    }

    /// Submit a new order.
    #[pyo3(name = "submit_order")]
    #[pyo3(signature = (
        account_id,
        product_type,
        instrument_id,
        client_order_id,
        order_side,
        order_type,
        quantity,
        time_in_force = None,
        price = None,
        trigger_price = None,
        post_only = None,
        reduce_only = false,
        is_quote_quantity = false,
        is_leverage = false,
        position_idx = None,
        bbo_side_type = None,
        bbo_level = None,
    ))]
    #[expect(clippy::too_many_arguments)]
    fn py_submit_order<'py>(
        &self,
        py: Python<'py>,
        account_id: AccountId,
        product_type: BybitProductType,
        instrument_id: InstrumentId,
        client_order_id: ClientOrderId,
        order_side: OrderSide,
        order_type: OrderType,
        quantity: Quantity,
        time_in_force: Option<TimeInForce>,
        price: Option<Price>,
        trigger_price: Option<Price>,
        post_only: Option<bool>,
        reduce_only: bool,
        is_quote_quantity: bool,
        is_leverage: bool,
        position_idx: Option<BybitPositionIdx>,
        bbo_side_type: Option<String>,
        bbo_level: Option<String>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();
        let bbo_side_type = bbo_side_type
            .map(|value| parse_bbo_side_type(&value))
            .transpose()
            .map_err(to_pyvalue_err)?;
        let bbo_level = bbo_level
            .map(parse_bbo_level)
            .transpose()
            .map_err(to_pyvalue_err)?;
        if bbo_side_type.is_some() != bbo_level.is_some() {
            return Err(to_pyvalue_err(anyhow::anyhow!(
                "'bbo_side_type' and 'bbo_level' must be provided together"
            )));
        }

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let report = client
                .submit_order(
                    account_id,
                    product_type,
                    instrument_id,
                    client_order_id,
                    order_side,
                    order_type,
                    quantity,
                    time_in_force,
                    price,
                    trigger_price,
                    post_only,
                    reduce_only,
                    is_quote_quantity,
                    is_leverage,
                    position_idx,
                    bbo_side_type,
                    bbo_level,
                )
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| report.into_py_any(py))
        })
    }

    /// Modify an existing order.
    #[pyo3(name = "modify_order")]
    #[pyo3(signature = (
        account_id,
        product_type,
        instrument_id,
        client_order_id=None,
        venue_order_id=None,
        quantity=None,
        price=None
    ))]
    #[expect(clippy::too_many_arguments)]
    fn py_modify_order<'py>(
        &self,
        py: Python<'py>,
        account_id: AccountId,
        product_type: BybitProductType,
        instrument_id: InstrumentId,
        client_order_id: Option<ClientOrderId>,
        venue_order_id: Option<VenueOrderId>,
        quantity: Option<Quantity>,
        price: Option<Price>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let report = client
                .modify_order(
                    account_id,
                    product_type,
                    instrument_id,
                    client_order_id,
                    venue_order_id,
                    quantity,
                    price,
                )
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| report.into_py_any(py))
        })
    }

    /// Cancel an order.
    #[pyo3(name = "cancel_order")]
    #[pyo3(signature = (account_id, product_type, instrument_id, client_order_id=None, venue_order_id=None))]
    fn py_cancel_order<'py>(
        &self,
        py: Python<'py>,
        account_id: AccountId,
        product_type: BybitProductType,
        instrument_id: InstrumentId,
        client_order_id: Option<ClientOrderId>,
        venue_order_id: Option<VenueOrderId>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let report = client
                .cancel_order(
                    account_id,
                    product_type,
                    instrument_id,
                    client_order_id,
                    venue_order_id,
                )
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| report.into_py_any(py))
        })
    }

    /// Cancel all orders for an instrument.
    #[pyo3(name = "cancel_all_orders")]
    fn py_cancel_all_orders<'py>(
        &self,
        py: Python<'py>,
        account_id: AccountId,
        product_type: BybitProductType,
        instrument_id: InstrumentId,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let reports = client
                .cancel_all_orders(account_id, product_type, instrument_id)
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| {
                let py_reports: PyResult<Vec<_>> = reports
                    .into_iter()
                    .map(|report| report.into_py_any(py))
                    .collect();
                let pylist = PyList::new(py, py_reports?).unwrap().into_any().unbind();
                Ok(pylist)
            })
        })
    }

    /// Query a single order by client order ID or venue order ID.
    #[pyo3(name = "query_order")]
    #[pyo3(signature = (account_id, product_type, instrument_id, client_order_id=None, venue_order_id=None))]
    fn py_query_order<'py>(
        &self,
        py: Python<'py>,
        account_id: AccountId,
        product_type: BybitProductType,
        instrument_id: InstrumentId,
        client_order_id: Option<ClientOrderId>,
        venue_order_id: Option<VenueOrderId>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            match client
                .query_order(
                    account_id,
                    product_type,
                    instrument_id,
                    client_order_id,
                    venue_order_id,
                )
                .await
            {
                Ok(Some(report)) => Python::attach(|py| report.into_py_any(py)),
                Ok(None) => Ok(Python::attach(|py| py.None())),
                Err(e) => Err(to_pyvalue_err(e)),
            }
        })
    }

    /// Request recent trade tick history for a given symbol.
    ///
    /// Returns the most recent public trades from Bybit's `/v5/market/recent-trade` endpoint.
    /// This endpoint only provides recent trades (up to 1000 most recent), typically covering
    /// only the last few minutes for active markets.
    ///
    /// **Note**: For historical trade data with time ranges, use the klines endpoint instead.
    /// The Bybit public API does not support fetching historical trades by time range.
    ///
    /// # References
    ///
    /// <https://bybit-exchange.github.io/docs/v5/market/recent-trade>
    #[pyo3(name = "request_trades")]
    #[pyo3(signature = (product_type, instrument_id, limit=None))]
    fn py_request_trades<'py>(
        &self,
        py: Python<'py>,
        product_type: BybitProductType,
        instrument_id: InstrumentId,
        limit: Option<u32>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let trades = client
                .request_trades(product_type, instrument_id, limit)
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| {
                let py_trades: PyResult<Vec<_>> = trades
                    .into_iter()
                    .map(|trade| trade.into_py_any(py))
                    .collect();
                let pylist = PyList::new(py, py_trades?).unwrap().into_any().unbind();
                Ok(pylist)
            })
        })
    }

    /// Request funding rate history for a given symbol.
    ///
    /// # References
    ///
    /// <https://bybit-exchange.github.io/docs/v5/market/history-fund-rate>
    #[pyo3(name = "request_funding_rates")]
    #[pyo3(signature = (product_type, instrument_id, start=None, end=None, limit=None))]
    fn py_request_funding_rates<'py>(
        &self,
        py: Python<'py>,
        product_type: BybitProductType,
        instrument_id: InstrumentId,
        start: Option<DateTime<Utc>>,
        end: Option<DateTime<Utc>>,
        limit: Option<u32>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let funding_rates = client
                .request_funding_rates(product_type, instrument_id, start, end, limit)
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| {
                let py_funding_rates: PyResult<Vec<_>> = funding_rates
                    .into_iter()
                    .map(|funding_rate| funding_rate.into_py_any(py))
                    .collect();
                let pylist = PyList::new(py, py_funding_rates?)
                    .unwrap()
                    .into_any()
                    .unbind();
                Ok(pylist)
            })
        })
    }

    /// Request an orderbook snapshot for a given symbol.
    ///
    /// Bybit limits the amount of levels (depth) for each product type to:
    /// - Spot: `1..=200` (default: `1`)
    /// - Linear & Inverse: `1..=500` (default: `25`)
    /// - Options: `1..=25` (default: `1`)
    ///
    /// # References
    ///
    /// <https://bybit-exchange.github.io/docs/v5/market/orderbook>
    #[pyo3(name = "request_orderbook_snapshot")]
    #[pyo3(signature = (product_type, instrument_id, limit=None))]
    fn py_request_orderbook_snapshot<'py>(
        &self,
        py: Python<'py>,
        product_type: BybitProductType,
        instrument_id: InstrumentId,
        limit: Option<u32>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let deltas = client
                .request_orderbook_snapshot(product_type, instrument_id, limit)
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| Ok(deltas.into_py_any(py).unwrap()))
        })
    }

    /// Request bar/kline history for a given symbol.
    ///
    /// # References
    ///
    /// <https://bybit-exchange.github.io/docs/v5/market/kline>
    #[pyo3(name = "request_bars")]
    #[pyo3(signature = (product_type, bar_type, start=None, end=None, limit=None, timestamp_on_close=true))]
    #[expect(clippy::too_many_arguments)]
    fn py_request_bars<'py>(
        &self,
        py: Python<'py>,
        product_type: BybitProductType,
        bar_type: BarType,
        start: Option<DateTime<Utc>>,
        end: Option<DateTime<Utc>>,
        limit: Option<u32>,
        timestamp_on_close: bool,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let bars = client
                .request_bars(
                    product_type,
                    bar_type,
                    start,
                    end,
                    limit,
                    timestamp_on_close,
                )
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| {
                let py_bars: PyResult<Vec<_>> =
                    bars.into_iter().map(|bar| bar.into_py_any(py)).collect();
                let pylist = PyList::new(py, py_bars?).unwrap().into_any().unbind();
                Ok(pylist)
            })
        })
    }

    /// Requests trading fee rates for the specified product type and optional filters.
    ///
    /// # References
    ///
    /// <https://bybit-exchange.github.io/docs/v5/account/fee-rate>
    #[pyo3(name = "request_fee_rates")]
    #[pyo3(signature = (product_type, symbol=None, base_coin=None))]
    fn py_request_fee_rates<'py>(
        &self,
        py: Python<'py>,
        product_type: BybitProductType,
        symbol: Option<String>,
        base_coin: Option<String>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let fee_rates = client
                .request_fee_rates(product_type, symbol, base_coin)
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| {
                let py_fee_rates: PyResult<Vec<_>> = fee_rates
                    .into_iter()
                    .map(|rate| Py::new(py, rate))
                    .collect();
                let pylist = PyList::new(py, py_fee_rates?).unwrap().into_any().unbind();
                Ok(pylist)
            })
        })
    }

    /// Requests the current account state for the specified account type.
    ///
    /// # References
    ///
    /// <https://bybit-exchange.github.io/docs/v5/account/wallet-balance>
    #[pyo3(name = "request_account_state")]
    fn py_request_account_state<'py>(
        &self,
        py: Python<'py>,
        account_type: crate::common::enums::BybitAccountType,
        account_id: AccountId,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let account_state = client
                .request_account_state(account_type, account_id)
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| account_state.into_py_any(py))
        })
    }

    /// Request multiple order status reports.
    ///
    /// Orders for instruments not currently loaded in cache will be skipped.
    #[pyo3(name = "request_order_status_reports")]
    #[pyo3(signature = (account_id, product_type, instrument_id=None, open_only=false, start=None, end=None, limit=None))]
    #[expect(clippy::too_many_arguments)]
    fn py_request_order_status_reports<'py>(
        &self,
        py: Python<'py>,
        account_id: AccountId,
        product_type: BybitProductType,
        instrument_id: Option<InstrumentId>,
        open_only: bool,
        start: Option<DateTime<Utc>>,
        end: Option<DateTime<Utc>>,
        limit: Option<u32>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let reports = client
                .request_order_status_reports(
                    account_id,
                    product_type,
                    instrument_id,
                    open_only,
                    start,
                    end,
                    limit,
                )
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| {
                let py_reports: PyResult<Vec<_>> = reports
                    .into_iter()
                    .map(|report| report.into_py_any(py))
                    .collect();
                let pylist = PyList::new(py, py_reports?).unwrap().into_any().unbind();
                Ok(pylist)
            })
        })
    }

    /// Fetches execution history (fills) for the account and returns a list of `FillReport`s.
    ///
    /// Executions for instruments not currently loaded in cache will be skipped.
    ///
    /// # References
    ///
    /// <https://bybit-exchange.github.io/docs/v5/order/execution>
    #[pyo3(name = "request_fill_reports")]
    #[pyo3(signature = (account_id, product_type, instrument_id=None, start=None, end=None, limit=None))]
    #[expect(clippy::too_many_arguments)]
    fn py_request_fill_reports<'py>(
        &self,
        py: Python<'py>,
        account_id: AccountId,
        product_type: BybitProductType,
        instrument_id: Option<InstrumentId>,
        start: Option<i64>,
        end: Option<i64>,
        limit: Option<u32>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let reports = client
                .request_fill_reports(account_id, product_type, instrument_id, start, end, limit)
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| {
                let py_reports: PyResult<Vec<_>> = reports
                    .into_iter()
                    .map(|report| report.into_py_any(py))
                    .collect();
                let pylist = PyList::new(py, py_reports?).unwrap().into_any().unbind();
                Ok(pylist)
            })
        })
    }

    /// Fetches position information for the account and returns a list of `PositionStatusReport`s.
    ///
    /// Positions for instruments not currently loaded in cache will be skipped.
    ///
    /// # References
    ///
    /// <https://bybit-exchange.github.io/docs/v5/position>
    #[pyo3(name = "request_position_status_reports")]
    #[pyo3(signature = (account_id, product_type, instrument_id=None))]
    fn py_request_position_status_reports<'py>(
        &self,
        py: Python<'py>,
        account_id: AccountId,
        product_type: BybitProductType,
        instrument_id: Option<InstrumentId>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let reports = client
                .request_position_status_reports(account_id, product_type, instrument_id)
                .await
                .map_err(to_pyvalue_err)?;

            Python::attach(|py| {
                let py_reports: PyResult<Vec<_>> = reports
                    .into_iter()
                    .map(|report| report.into_py_any(py))
                    .collect();
                let pylist = PyList::new(py, py_reports?).unwrap().into_any().unbind();
                Ok(pylist)
            })
        })
    }

    /// Request forward prices for option chain ATM determination.
    ///
    /// Single-instrument path (1 HTTP call) if `instrument_id` is provided,
    /// otherwise bulk path via option tickers.
    #[pyo3(name = "request_forward_prices")]
    #[pyo3(signature = (base_coin, instrument_id=None))]
    fn py_request_forward_prices<'py>(
        &self,
        py: Python<'py>,
        base_coin: String,
        instrument_id: Option<InstrumentId>,
    ) -> PyResult<Bound<'py, PyAny>> {
        let client = self.clone();

        pyo3_async_runtimes::tokio::future_into_py(py, async move {
            let forward_prices: Vec<ForwardPrice> = if let Some(inst_id) = instrument_id {
                // Single-instrument path: fetch ticker for one symbol
                let raw_symbol = extract_raw_symbol(inst_id.symbol.as_str()).to_string();
                let params = crate::http::query::BybitTickersParams {
                    category: BybitProductType::Option,
                    symbol: Some(raw_symbol),
                    base_coin: None,
                    exp_date: None,
                };
                let tickers = client
                    .request_option_tickers_raw_with_params(&params)
                    .await
                    .map_err(to_pyvalue_err)?;

                let ts = UnixNanos::default();
                tickers
                    .into_iter()
                    .filter_map(|t| {
                        let up: rust_decimal::Decimal = t.underlying_price.parse().ok()?;
                        if up.is_zero() {
                            return None;
                        }
                        Some(ForwardPrice::new(inst_id, up, None, ts, ts))
                    })
                    .collect()
            } else {
                // Bulk path: fetch all option tickers for base coin
                let tickers = client
                    .request_option_tickers_raw(&base_coin)
                    .await
                    .map_err(to_pyvalue_err)?;

                let ts = nautilus_core::UnixNanos::default();
                let mut seen_expiries = HashSet::new();
                tickers
                    .into_iter()
                    .filter_map(|t| {
                        let up: rust_decimal::Decimal = t.underlying_price.parse().ok()?;
                        if up.is_zero() {
                            return None;
                        }
                        let parts: Vec<&str> = t.symbol.splitn(3, '-').collect();
                        let expiry_key = if parts.len() >= 2 {
                            format!("{}-{}", parts[0], parts[1])
                        } else {
                            t.symbol.to_string()
                        };

                        if !seen_expiries.insert(expiry_key) {
                            return None;
                        }
                        let symbol_str = format!("{}-OPTION", t.symbol);
                        let inst_id = InstrumentId::new(
                            Symbol::new(&symbol_str),
                            *crate::common::consts::BYBIT_VENUE,
                        );
                        Some(ForwardPrice::new(inst_id, up, None, ts, ts))
                    })
                    .collect()
            };

            Python::attach(|py| {
                let py_prices: PyResult<Vec<_>> = forward_prices
                    .into_iter()
                    .map(|fp| Py::new(py, fp))
                    .collect();
                let pylist = PyList::new(py, py_prices?)?.into_any().unbind();
                Ok(pylist)
            })
        })
    }
}

impl From<BybitHttpError> for PyErr {
    fn from(error: BybitHttpError) -> Self {
        match error {
            // Runtime/operational errors
            BybitHttpError::Canceled(msg) => to_pyruntime_err(format!("Request canceled: {msg}")),
            BybitHttpError::NetworkError(msg) => to_pyruntime_err(format!("Network error: {msg}")),
            BybitHttpError::UnexpectedStatus { status, body } => {
                to_pyruntime_err(format!("Unexpected HTTP status code {status}: {body}"))
            }
            // Validation/configuration errors
            BybitHttpError::MissingCredentials => {
                to_pyvalue_err("Missing credentials for authenticated request")
            }
            BybitHttpError::ValidationError(msg) => {
                to_pyvalue_err(format!("Parameter validation error: {msg}"))
            }
            BybitHttpError::JsonError(msg) => to_pyvalue_err(format!("JSON error: {msg}")),
            BybitHttpError::BuildError(e) => to_pyvalue_err(format!("Build error: {e}")),
            BybitHttpError::BybitError {
                error_code,
                message,
            } => to_pyvalue_err(format!("Bybit error {error_code}: {message}")),
        }
    }
}