nautilus-bybit 0.55.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
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
// -------------------------------------------------------------------------------------------------
//  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.
// -------------------------------------------------------------------------------------------------

//! Data transfer objects for deserializing Bybit HTTP API payloads.

use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use ustr::Ustr;

use crate::common::{
    enums::{
        BybitAccountType, BybitCancelType, BybitContractType, BybitCreateType, BybitExecType,
        BybitInnovationFlag, BybitInstrumentStatus, BybitMarginTrading, BybitOptionType,
        BybitOrderSide, BybitOrderStatus, BybitOrderType, BybitPositionIdx, BybitPositionSide,
        BybitPositionStatus, BybitProductType, BybitSmpType, BybitStopOrderType, BybitTimeInForce,
        BybitTpSlMode, BybitTriggerDirection, BybitTriggerType,
    },
    models::{
        BybitCursorList, BybitCursorListResponse, BybitListResponse, BybitResponse, LeverageFilter,
        LinearLotSizeFilter, LinearPriceFilter, OptionLotSizeFilter, SpotLotSizeFilter,
        SpotPriceFilter,
    },
    parse::{
        deserialize_decimal_or_zero, deserialize_optional_decimal_or_zero, deserialize_string_to_u8,
    },
};

/// Cursor-paginated list of orders for Python bindings.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.bybit", from_py_object)
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.bybit")
)]
pub struct BybitOrderCursorList {
    /// Collection of orders returned by the endpoint.
    pub list: Vec<BybitOrder>,
    /// Pagination cursor for the next page.
    pub next_page_cursor: Option<String>,
    /// Optional product category when the API includes it.
    #[serde(default)]
    pub category: Option<BybitProductType>,
}

impl From<BybitCursorList<BybitOrder>> for BybitOrderCursorList {
    fn from(cursor_list: BybitCursorList<BybitOrder>) -> Self {
        Self {
            list: cursor_list.list,
            next_page_cursor: cursor_list.next_page_cursor,
            category: cursor_list.category,
        }
    }
}

#[cfg(feature = "python")]
#[pyo3::pymethods]
impl BybitOrderCursorList {
    #[getter]
    #[must_use]
    pub fn list(&self) -> Vec<BybitOrder> {
        self.list.clone()
    }

    #[getter]
    #[must_use]
    pub fn next_page_cursor(&self) -> Option<&str> {
        self.next_page_cursor.as_deref()
    }

    #[getter]
    #[must_use]
    pub fn category(&self) -> Option<BybitProductType> {
        self.category
    }
}

/// Response payload returned by `GET /v5/market/time`.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/time>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.bybit", from_py_object)
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.bybit")
)]
#[serde(rename_all = "camelCase")]
pub struct BybitServerTime {
    /// Server timestamp in seconds represented as string.
    pub time_second: String,
    /// Server timestamp in nanoseconds represented as string.
    pub time_nano: String,
}

#[cfg(feature = "python")]
#[pyo3::pymethods]
impl BybitServerTime {
    #[getter]
    #[must_use]
    pub fn time_second(&self) -> &str {
        &self.time_second
    }

    #[getter]
    #[must_use]
    pub fn time_nano(&self) -> &str {
        &self.time_nano
    }
}

/// Type alias for the server time response envelope.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/time>
pub type BybitServerTimeResponse = BybitResponse<BybitServerTime>;

/// Ticker payload for spot instruments.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/tickers>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitTickerSpot {
    pub symbol: Ustr,
    pub bid1_price: String,
    pub bid1_size: String,
    pub ask1_price: String,
    pub ask1_size: String,
    pub last_price: String,
    pub prev_price24h: String,
    pub price24h_pcnt: String,
    pub high_price24h: String,
    pub low_price24h: String,
    pub turnover24h: String,
    pub volume24h: String,
    #[serde(default)]
    pub usd_index_price: String,
}

/// Ticker payload for linear and inverse perpetual/futures instruments.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/tickers>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitTickerLinear {
    pub symbol: Ustr,
    pub last_price: String,
    pub index_price: String,
    pub mark_price: String,
    pub prev_price24h: String,
    pub price24h_pcnt: String,
    pub high_price24h: String,
    pub low_price24h: String,
    pub prev_price1h: String,
    pub open_interest: String,
    pub open_interest_value: String,
    pub turnover24h: String,
    pub volume24h: String,
    pub funding_rate: String,
    pub next_funding_time: String,
    pub predicted_delivery_price: String,
    pub basis_rate: String,
    pub delivery_fee_rate: String,
    pub delivery_time: String,
    pub ask1_size: String,
    pub bid1_price: String,
    pub ask1_price: String,
    pub bid1_size: String,
    pub basis: String,
}

/// Ticker payload for option instruments.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/tickers>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitTickerOption {
    pub symbol: Ustr,
    pub bid1_price: String,
    pub bid1_size: String,
    pub bid1_iv: String,
    pub ask1_price: String,
    pub ask1_size: String,
    pub ask1_iv: String,
    pub last_price: String,
    pub high_price24h: String,
    pub low_price24h: String,
    pub mark_price: String,
    pub index_price: String,
    pub mark_iv: String,
    pub underlying_price: String,
    pub open_interest: String,
    pub turnover24h: String,
    pub volume24h: String,
    pub total_volume: String,
    pub total_turnover: String,
    pub delta: String,
    pub gamma: String,
    pub vega: String,
    pub theta: String,
    pub predicted_delivery_price: String,
    pub change24h: String,
}

/// Response alias for spot ticker requests.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/tickers>
pub type BybitTickersSpotResponse = BybitListResponse<BybitTickerSpot>;
/// Response alias for linear/inverse ticker requests.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/tickers>
pub type BybitTickersLinearResponse = BybitListResponse<BybitTickerLinear>;
/// Response alias for option ticker requests.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/tickers>
pub type BybitTickersOptionResponse = BybitListResponse<BybitTickerOption>;

/// Unified ticker data structure containing common fields across all product types.
///
/// This simplified ticker structure is designed to work across SPOT, LINEAR, and OPTION products,
/// containing only the most commonly used fields.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.bybit", from_py_object)
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.bybit")
)]
pub struct BybitTickerData {
    pub symbol: Ustr,
    pub bid1_price: String,
    pub bid1_size: String,
    pub ask1_price: String,
    pub ask1_size: String,
    pub last_price: String,
    pub high_price24h: String,
    pub low_price24h: String,
    pub turnover24h: String,
    pub volume24h: String,
    #[serde(default)]
    pub open_interest: Option<String>,
    #[serde(default)]
    pub funding_rate: Option<String>,
    #[serde(default)]
    pub next_funding_time: Option<String>,
    #[serde(default)]
    pub mark_price: Option<String>,
    #[serde(default)]
    pub index_price: Option<String>,
}

#[cfg(feature = "python")]
#[pyo3::pymethods]
impl BybitTickerData {
    #[getter]
    #[must_use]
    pub fn symbol(&self) -> &str {
        self.symbol.as_str()
    }

    #[getter]
    #[must_use]
    pub fn bid1_price(&self) -> &str {
        &self.bid1_price
    }

    #[getter]
    #[must_use]
    pub fn bid1_size(&self) -> &str {
        &self.bid1_size
    }

    #[getter]
    #[must_use]
    pub fn ask1_price(&self) -> &str {
        &self.ask1_price
    }

    #[getter]
    #[must_use]
    pub fn ask1_size(&self) -> &str {
        &self.ask1_size
    }

    #[getter]
    #[must_use]
    pub fn last_price(&self) -> &str {
        &self.last_price
    }

    #[getter]
    #[must_use]
    pub fn high_price24h(&self) -> &str {
        &self.high_price24h
    }

    #[getter]
    #[must_use]
    pub fn low_price24h(&self) -> &str {
        &self.low_price24h
    }

    #[getter]
    #[must_use]
    pub fn turnover24h(&self) -> &str {
        &self.turnover24h
    }

    #[getter]
    #[must_use]
    pub fn volume24h(&self) -> &str {
        &self.volume24h
    }

    #[getter]
    #[must_use]
    pub fn open_interest(&self) -> Option<&str> {
        self.open_interest.as_deref()
    }

    #[getter]
    #[must_use]
    pub fn funding_rate(&self) -> Option<&str> {
        self.funding_rate.as_deref()
    }

    #[getter]
    #[must_use]
    pub fn next_funding_time(&self) -> Option<&str> {
        self.next_funding_time.as_deref()
    }

    #[getter]
    #[must_use]
    pub fn mark_price(&self) -> Option<&str> {
        self.mark_price.as_deref()
    }

    #[getter]
    #[must_use]
    pub fn index_price(&self) -> Option<&str> {
        self.index_price.as_deref()
    }
}

impl From<BybitTickerSpot> for BybitTickerData {
    fn from(ticker: BybitTickerSpot) -> Self {
        Self {
            symbol: ticker.symbol,
            bid1_price: ticker.bid1_price,
            bid1_size: ticker.bid1_size,
            ask1_price: ticker.ask1_price,
            ask1_size: ticker.ask1_size,
            last_price: ticker.last_price,
            high_price24h: ticker.high_price24h,
            low_price24h: ticker.low_price24h,
            turnover24h: ticker.turnover24h,
            volume24h: ticker.volume24h,
            open_interest: None,
            funding_rate: None,
            next_funding_time: None,
            mark_price: None,
            index_price: None,
        }
    }
}

impl From<BybitTickerLinear> for BybitTickerData {
    fn from(ticker: BybitTickerLinear) -> Self {
        Self {
            symbol: ticker.symbol,
            bid1_price: ticker.bid1_price,
            bid1_size: ticker.bid1_size,
            ask1_price: ticker.ask1_price,
            ask1_size: ticker.ask1_size,
            last_price: ticker.last_price,
            high_price24h: ticker.high_price24h,
            low_price24h: ticker.low_price24h,
            turnover24h: ticker.turnover24h,
            volume24h: ticker.volume24h,
            open_interest: Some(ticker.open_interest),
            funding_rate: Some(ticker.funding_rate),
            next_funding_time: Some(ticker.next_funding_time),
            mark_price: Some(ticker.mark_price),
            index_price: Some(ticker.index_price),
        }
    }
}

impl From<BybitTickerOption> for BybitTickerData {
    fn from(ticker: BybitTickerOption) -> Self {
        Self {
            symbol: ticker.symbol,
            bid1_price: ticker.bid1_price,
            bid1_size: ticker.bid1_size,
            ask1_price: ticker.ask1_price,
            ask1_size: ticker.ask1_size,
            last_price: ticker.last_price,
            high_price24h: ticker.high_price24h,
            low_price24h: ticker.low_price24h,
            turnover24h: ticker.turnover24h,
            volume24h: ticker.volume24h,
            open_interest: Some(ticker.open_interest),
            funding_rate: None,
            next_funding_time: None,
            mark_price: Some(ticker.mark_price),
            index_price: Some(ticker.index_price),
        }
    }
}

/// Kline/candlestick entry returned by `GET /v5/market/kline`.
///
/// Bybit returns klines as arrays with 7 elements:
/// [startTime, openPrice, highPrice, lowPrice, closePrice, volume, turnover]
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/kline>
#[derive(Clone, Debug, Serialize)]
pub struct BybitKline {
    pub start: String,
    pub open: String,
    pub high: String,
    pub low: String,
    pub close: String,
    pub volume: String,
    pub turnover: String,
}

impl<'de> Deserialize<'de> for BybitKline {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let [start, open, high, low, close, volume, turnover]: [String; 7] =
            Deserialize::deserialize(deserializer)?;
        Ok(Self {
            start,
            open,
            high,
            low,
            close,
            volume,
            turnover,
        })
    }
}

/// Kline list result returned by Bybit.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/kline>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitKlineResult {
    pub category: BybitProductType,
    pub symbol: Ustr,
    pub list: Vec<BybitKline>,
}

/// Response alias for kline history requests.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/kline>
pub type BybitKlinesResponse = BybitResponse<BybitKlineResult>;

/// Trade entry returned by `GET /v5/market/recent-trade`.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/recent-trade>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitTrade {
    pub exec_id: String,
    pub symbol: Ustr,
    pub price: String,
    pub size: String,
    pub side: BybitOrderSide,
    pub time: String,
    pub is_block_trade: bool,
    #[serde(default)]
    pub m_p: Option<String>,
    #[serde(default)]
    pub i_p: Option<String>,
    #[serde(default)]
    pub mlv: Option<String>,
    #[serde(default)]
    pub iv: Option<String>,
}

/// Trade list result returned by Bybit.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/recent-trade>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitTradeResult {
    pub category: BybitProductType,
    pub list: Vec<BybitTrade>,
}

/// Response alias for recent trades requests.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/recent-trade>
pub type BybitTradesResponse = BybitResponse<BybitTradeResult>;

/// Funding entry returned by `GET /v5/market/funding/history`.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/history-fund-rate>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitFunding {
    pub symbol: Ustr,
    pub funding_rate: String,
    pub funding_rate_timestamp: String,
}

/// Funding list result returned by Bybit.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/history-fund-rate>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitFundingResult {
    pub category: BybitProductType,
    pub list: Vec<BybitFunding>,
}

/// Response alias for historical funding requests.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/history-fund-rate>
pub type BybitFundingResponse = BybitResponse<BybitFundingResult>;

/// Orderbook result returned by Bybit.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/orderbook>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitOrderbookResult {
    /// Symbol.
    pub s: Ustr,
    /// Bid levels represented as `[price, size]` string pairs.
    pub b: Vec<[String; 2]>,
    /// Ask levels represented as `[price, size]` string pairs.
    pub a: Vec<[String; 2]>,
    pub ts: i64,
    /// Update identifier.
    pub u: i64,
    /// Cross sequence number.
    pub seq: i64,
    pub cts: i64,
}

/// Response alias for orderbook requests.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/orderbook>
pub type BybitOrderbookResponse = BybitResponse<BybitOrderbookResult>;

/// Instrument definition for spot symbols.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitInstrumentSpot {
    pub symbol: Ustr,
    pub base_coin: Ustr,
    pub quote_coin: Ustr,
    pub innovation: BybitInnovationFlag,
    pub status: BybitInstrumentStatus,
    pub margin_trading: BybitMarginTrading,
    pub lot_size_filter: SpotLotSizeFilter,
    pub price_filter: SpotPriceFilter,
}

/// Instrument definition for linear contracts.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitInstrumentLinear {
    pub symbol: Ustr,
    pub contract_type: BybitContractType,
    pub status: BybitInstrumentStatus,
    pub base_coin: Ustr,
    pub quote_coin: Ustr,
    pub launch_time: String,
    pub delivery_time: String,
    pub delivery_fee_rate: String,
    pub price_scale: String,
    pub leverage_filter: LeverageFilter,
    pub price_filter: LinearPriceFilter,
    pub lot_size_filter: LinearLotSizeFilter,
    pub unified_margin_trade: bool,
    pub funding_interval: i64,
    pub settle_coin: Ustr,
}

/// Instrument definition for inverse contracts.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitInstrumentInverse {
    pub symbol: Ustr,
    pub contract_type: BybitContractType,
    pub status: BybitInstrumentStatus,
    pub base_coin: Ustr,
    pub quote_coin: Ustr,
    pub launch_time: String,
    pub delivery_time: String,
    pub delivery_fee_rate: String,
    pub price_scale: String,
    pub leverage_filter: LeverageFilter,
    pub price_filter: LinearPriceFilter,
    pub lot_size_filter: LinearLotSizeFilter,
    pub unified_margin_trade: bool,
    pub funding_interval: i64,
    pub settle_coin: Ustr,
}

/// Instrument definition for option contracts.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitInstrumentOption {
    pub symbol: Ustr,
    pub status: BybitInstrumentStatus,
    pub base_coin: Ustr,
    pub quote_coin: Ustr,
    pub settle_coin: Ustr,
    pub options_type: BybitOptionType,
    pub launch_time: String,
    pub delivery_time: String,
    pub delivery_fee_rate: String,
    pub price_filter: LinearPriceFilter,
    pub lot_size_filter: OptionLotSizeFilter,
}

/// Response alias for instrument info requests that return spot instruments.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
pub type BybitInstrumentSpotResponse = BybitCursorListResponse<BybitInstrumentSpot>;
/// Response alias for instrument info requests that return linear contracts.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
pub type BybitInstrumentLinearResponse = BybitCursorListResponse<BybitInstrumentLinear>;
/// Response alias for instrument info requests that return inverse contracts.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
pub type BybitInstrumentInverseResponse = BybitCursorListResponse<BybitInstrumentInverse>;
/// Response alias for instrument info requests that return option contracts.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/market/instrument>
pub type BybitInstrumentOptionResponse = BybitCursorListResponse<BybitInstrumentOption>;

/// Fee rate structure returned by `GET /v5/account/fee-rate`.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/account/fee-rate>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.bybit", from_py_object)
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.bybit")
)]
pub struct BybitFeeRate {
    pub symbol: Ustr,
    pub taker_fee_rate: String,
    pub maker_fee_rate: String,
    #[serde(default)]
    pub base_coin: Option<Ustr>,
}

#[cfg(feature = "python")]
#[pyo3::pymethods]
impl BybitFeeRate {
    #[getter]
    #[must_use]
    pub fn symbol(&self) -> &str {
        self.symbol.as_str()
    }

    #[getter]
    #[must_use]
    pub fn taker_fee_rate(&self) -> &str {
        &self.taker_fee_rate
    }

    #[getter]
    #[must_use]
    pub fn maker_fee_rate(&self) -> &str {
        &self.maker_fee_rate
    }

    #[getter]
    #[must_use]
    pub fn base_coin(&self) -> Option<&str> {
        self.base_coin.as_ref().map(|u| u.as_str())
    }
}

/// Response alias for fee rate requests.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/account/fee-rate>
pub type BybitFeeRateResponse = BybitListResponse<BybitFeeRate>;

/// Account balance snapshot coin entry.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/account/wallet-balance>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitCoinBalance {
    pub available_to_borrow: String,
    pub bonus: String,
    pub accrued_interest: String,
    pub available_to_withdraw: String,
    #[serde(default, rename = "totalOrderIM")]
    pub total_order_im: Option<String>,
    pub equity: String,
    pub usd_value: String,
    pub borrow_amount: String,
    #[serde(default, rename = "totalPositionMM")]
    pub total_position_mm: Option<String>,
    #[serde(default, rename = "totalPositionIM")]
    pub total_position_im: Option<String>,
    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
    pub wallet_balance: Decimal,
    pub unrealised_pnl: String,
    pub cum_realised_pnl: String,
    #[serde(deserialize_with = "deserialize_decimal_or_zero")]
    pub locked: Decimal,
    pub collateral_switch: bool,
    pub margin_collateral: bool,
    pub coin: Ustr,
    #[serde(default)]
    pub spot_hedging_qty: Option<String>,
    #[serde(default, deserialize_with = "deserialize_optional_decimal_or_zero")]
    pub spot_borrow: Decimal,
}

/// Wallet balance snapshot containing per-coin balances.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/account/wallet-balance>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitWalletBalance {
    pub total_equity: String,
    #[serde(rename = "accountIMRate")]
    pub account_im_rate: String,
    pub total_margin_balance: String,
    pub total_initial_margin: String,
    pub account_type: BybitAccountType,
    pub total_available_balance: String,
    #[serde(rename = "accountMMRate")]
    pub account_mm_rate: String,
    #[serde(rename = "totalPerpUPL")]
    pub total_perp_upl: String,
    pub total_wallet_balance: String,
    #[serde(rename = "accountLTV")]
    pub account_ltv: String,
    pub total_maintenance_margin: String,
    pub coin: Vec<BybitCoinBalance>,
}

/// Response alias for wallet balance requests.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/account/wallet-balance>
pub type BybitWalletBalanceResponse = BybitListResponse<BybitWalletBalance>;

/// Order representation as returned by order-related endpoints.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/order/order-list>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.bybit", from_py_object)
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.bybit")
)]
#[serde(rename_all = "camelCase")]
pub struct BybitOrder {
    pub order_id: Ustr,
    pub order_link_id: Ustr,
    pub block_trade_id: Option<Ustr>,
    pub symbol: Ustr,
    pub price: String,
    pub qty: String,
    pub side: BybitOrderSide,
    pub is_leverage: String,
    pub position_idx: i32,
    pub order_status: BybitOrderStatus,
    pub cancel_type: BybitCancelType,
    pub reject_reason: Ustr,
    pub avg_price: Option<String>,
    pub leaves_qty: String,
    pub leaves_value: String,
    pub cum_exec_qty: String,
    pub cum_exec_value: String,
    pub cum_exec_fee: String,
    pub time_in_force: BybitTimeInForce,
    pub order_type: BybitOrderType,
    pub stop_order_type: BybitStopOrderType,
    pub order_iv: Option<String>,
    pub trigger_price: String,
    pub take_profit: String,
    pub stop_loss: String,
    pub tp_trigger_by: BybitTriggerType,
    pub sl_trigger_by: BybitTriggerType,
    pub trigger_direction: BybitTriggerDirection,
    pub trigger_by: BybitTriggerType,
    pub last_price_on_created: String,
    pub reduce_only: bool,
    pub close_on_trigger: bool,
    pub smp_type: BybitSmpType,
    pub smp_group: i32,
    pub smp_order_id: Ustr,
    pub tpsl_mode: Option<BybitTpSlMode>,
    pub tp_limit_price: String,
    pub sl_limit_price: String,
    pub place_type: Ustr,
    pub created_time: String,
    pub updated_time: String,
}

#[cfg(feature = "python")]
#[pyo3::pymethods]
impl BybitOrder {
    #[getter]
    #[must_use]
    pub fn order_id(&self) -> &str {
        self.order_id.as_str()
    }

    #[getter]
    #[must_use]
    pub fn order_link_id(&self) -> &str {
        self.order_link_id.as_str()
    }

    #[getter]
    #[must_use]
    pub fn block_trade_id(&self) -> Option<&str> {
        self.block_trade_id.as_ref().map(|s| s.as_str())
    }

    #[getter]
    #[must_use]
    pub fn symbol(&self) -> &str {
        self.symbol.as_str()
    }

    #[getter]
    #[must_use]
    pub fn price(&self) -> &str {
        &self.price
    }

    #[getter]
    #[must_use]
    pub fn qty(&self) -> &str {
        &self.qty
    }

    #[getter]
    #[must_use]
    pub fn side(&self) -> BybitOrderSide {
        self.side
    }

    #[getter]
    #[must_use]
    pub fn is_leverage(&self) -> &str {
        &self.is_leverage
    }

    #[getter]
    #[must_use]
    pub fn position_idx(&self) -> i32 {
        self.position_idx
    }

    #[getter]
    #[must_use]
    pub fn order_status(&self) -> BybitOrderStatus {
        self.order_status
    }

    #[getter]
    #[must_use]
    pub fn cancel_type(&self) -> BybitCancelType {
        self.cancel_type
    }

    #[getter]
    #[must_use]
    pub fn reject_reason(&self) -> &str {
        self.reject_reason.as_str()
    }

    #[getter]
    #[must_use]
    pub fn avg_price(&self) -> Option<&str> {
        self.avg_price.as_deref()
    }

    #[getter]
    #[must_use]
    pub fn leaves_qty(&self) -> &str {
        &self.leaves_qty
    }

    #[getter]
    #[must_use]
    pub fn leaves_value(&self) -> &str {
        &self.leaves_value
    }

    #[getter]
    #[must_use]
    pub fn cum_exec_qty(&self) -> &str {
        &self.cum_exec_qty
    }

    #[getter]
    #[must_use]
    pub fn cum_exec_value(&self) -> &str {
        &self.cum_exec_value
    }

    #[getter]
    #[must_use]
    pub fn cum_exec_fee(&self) -> &str {
        &self.cum_exec_fee
    }

    #[getter]
    #[must_use]
    pub fn time_in_force(&self) -> BybitTimeInForce {
        self.time_in_force
    }

    #[getter]
    #[must_use]
    pub fn order_type(&self) -> BybitOrderType {
        self.order_type
    }

    #[getter]
    #[must_use]
    pub fn stop_order_type(&self) -> BybitStopOrderType {
        self.stop_order_type
    }

    #[getter]
    #[must_use]
    pub fn order_iv(&self) -> Option<&str> {
        self.order_iv.as_deref()
    }

    #[getter]
    #[must_use]
    pub fn trigger_price(&self) -> &str {
        &self.trigger_price
    }

    #[getter]
    #[must_use]
    pub fn take_profit(&self) -> &str {
        &self.take_profit
    }

    #[getter]
    #[must_use]
    pub fn stop_loss(&self) -> &str {
        &self.stop_loss
    }

    #[getter]
    #[must_use]
    pub fn tp_trigger_by(&self) -> BybitTriggerType {
        self.tp_trigger_by
    }

    #[getter]
    #[must_use]
    pub fn sl_trigger_by(&self) -> BybitTriggerType {
        self.sl_trigger_by
    }

    #[getter]
    #[must_use]
    pub fn trigger_direction(&self) -> BybitTriggerDirection {
        self.trigger_direction
    }

    #[getter]
    #[must_use]
    pub fn trigger_by(&self) -> BybitTriggerType {
        self.trigger_by
    }

    #[getter]
    #[must_use]
    pub fn last_price_on_created(&self) -> &str {
        &self.last_price_on_created
    }

    #[getter]
    #[must_use]
    pub fn reduce_only(&self) -> bool {
        self.reduce_only
    }

    #[getter]
    #[must_use]
    pub fn close_on_trigger(&self) -> bool {
        self.close_on_trigger
    }

    #[getter]
    #[must_use]
    #[allow(
        clippy::missing_panics_doc,
        reason = "serialization of a simple enum cannot fail"
    )]
    pub fn smp_type(&self) -> String {
        serde_json::to_string(&self.smp_type)
            .expect("Failed to serialize BybitSmpType")
            .trim_matches('"')
            .to_string()
    }

    #[getter]
    #[must_use]
    pub fn smp_group(&self) -> i32 {
        self.smp_group
    }

    #[getter]
    #[must_use]
    pub fn smp_order_id(&self) -> &str {
        self.smp_order_id.as_str()
    }

    #[getter]
    #[must_use]
    pub fn tpsl_mode(&self) -> Option<BybitTpSlMode> {
        self.tpsl_mode
    }

    #[getter]
    #[must_use]
    pub fn tp_limit_price(&self) -> &str {
        &self.tp_limit_price
    }

    #[getter]
    #[must_use]
    pub fn sl_limit_price(&self) -> &str {
        &self.sl_limit_price
    }

    #[getter]
    #[must_use]
    pub fn place_type(&self) -> &str {
        self.place_type.as_str()
    }

    #[getter]
    #[must_use]
    pub fn created_time(&self) -> &str {
        &self.created_time
    }

    #[getter]
    #[must_use]
    pub fn updated_time(&self) -> &str {
        &self.updated_time
    }
}

/// Response alias for open order queries.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/order/order-list>
pub type BybitOpenOrdersResponse = BybitCursorListResponse<BybitOrder>;
/// Response alias for order history queries with pagination.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/order/order-list>
pub type BybitOrderHistoryResponse = BybitCursorListResponse<BybitOrder>;

/// Payload returned after placing a single order.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/order/create-order>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitPlaceOrderResult {
    pub order_id: Option<Ustr>,
    pub order_link_id: Option<Ustr>,
}

/// Response alias for order placement endpoints.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/order/create-order>
pub type BybitPlaceOrderResponse = BybitResponse<BybitPlaceOrderResult>;

/// Payload returned after cancelling a single order.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/order/cancel-order>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitCancelOrderResult {
    pub order_id: Option<Ustr>,
    pub order_link_id: Option<Ustr>,
}

/// Response alias for order cancellation endpoints.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/order/cancel-order>
pub type BybitCancelOrderResponse = BybitResponse<BybitCancelOrderResult>;

/// Execution/Fill payload returned by `GET /v5/execution/list`.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/order/execution>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitExecution {
    pub symbol: Ustr,
    pub order_id: Ustr,
    pub order_link_id: Ustr,
    pub side: BybitOrderSide,
    pub order_price: String,
    pub order_qty: String,
    pub leaves_qty: String,
    pub create_type: Option<BybitCreateType>,
    pub order_type: BybitOrderType,
    pub stop_order_type: Option<BybitStopOrderType>,
    pub exec_fee: String,
    pub exec_id: String,
    pub exec_price: String,
    pub exec_qty: String,
    pub exec_type: BybitExecType,
    pub exec_value: String,
    pub exec_time: String,
    pub fee_currency: Ustr,
    pub is_maker: bool,
    pub fee_rate: String,
    pub trade_iv: String,
    pub mark_iv: String,
    pub mark_price: String,
    pub index_price: String,
    pub underlying_price: String,
    pub block_trade_id: String,
    pub closed_size: String,
    pub seq: i64,
}

/// Response alias for trade history requests.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/order/execution>
pub type BybitTradeHistoryResponse = BybitCursorListResponse<BybitExecution>;

/// Represents a position returned by the Bybit API.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/position>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitPosition {
    pub position_idx: BybitPositionIdx,
    pub risk_id: i32,
    pub risk_limit_value: String,
    pub symbol: Ustr,
    pub side: BybitPositionSide,
    pub size: String,
    pub avg_price: String,
    pub position_value: String,
    pub trade_mode: i32,
    pub position_status: BybitPositionStatus,
    pub auto_add_margin: i32,
    pub adl_rank_indicator: i32,
    pub leverage: String,
    pub position_balance: String,
    pub mark_price: String,
    pub liq_price: String,
    pub bust_price: String,
    #[serde(rename = "positionMM")]
    pub position_mm: String,
    #[serde(rename = "positionIM")]
    pub position_im: String,
    pub tpsl_mode: BybitTpSlMode,
    pub take_profit: String,
    pub stop_loss: String,
    pub trailing_stop: String,
    pub unrealised_pnl: String,
    pub cur_realised_pnl: String,
    pub cum_realised_pnl: String,
    pub seq: i64,
    pub is_reduce_only: bool,
    pub mmr_sys_updated_time: String,
    pub leverage_sys_updated_time: String,
    pub created_time: String,
    pub updated_time: String,
}

/// Response alias for position list requests.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/position>
pub type BybitPositionListResponse = BybitCursorListResponse<BybitPosition>;

/// Reason detail for set margin mode failures.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/account/set-margin-mode>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitSetMarginModeReason {
    pub reason_code: String,
    pub reason_msg: String,
}

/// Result payload for set margin mode operation.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/account/set-margin-mode>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitSetMarginModeResult {
    #[serde(default)]
    pub reasons: Vec<BybitSetMarginModeReason>,
}

/// Response alias for set margin mode requests.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/account/set-margin-mode>
pub type BybitSetMarginModeResponse = BybitResponse<BybitSetMarginModeResult>;

/// Empty result for set leverage operation.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BybitSetLeverageResult {}

/// Response alias for set leverage requests.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/position/leverage>
pub type BybitSetLeverageResponse = BybitResponse<BybitSetLeverageResult>;

/// Empty result for switch mode operation.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BybitSwitchModeResult {}

/// Response alias for switch mode requests.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/position/position-mode>
pub type BybitSwitchModeResponse = BybitResponse<BybitSwitchModeResult>;

/// Empty result for set trading stop operation.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BybitSetTradingStopResult {}

/// Response alias for set trading stop requests.
///
/// # References
/// - <https://bybit-exchange.github.io/docs/v5/position/trading-stop>
pub type BybitSetTradingStopResponse = BybitResponse<BybitSetTradingStopResult>;

/// Result from manual borrow operation.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitBorrowResult {
    pub coin: Ustr,
    pub amount: String,
}

/// Response alias for manual borrow requests.
///
/// # References
///
/// - <https://bybit-exchange.github.io/docs/v5/account/borrow>
pub type BybitBorrowResponse = BybitResponse<BybitBorrowResult>;

/// Result from no-convert repay operation.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BybitNoConvertRepayResult {
    pub result_status: String,
}

/// Response alias for no-convert repay requests.
///
/// # References
///
/// - <https://bybit-exchange.github.io/docs/v5/account/no-convert-repay>
pub type BybitNoConvertRepayResponse = BybitResponse<BybitNoConvertRepayResult>;

/// API key permissions.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.bybit", from_py_object)
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.bybit")
)]
#[serde(rename_all = "PascalCase")]
pub struct BybitApiKeyPermissions {
    #[serde(default)]
    pub contract_trade: Vec<String>,
    #[serde(default)]
    pub spot: Vec<String>,
    #[serde(default)]
    pub wallet: Vec<String>,
    #[serde(default)]
    pub options: Vec<String>,
    #[serde(default)]
    pub derivatives: Vec<String>,
    #[serde(default)]
    pub exchange: Vec<String>,
    #[serde(default)]
    pub copy_trading: Vec<String>,
    #[serde(default)]
    pub block_trade: Vec<String>,
    #[serde(default)]
    pub nft: Vec<String>,
    #[serde(default)]
    pub affiliate: Vec<String>,
}

/// Account details from API key info.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.bybit", from_py_object)
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.bybit")
)]
#[serde(rename_all = "camelCase")]
pub struct BybitAccountDetails {
    pub id: String,
    pub note: String,
    pub api_key: String,
    pub read_only: u8,
    pub secret: String,
    #[serde(rename = "type")]
    pub key_type: u8,
    pub permissions: BybitApiKeyPermissions,
    pub ips: Vec<String>,
    #[serde(default)]
    pub user_id: Option<u64>,
    #[serde(default)]
    pub inviter_id: Option<u64>,
    pub vip_level: String,
    #[serde(deserialize_with = "deserialize_string_to_u8", default)]
    pub mkt_maker_level: u8,
    #[serde(default)]
    pub affiliate_id: Option<u64>,
    pub rsa_public_key: String,
    pub is_master: bool,
    pub parent_uid: String,
    pub uta: u8,
    pub kyc_level: String,
    pub kyc_region: String,
    #[serde(default)]
    pub deadline_day: i64,
    #[serde(default)]
    pub expired_at: Option<String>,
    pub created_at: String,
}

#[cfg(feature = "python")]
#[pyo3::pymethods]
impl BybitAccountDetails {
    #[getter]
    #[must_use]
    pub fn id(&self) -> &str {
        &self.id
    }

    #[getter]
    #[must_use]
    pub fn note(&self) -> &str {
        &self.note
    }

    #[getter]
    #[must_use]
    pub fn api_key(&self) -> &str {
        &self.api_key
    }

    #[getter]
    #[must_use]
    pub fn read_only(&self) -> u8 {
        self.read_only
    }

    #[getter]
    #[must_use]
    pub fn key_type(&self) -> u8 {
        self.key_type
    }

    #[getter]
    #[must_use]
    pub fn user_id(&self) -> Option<u64> {
        self.user_id
    }

    #[getter]
    #[must_use]
    pub fn inviter_id(&self) -> Option<u64> {
        self.inviter_id
    }

    #[getter]
    #[must_use]
    pub fn vip_level(&self) -> &str {
        &self.vip_level
    }

    #[getter]
    #[must_use]
    pub fn mkt_maker_level(&self) -> u8 {
        self.mkt_maker_level
    }

    #[getter]
    #[must_use]
    pub fn affiliate_id(&self) -> Option<u64> {
        self.affiliate_id
    }

    #[getter]
    #[must_use]
    pub fn rsa_public_key(&self) -> &str {
        &self.rsa_public_key
    }

    #[getter]
    #[must_use]
    pub fn is_master(&self) -> bool {
        self.is_master
    }

    #[getter]
    #[must_use]
    pub fn parent_uid(&self) -> &str {
        &self.parent_uid
    }

    #[getter]
    #[must_use]
    pub fn uta(&self) -> u8 {
        self.uta
    }

    #[getter]
    #[must_use]
    pub fn kyc_level(&self) -> &str {
        &self.kyc_level
    }

    #[getter]
    #[must_use]
    pub fn kyc_region(&self) -> &str {
        &self.kyc_region
    }

    #[getter]
    #[must_use]
    pub fn deadline_day(&self) -> i64 {
        self.deadline_day
    }

    #[getter]
    #[must_use]
    pub fn expired_at(&self) -> Option<&str> {
        self.expired_at.as_deref()
    }

    #[getter]
    #[must_use]
    pub fn created_at(&self) -> &str {
        &self.created_at
    }
}

/// Response alias for API key info requests.
///
/// # References
///
/// - <https://bybit-exchange.github.io/docs/v5/user/apikey-info>
pub type BybitAccountDetailsResponse = BybitResponse<BybitAccountDetails>;

#[cfg(test)]
mod tests {
    use nautilus_core::UnixNanos;
    use nautilus_model::identifiers::AccountId;
    use rstest::rstest;
    use rust_decimal::Decimal;
    use rust_decimal_macros::dec;

    use super::*;
    use crate::common::testing::load_test_json;

    #[rstest]
    fn deserialize_spot_instrument_uses_enums() {
        let json = load_test_json("http_get_instruments_spot.json");
        let response: BybitInstrumentSpotResponse = serde_json::from_str(&json).unwrap();
        let instrument = &response.result.list[0];

        assert_eq!(instrument.status, BybitInstrumentStatus::Trading);
        assert_eq!(instrument.innovation, BybitInnovationFlag::Standard);
        assert_eq!(instrument.margin_trading, BybitMarginTrading::UtaOnly);
    }

    #[rstest]
    fn deserialize_linear_instrument_status() {
        let json = load_test_json("http_get_instruments_linear.json");
        let response: BybitInstrumentLinearResponse = serde_json::from_str(&json).unwrap();
        let instrument = &response.result.list[0];

        assert_eq!(instrument.status, BybitInstrumentStatus::Trading);
        assert_eq!(instrument.contract_type, BybitContractType::LinearPerpetual);
    }

    #[rstest]
    fn deserialize_order_response_maps_enums() {
        let json = load_test_json("http_get_orders_history.json");
        let response: BybitOrderHistoryResponse = serde_json::from_str(&json).unwrap();
        let order = &response.result.list[0];

        assert_eq!(order.cancel_type, BybitCancelType::CancelByUser);
        assert_eq!(order.tp_trigger_by, BybitTriggerType::MarkPrice);
        assert_eq!(order.sl_trigger_by, BybitTriggerType::LastPrice);
        assert_eq!(order.tpsl_mode, Some(BybitTpSlMode::Full));
        assert_eq!(order.order_type, BybitOrderType::Limit);
        assert_eq!(order.smp_type, BybitSmpType::None);
    }

    #[rstest]
    fn deserialize_wallet_balance_without_optional_fields() {
        let json = r#"{
            "retCode": 0,
            "retMsg": "OK",
            "result": {
                "list": [{
                    "totalEquity": "1000.00",
                    "accountIMRate": "0",
                    "totalMarginBalance": "1000.00",
                    "totalInitialMargin": "0",
                    "accountType": "UNIFIED",
                    "totalAvailableBalance": "1000.00",
                    "accountMMRate": "0",
                    "totalPerpUPL": "0",
                    "totalWalletBalance": "1000.00",
                    "accountLTV": "0",
                    "totalMaintenanceMargin": "0",
                    "coin": [{
                        "availableToBorrow": "0",
                        "bonus": "0",
                        "accruedInterest": "0",
                        "availableToWithdraw": "1000.00",
                        "equity": "1000.00",
                        "usdValue": "1000.00",
                        "borrowAmount": "0",
                        "totalPositionIM": "0",
                        "walletBalance": "1000.00",
                        "unrealisedPnl": "0",
                        "cumRealisedPnl": "0",
                        "locked": "0",
                        "collateralSwitch": true,
                        "marginCollateral": true,
                        "coin": "USDT"
                    }]
                }]
            }
        }"#;

        let response: BybitWalletBalanceResponse = serde_json::from_str(json)
            .expect("Failed to parse wallet balance without optional fields");

        assert_eq!(response.ret_code, 0);
        assert_eq!(response.result.list[0].coin[0].total_order_im, None);
        assert_eq!(response.result.list[0].coin[0].total_position_mm, None);
    }

    #[rstest]
    fn deserialize_wallet_balance_from_docs() {
        let json = include_str!("../../test_data/http_get_wallet_balance.json");

        let response: BybitWalletBalanceResponse = serde_json::from_str(json)
            .expect("Failed to parse wallet balance from Bybit docs example");

        assert_eq!(response.ret_code, 0);
        assert_eq!(response.ret_msg, "OK");

        let wallet = &response.result.list[0];
        assert_eq!(wallet.total_equity, "3.31216591");
        assert_eq!(wallet.account_im_rate, "0");
        assert_eq!(wallet.account_mm_rate, "0");
        assert_eq!(wallet.total_perp_upl, "0");
        assert_eq!(wallet.account_ltv, "0");

        // Check BTC coin
        let btc = &wallet.coin[0];
        assert_eq!(btc.coin.as_str(), "BTC");
        assert_eq!(btc.available_to_borrow, "3");
        assert_eq!(btc.total_order_im, Some("0".to_string()));
        assert_eq!(btc.total_position_mm, Some("0".to_string()));
        assert_eq!(btc.total_position_im, Some("0".to_string()));

        // Check USDT coin (without optional IM/MM fields)
        let usdt = &wallet.coin[1];
        assert_eq!(usdt.coin.as_str(), "USDT");
        assert_eq!(usdt.wallet_balance, dec!(1000.50));
        assert_eq!(usdt.total_order_im, None);
        assert_eq!(usdt.total_position_mm, None);
        assert_eq!(usdt.total_position_im, None);
        assert_eq!(btc.spot_borrow, Decimal::ZERO);
        assert_eq!(usdt.spot_borrow, Decimal::ZERO);
    }

    #[rstest]
    fn test_parse_wallet_balance_with_spot_borrow() {
        let json = include_str!("../../test_data/http_get_wallet_balance_with_spot_borrow.json");
        let response: BybitWalletBalanceResponse =
            serde_json::from_str(json).expect("Failed to parse wallet balance with spotBorrow");

        let wallet = &response.result.list[0];
        let usdt = &wallet.coin[0];

        assert_eq!(usdt.coin.as_str(), "USDT");
        assert_eq!(usdt.wallet_balance, dec!(1200.00));
        assert_eq!(usdt.spot_borrow, dec!(200.00));
        assert_eq!(usdt.borrow_amount, "200.00");

        // Verify calculation: actual_balance = walletBalance - spotBorrow = 1200 - 200 = 1000
        let account_id = crate::common::parse::parse_account_state(
            wallet,
            AccountId::new("BYBIT-001"),
            UnixNanos::default(),
        )
        .expect("Failed to parse account state");

        let balance = &account_id.balances[0];
        assert_eq!(balance.total.as_f64(), 1000.0);
    }

    #[rstest]
    fn test_parse_wallet_balance_spot_short() {
        let json = include_str!("../../test_data/http_get_wallet_balance_spot_short.json");
        let response: BybitWalletBalanceResponse = serde_json::from_str(json)
            .expect("Failed to parse wallet balance with SHORT SPOT position");

        let wallet = &response.result.list[0];
        let eth = &wallet.coin[0];

        assert_eq!(eth.coin.as_str(), "ETH");
        assert_eq!(eth.wallet_balance, dec!(0));
        assert_eq!(eth.spot_borrow, dec!(0.06142));
        assert_eq!(eth.borrow_amount, "0.06142");

        let account_state = crate::common::parse::parse_account_state(
            wallet,
            AccountId::new("BYBIT-001"),
            UnixNanos::default(),
        )
        .expect("Failed to parse account state");

        let eth_balance = account_state
            .balances
            .iter()
            .find(|b| b.currency.code.as_str() == "ETH")
            .expect("ETH balance not found");

        // Negative balance represents SHORT position (borrowed ETH)
        assert_eq!(eth_balance.total.as_f64(), -0.06142);
    }

    #[rstest]
    fn deserialize_borrow_response() {
        let json = r#"{
            "retCode": 0,
            "retMsg": "success",
            "result": {
                "coin": "BTC",
                "amount": "0.01"
            },
            "retExtInfo": {},
            "time": 1756197991955
        }"#;

        let response: BybitBorrowResponse = serde_json::from_str(json).unwrap();

        assert_eq!(response.ret_code, 0);
        assert_eq!(response.ret_msg, "success");
        assert_eq!(response.result.coin, "BTC");
        assert_eq!(response.result.amount, "0.01");
    }

    #[rstest]
    fn deserialize_no_convert_repay_response() {
        let json = r#"{
            "retCode": 0,
            "retMsg": "OK",
            "result": {
                "resultStatus": "SU"
            },
            "retExtInfo": {},
            "time": 1234567890
        }"#;

        let response: BybitNoConvertRepayResponse = serde_json::from_str(json).unwrap();

        assert_eq!(response.ret_code, 0);
        assert_eq!(response.ret_msg, "OK");
        assert_eq!(response.result.result_status, "SU");
    }
}