nautilus-binance 0.55.0

Binance 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
// -------------------------------------------------------------------------------------------------
//  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.
// -------------------------------------------------------------------------------------------------

//! Binance Futures HTTP response models.

use anyhow::Context;
use nautilus_core::{UUID4, UnixNanos};
use nautilus_model::{
    enums::{AccountType, LiquiditySide, OrderSide, OrderStatus, OrderType, TimeInForce},
    events::AccountState,
    identifiers::{AccountId, ClientOrderId, InstrumentId, Symbol, TradeId, Venue, VenueOrderId},
    reports::{FillReport, OrderStatusReport},
    types::{AccountBalance, Currency, MarginBalance, Money, Price, Quantity},
};
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use ustr::Ustr;

use crate::common::{
    consts::BINANCE_NAUTILUS_FUTURES_BROKER_ID,
    encoder::decode_broker_id,
    enums::{
        BinanceAlgoStatus, BinanceAlgoType, BinanceContractStatus, BinanceFuturesOrderType,
        BinanceIncomeType, BinanceMarginType, BinanceOrderStatus, BinancePositionSide,
        BinancePriceMatch, BinanceSelfTradePreventionMode, BinanceSide, BinanceTimeInForce,
        BinanceTradingStatus, BinanceWorkingType,
    },
    models::BinanceRateLimit,
};

/// Server time response from `GET /fapi/v1/time`.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceServerTime {
    /// Server timestamp in milliseconds.
    pub server_time: i64,
}

/// Public trade from `GET /fapi/v1/trades`.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceFuturesTrade {
    /// Trade ID.
    pub id: i64,
    /// Trade price.
    pub price: String,
    /// Trade quantity.
    pub qty: String,
    /// Quote asset quantity.
    pub quote_qty: String,
    /// Trade timestamp in milliseconds.
    pub time: i64,
    /// Whether the buyer is the maker.
    pub is_buyer_maker: bool,
}

/// Kline/candlestick data from `GET /fapi/v1/klines`.
#[derive(Clone, Debug)]
pub struct BinanceFuturesKline {
    /// Open time in milliseconds.
    pub open_time: i64,
    /// Open price.
    pub open: String,
    /// High price.
    pub high: String,
    /// Low price.
    pub low: String,
    /// Close price.
    pub close: String,
    /// Volume.
    pub volume: String,
    /// Close time in milliseconds.
    pub close_time: i64,
    /// Quote asset volume.
    pub quote_volume: String,
    /// Number of trades.
    pub num_trades: i64,
    /// Taker buy base volume.
    pub taker_buy_base_volume: String,
    /// Taker buy quote volume.
    pub taker_buy_quote_volume: String,
}

impl<'de> Deserialize<'de> for BinanceFuturesKline {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let arr: Vec<Value> = Vec::deserialize(deserializer)?;
        if arr.len() < 11 {
            return Err(serde::de::Error::custom("Invalid kline array length"));
        }

        Ok(Self {
            open_time: arr[0].as_i64().unwrap_or(0),
            open: arr[1].as_str().unwrap_or("0").to_string(),
            high: arr[2].as_str().unwrap_or("0").to_string(),
            low: arr[3].as_str().unwrap_or("0").to_string(),
            close: arr[4].as_str().unwrap_or("0").to_string(),
            volume: arr[5].as_str().unwrap_or("0").to_string(),
            close_time: arr[6].as_i64().unwrap_or(0),
            quote_volume: arr[7].as_str().unwrap_or("0").to_string(),
            num_trades: arr[8].as_i64().unwrap_or(0),
            taker_buy_base_volume: arr[9].as_str().unwrap_or("0").to_string(),
            taker_buy_quote_volume: arr[10].as_str().unwrap_or("0").to_string(),
        })
    }
}

/// USD-M Futures exchange information response from `GET /fapi/v1/exchangeInfo`.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceFuturesUsdExchangeInfo {
    /// Server timezone.
    pub timezone: String,
    /// Server timestamp in milliseconds.
    pub server_time: i64,
    /// Rate limit definitions.
    pub rate_limits: Vec<BinanceRateLimit>,
    /// Exchange-level filters.
    #[serde(default)]
    pub exchange_filters: Vec<Value>,
    /// Asset definitions.
    #[serde(default)]
    pub assets: Vec<BinanceFuturesAsset>,
    /// Trading symbols.
    pub symbols: Vec<BinanceFuturesUsdSymbol>,
}

/// Futures asset definition.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceFuturesAsset {
    /// Asset name.
    pub asset: Ustr,
    /// Whether margin is available.
    pub margin_available: bool,
    /// Auto asset exchange threshold.
    #[serde(default)]
    pub auto_asset_exchange: Option<String>,
}

/// USD-M Futures symbol definition.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceFuturesUsdSymbol {
    /// Symbol name (e.g., "BTCUSDT").
    pub symbol: Ustr,
    /// Trading pair (e.g., "BTCUSDT").
    pub pair: Ustr,
    /// Contract type (PERPETUAL, CURRENT_QUARTER, NEXT_QUARTER).
    pub contract_type: String,
    /// Delivery date timestamp.
    pub delivery_date: i64,
    /// Onboard date timestamp.
    pub onboard_date: i64,
    /// Trading status.
    pub status: BinanceTradingStatus,
    /// Maintenance margin percent.
    pub maint_margin_percent: String,
    /// Required margin percent.
    pub required_margin_percent: String,
    /// Base asset.
    pub base_asset: Ustr,
    /// Quote asset.
    pub quote_asset: Ustr,
    /// Margin asset.
    pub margin_asset: Ustr,
    /// Price precision.
    pub price_precision: i32,
    /// Quantity precision.
    pub quantity_precision: i32,
    /// Base asset precision.
    pub base_asset_precision: i32,
    /// Quote precision.
    pub quote_precision: i32,
    /// Underlying type.
    #[serde(default)]
    pub underlying_type: Option<String>,
    /// Underlying sub type.
    #[serde(default)]
    pub underlying_sub_type: Vec<String>,
    /// Settle plan.
    #[serde(default)]
    pub settle_plan: Option<i64>,
    /// Trigger protect threshold.
    #[serde(default)]
    pub trigger_protect: Option<String>,
    /// Liquidation fee.
    #[serde(default)]
    pub liquidation_fee: Option<String>,
    /// Market take bound.
    #[serde(default)]
    pub market_take_bound: Option<String>,
    /// Allowed order types.
    pub order_types: Vec<String>,
    /// Time in force options.
    pub time_in_force: Vec<String>,
    /// Symbol filters.
    pub filters: Vec<Value>,
}

/// COIN-M Futures exchange information response from `GET /dapi/v1/exchangeInfo`.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceFuturesCoinExchangeInfo {
    /// Server timezone.
    pub timezone: String,
    /// Server timestamp in milliseconds.
    pub server_time: i64,
    /// Rate limit definitions.
    pub rate_limits: Vec<BinanceRateLimit>,
    /// Exchange-level filters.
    #[serde(default)]
    pub exchange_filters: Vec<Value>,
    /// Trading symbols.
    pub symbols: Vec<BinanceFuturesCoinSymbol>,
}

/// COIN-M Futures symbol definition.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceFuturesCoinSymbol {
    /// Symbol name (e.g., "BTCUSD_PERP").
    pub symbol: Ustr,
    /// Trading pair (e.g., "BTCUSD").
    pub pair: Ustr,
    /// Contract type (PERPETUAL, CURRENT_QUARTER, NEXT_QUARTER).
    pub contract_type: String,
    /// Delivery date timestamp.
    pub delivery_date: i64,
    /// Onboard date timestamp.
    pub onboard_date: i64,
    /// Trading status.
    #[serde(default)]
    pub contract_status: Option<BinanceContractStatus>,
    /// Contract size.
    pub contract_size: i64,
    /// Maintenance margin percent.
    pub maint_margin_percent: String,
    /// Required margin percent.
    pub required_margin_percent: String,
    /// Base asset.
    pub base_asset: Ustr,
    /// Quote asset.
    pub quote_asset: Ustr,
    /// Margin asset.
    pub margin_asset: Ustr,
    /// Price precision.
    pub price_precision: i32,
    /// Quantity precision.
    pub quantity_precision: i32,
    /// Base asset precision.
    pub base_asset_precision: i32,
    /// Quote precision.
    pub quote_precision: i32,
    /// Equal quantity precision.
    #[serde(default, rename = "equalQtyPrecision")]
    pub equal_qty_precision: Option<i32>,
    /// Trigger protect threshold.
    #[serde(default)]
    pub trigger_protect: Option<String>,
    /// Liquidation fee.
    #[serde(default)]
    pub liquidation_fee: Option<String>,
    /// Market take bound.
    #[serde(default)]
    pub market_take_bound: Option<String>,
    /// Allowed order types.
    pub order_types: Vec<String>,
    /// Time in force options.
    pub time_in_force: Vec<String>,
    /// Symbol filters.
    pub filters: Vec<Value>,
}

/// 24hr ticker price change statistics for futures.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceFuturesTicker24hr {
    /// Symbol name.
    pub symbol: Ustr,
    /// Price change in quote asset.
    pub price_change: String,
    /// Price change percentage.
    pub price_change_percent: String,
    /// Weighted average price.
    pub weighted_avg_price: String,
    /// Last traded price.
    pub last_price: String,
    /// Last traded quantity.
    #[serde(default)]
    pub last_qty: Option<String>,
    /// Opening price.
    pub open_price: String,
    /// Highest price.
    pub high_price: String,
    /// Lowest price.
    pub low_price: String,
    /// Total traded base asset volume.
    pub volume: String,
    /// Total traded quote asset volume.
    pub quote_volume: String,
    /// Statistics open time.
    pub open_time: i64,
    /// Statistics close time.
    pub close_time: i64,
    /// First trade ID.
    #[serde(default)]
    pub first_id: Option<i64>,
    /// Last trade ID.
    #[serde(default)]
    pub last_id: Option<i64>,
    /// Total number of trades.
    #[serde(default)]
    pub count: Option<i64>,
}

/// Mark price and funding rate for futures.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceFuturesMarkPrice {
    /// Symbol name.
    pub symbol: Ustr,
    /// Mark price.
    pub mark_price: String,
    /// Index price.
    #[serde(default)]
    pub index_price: Option<String>,
    /// Estimated settle price (only for delivery contracts).
    #[serde(default)]
    pub estimated_settle_price: Option<String>,
    /// Last funding rate.
    #[serde(default)]
    pub last_funding_rate: Option<String>,
    /// Next funding time.
    #[serde(default)]
    pub next_funding_time: Option<i64>,
    /// Interest rate.
    #[serde(default)]
    pub interest_rate: Option<String>,
    /// Timestamp.
    pub time: i64,
}

/// Order book depth snapshot.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceOrderBook {
    /// Last update ID.
    pub last_update_id: i64,
    /// Bid levels as `[price, quantity]` arrays.
    pub bids: Vec<(String, String)>,
    /// Ask levels as `[price, quantity]` arrays.
    pub asks: Vec<(String, String)>,
    /// Message output time.
    #[serde(default, rename = "E")]
    pub event_time: Option<i64>,
    /// Transaction time.
    #[serde(default, rename = "T")]
    pub transaction_time: Option<i64>,
}

/// Best bid/ask from book ticker endpoint.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceBookTicker {
    /// Symbol name.
    pub symbol: Ustr,
    /// Best bid price.
    pub bid_price: String,
    /// Best bid quantity.
    pub bid_qty: String,
    /// Best ask price.
    pub ask_price: String,
    /// Best ask quantity.
    pub ask_qty: String,
    /// Event time.
    #[serde(default)]
    pub time: Option<i64>,
}

/// Price ticker.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinancePriceTicker {
    /// Symbol name.
    pub symbol: Ustr,
    /// Current price.
    pub price: String,
    /// Event time.
    #[serde(default)]
    pub time: Option<i64>,
}

/// Funding rate history record.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceFundingRate {
    /// Symbol name.
    pub symbol: Ustr,
    /// Funding rate value.
    pub funding_rate: String,
    /// Funding time in milliseconds.
    pub funding_time: i64,
    /// Mark price at the funding time.
    #[serde(default)]
    pub mark_price: Option<String>,
    /// Index price at the funding time.
    #[serde(default)]
    pub index_price: Option<String>,
}

/// Open interest record.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceOpenInterest {
    /// Symbol name.
    pub symbol: Ustr,
    /// Total open interest.
    pub open_interest: String,
    /// Timestamp in milliseconds.
    pub time: i64,
}

/// Futures account balance entry.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceFuturesBalance {
    /// Account alias (only USD-M).
    #[serde(default)]
    pub account_alias: Option<String>,
    /// Asset code (e.g., "USDT").
    pub asset: Ustr,
    /// Wallet balance (v2 uses walletBalance, v1 uses balance).
    #[serde(alias = "balance")]
    pub wallet_balance: String,
    /// Unrealized profit.
    #[serde(default)]
    pub unrealized_profit: Option<String>,
    /// Margin balance.
    #[serde(default)]
    pub margin_balance: Option<String>,
    /// Maintenance margin required.
    #[serde(default)]
    pub maint_margin: Option<String>,
    /// Initial margin required.
    #[serde(default)]
    pub initial_margin: Option<String>,
    /// Position initial margin.
    #[serde(default)]
    pub position_initial_margin: Option<String>,
    /// Open order initial margin.
    #[serde(default)]
    pub open_order_initial_margin: Option<String>,
    /// Cross wallet balance.
    #[serde(default)]
    pub cross_wallet_balance: Option<String>,
    /// Unrealized PnL for cross positions.
    #[serde(default)]
    pub cross_un_pnl: Option<String>,
    /// Available balance.
    pub available_balance: String,
    /// Maximum withdrawable amount.
    #[serde(default)]
    pub max_withdraw_amount: Option<String>,
    /// Whether margin trading is available.
    #[serde(default)]
    pub margin_available: Option<bool>,
    /// Timestamp of last update in milliseconds.
    pub update_time: i64,
    /// Withdrawable amount (COIN-M specific).
    #[serde(default)]
    pub withdraw_available: Option<String>,
}

/// Account position from `GET /fapi/v2/account` positions array.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceAccountPosition {
    /// Symbol name.
    pub symbol: Ustr,
    /// Initial margin.
    #[serde(default)]
    pub initial_margin: Option<String>,
    /// Maintenance margin.
    #[serde(default)]
    pub maint_margin: Option<String>,
    /// Unrealized profit.
    #[serde(default)]
    pub unrealized_profit: Option<String>,
    /// Position initial margin.
    #[serde(default)]
    pub position_initial_margin: Option<String>,
    /// Open order initial margin.
    #[serde(default)]
    pub open_order_initial_margin: Option<String>,
    /// Leverage.
    #[serde(default)]
    pub leverage: Option<String>,
    /// Isolated margin mode.
    #[serde(default)]
    pub isolated: Option<bool>,
    /// Entry price.
    #[serde(default)]
    pub entry_price: Option<String>,
    /// Max notional value.
    #[serde(default)]
    pub max_notional: Option<String>,
    /// Bid notional.
    #[serde(default)]
    pub bid_notional: Option<String>,
    /// Ask notional.
    #[serde(default)]
    pub ask_notional: Option<String>,
    /// Position side (BOTH, LONG, SHORT).
    #[serde(default)]
    pub position_side: Option<BinancePositionSide>,
    /// Position amount.
    #[serde(default)]
    pub position_amt: Option<String>,
    /// Update time.
    #[serde(default)]
    pub update_time: Option<i64>,
}

/// Position risk from `GET /fapi/v2/positionRisk`.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinancePositionRisk {
    /// Symbol name.
    pub symbol: Ustr,
    /// Position quantity.
    pub position_amt: String,
    /// Entry price.
    pub entry_price: String,
    /// Mark price.
    pub mark_price: String,
    /// Unrealized profit and loss.
    #[serde(default)]
    pub un_realized_profit: Option<String>,
    /// Liquidation price.
    #[serde(default)]
    pub liquidation_price: Option<String>,
    /// Applied leverage.
    pub leverage: String,
    /// Max notional value.
    #[serde(default)]
    pub max_notional_value: Option<String>,
    /// Margin type (CROSSED or ISOLATED).
    #[serde(default)]
    pub margin_type: Option<BinanceMarginType>,
    /// Isolated margin amount.
    #[serde(default)]
    pub isolated_margin: Option<String>,
    /// Auto add margin flag (as string from API).
    #[serde(default)]
    pub is_auto_add_margin: Option<String>,
    /// Position side (BOTH, LONG, SHORT).
    #[serde(default)]
    pub position_side: Option<BinancePositionSide>,
    /// Notional position value.
    #[serde(default)]
    pub notional: Option<String>,
    /// Isolated wallet balance.
    #[serde(default)]
    pub isolated_wallet: Option<String>,
    /// ADL quantile indicator.
    #[serde(default)]
    pub adl_quantile: Option<u8>,
    /// Last update time.
    #[serde(default)]
    pub update_time: Option<i64>,
    /// Break-even price.
    #[serde(default)]
    pub break_even_price: Option<String>,
    /// Bankruptcy price.
    #[serde(default)]
    pub bust_price: Option<String>,
}

/// Income history record.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceIncomeRecord {
    /// Symbol name (may be empty for transfers).
    #[serde(default)]
    pub symbol: Option<Ustr>,
    /// Income type (e.g., FUNDING_FEE, COMMISSION).
    pub income_type: BinanceIncomeType,
    /// Income amount.
    pub income: String,
    /// Asset code.
    pub asset: Ustr,
    /// Event time in milliseconds.
    pub time: i64,
    /// Additional info field.
    #[serde(default)]
    pub info: Option<String>,
    /// Transaction ID.
    #[serde(default)]
    pub tran_id: Option<i64>,
    /// Related trade ID.
    #[serde(default)]
    pub trade_id: Option<i64>,
}

/// User trade record.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceUserTrade {
    /// Symbol name.
    pub symbol: Ustr,
    /// Trade ID.
    pub id: i64,
    /// Order ID.
    pub order_id: i64,
    /// Trade price.
    pub price: String,
    /// Executed quantity.
    pub qty: String,
    /// Quote quantity.
    #[serde(default)]
    pub quote_qty: Option<String>,
    /// Realized PnL for the trade.
    pub realized_pnl: String,
    /// Buy/sell side.
    pub side: BinanceSide,
    /// Position side (BOTH, LONG, SHORT).
    #[serde(default)]
    pub position_side: Option<BinancePositionSide>,
    /// Trade time in milliseconds.
    pub time: i64,
    /// Was the buyer the maker?
    pub buyer: bool,
    /// Was the trade maker liquidity?
    pub maker: bool,
    /// Commission paid.
    #[serde(default)]
    pub commission: Option<String>,
    /// Commission asset.
    #[serde(default)]
    pub commission_asset: Option<Ustr>,
    /// Margin asset (if provided).
    #[serde(default)]
    pub margin_asset: Option<Ustr>,
}

/// Futures account information from `GET /fapi/v2/account` or `GET /dapi/v1/account`.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceFuturesAccountInfo {
    /// Total initial margin required.
    #[serde(default)]
    pub total_initial_margin: Option<String>,
    /// Total maintenance margin required.
    #[serde(default)]
    pub total_maint_margin: Option<String>,
    /// Total wallet balance.
    #[serde(default)]
    pub total_wallet_balance: Option<String>,
    /// Total unrealized profit.
    #[serde(default)]
    pub total_unrealized_profit: Option<String>,
    /// Total margin balance.
    #[serde(default)]
    pub total_margin_balance: Option<String>,
    /// Total position initial margin.
    #[serde(default)]
    pub total_position_initial_margin: Option<String>,
    /// Total open order initial margin.
    #[serde(default)]
    pub total_open_order_initial_margin: Option<String>,
    /// Total cross wallet balance.
    #[serde(default)]
    pub total_cross_wallet_balance: Option<String>,
    /// Total cross unrealized PnL.
    #[serde(default)]
    pub total_cross_un_pnl: Option<String>,
    /// Available balance.
    #[serde(default)]
    pub available_balance: Option<String>,
    /// Max withdraw amount.
    #[serde(default)]
    pub max_withdraw_amount: Option<String>,
    /// Can deposit.
    #[serde(default)]
    pub can_deposit: Option<bool>,
    /// Can trade.
    #[serde(default)]
    pub can_trade: Option<bool>,
    /// Can withdraw.
    #[serde(default)]
    pub can_withdraw: Option<bool>,
    /// Multi-assets margin mode.
    #[serde(default)]
    pub multi_assets_margin: Option<bool>,
    /// Update time.
    #[serde(default)]
    pub update_time: Option<i64>,
    /// Account balances.
    #[serde(default)]
    pub assets: Vec<BinanceFuturesBalance>,
    /// Account positions.
    #[serde(default)]
    pub positions: Vec<BinanceAccountPosition>,
}

impl BinanceFuturesAccountInfo {
    /// Converts this Binance account info to a Nautilus [`AccountState`].
    ///
    /// # Errors
    ///
    /// Returns an error if balance parsing fails.
    pub fn to_account_state(
        &self,
        account_id: AccountId,
        ts_init: UnixNanos,
    ) -> anyhow::Result<AccountState> {
        let mut balances = Vec::with_capacity(self.assets.len());

        for asset in &self.assets {
            let currency = Currency::get_or_create_crypto_with_context(
                asset.asset.as_str(),
                Some("futures balance"),
            );

            let total: Decimal = if asset.wallet_balance.is_empty() {
                Decimal::ZERO
            } else {
                asset.wallet_balance.parse().context("invalid balance")?
            };
            let available: Decimal = if asset.available_balance.is_empty() {
                Decimal::ZERO
            } else {
                asset
                    .available_balance
                    .parse()
                    .context("invalid available_balance")?
            };
            let locked = total - available;

            let total_money = Money::from_decimal(total, currency)
                .unwrap_or_else(|_| Money::new(total.to_string().parse().unwrap_or(0.0), currency));
            let locked_money = Money::from_decimal(locked, currency).unwrap_or_else(|_| {
                Money::new(locked.to_string().parse().unwrap_or(0.0), currency)
            });
            let free_money = Money::from_decimal(available, currency).unwrap_or_else(|_| {
                Money::new(available.to_string().parse().unwrap_or(0.0), currency)
            });

            let balance = AccountBalance::new(total_money, locked_money, free_money);
            balances.push(balance);
        }

        // Ensure at least one balance exists
        if balances.is_empty() {
            let zero_currency = Currency::USDT();
            let zero_money = Money::new(0.0, zero_currency);
            let zero_balance = AccountBalance::new(zero_money, zero_money, zero_money);
            balances.push(zero_balance);
        }

        // Parse margin requirements
        let mut margins = Vec::new();

        let initial_margin_dec = self
            .total_initial_margin
            .as_ref()
            .and_then(|s| Decimal::from_str_exact(s).ok());
        let maint_margin_dec = self
            .total_maint_margin
            .as_ref()
            .and_then(|s| Decimal::from_str_exact(s).ok());

        if let (Some(initial_margin_dec), Some(maint_margin_dec)) =
            (initial_margin_dec, maint_margin_dec)
        {
            let has_margin = !initial_margin_dec.is_zero() || !maint_margin_dec.is_zero();
            if has_margin {
                let margin_currency = Currency::USDT();
                let margin_instrument_id =
                    InstrumentId::new(Symbol::new("ACCOUNT"), Venue::new("BINANCE"));

                let initial_margin = Money::from_decimal(initial_margin_dec, margin_currency)
                    .unwrap_or_else(|_| Money::zero(margin_currency));
                let maintenance_margin = Money::from_decimal(maint_margin_dec, margin_currency)
                    .unwrap_or_else(|_| Money::zero(margin_currency));

                let margin_balance =
                    MarginBalance::new(initial_margin, maintenance_margin, margin_instrument_id);
                margins.push(margin_balance);
            }
        }

        let ts_event = self
            .update_time
            .map_or(ts_init, |t| UnixNanos::from_millis(t as u64));

        Ok(AccountState::new(
            account_id,
            AccountType::Margin,
            balances,
            margins,
            true, // is_reported
            UUID4::new(),
            ts_event,
            ts_init,
            None,
        ))
    }
}

/// Hedge mode (dual side position) response.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceHedgeModeResponse {
    /// Whether dual side position mode is enabled.
    pub dual_side_position: bool,
}

/// Leverage change response.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceLeverageResponse {
    /// Symbol.
    pub symbol: Ustr,
    /// New leverage value.
    pub leverage: u32,
    /// Max notional value at this leverage.
    #[serde(default)]
    pub max_notional_value: Option<String>,
}

/// Cancel all orders response.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceCancelAllOrdersResponse {
    /// Response code (200 = success).
    pub code: i32,
    /// Response message.
    pub msg: String,
}

/// Futures order information.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceFuturesOrder {
    /// Symbol name.
    pub symbol: Ustr,
    /// Order ID.
    pub order_id: i64,
    /// Client order ID.
    pub client_order_id: String,
    /// Original order quantity.
    pub orig_qty: String,
    /// Executed quantity.
    pub executed_qty: String,
    /// Cumulative quote asset transacted.
    pub cum_quote: String,
    /// Original limit price.
    pub price: String,
    /// Average execution price.
    #[serde(default)]
    pub avg_price: Option<String>,
    /// Stop price.
    #[serde(default)]
    pub stop_price: Option<String>,
    /// Order status.
    pub status: BinanceOrderStatus,
    /// Time in force.
    pub time_in_force: BinanceTimeInForce,
    /// Order type.
    #[serde(rename = "type")]
    pub order_type: BinanceFuturesOrderType,
    /// Original order type.
    #[serde(default)]
    pub orig_type: Option<BinanceFuturesOrderType>,
    /// Order side (BUY/SELL).
    pub side: BinanceSide,
    /// Position side (BOTH/LONG/SHORT).
    #[serde(default)]
    pub position_side: Option<BinancePositionSide>,
    /// Reduce-only flag.
    #[serde(default)]
    pub reduce_only: Option<bool>,
    /// Close position flag (for stop orders).
    #[serde(default)]
    pub close_position: Option<bool>,
    /// Trailing delta activation price.
    #[serde(default)]
    pub activate_price: Option<String>,
    /// Trailing callback rate.
    #[serde(default)]
    pub price_rate: Option<String>,
    /// Working type (CONTRACT_PRICE or MARK_PRICE).
    #[serde(default)]
    pub working_type: Option<BinanceWorkingType>,
    /// Whether price protection is enabled.
    #[serde(default)]
    pub price_protect: Option<bool>,
    /// Whether order uses isolated margin.
    #[serde(default)]
    pub is_isolated: Option<bool>,
    /// Good till date (for GTD orders).
    #[serde(default)]
    pub good_till_date: Option<i64>,
    /// Price match mode.
    #[serde(default)]
    pub price_match: Option<BinancePriceMatch>,
    /// Self-trade prevention mode.
    #[serde(default)]
    pub self_trade_prevention_mode: Option<BinanceSelfTradePreventionMode>,
    /// Last update time.
    #[serde(default)]
    pub update_time: Option<i64>,
    /// Working order ID for tracking.
    #[serde(default)]
    pub working_type_id: Option<i64>,
}

impl BinanceFuturesOrder {
    /// Converts this Binance order to a Nautilus [`OrderStatusReport`].
    ///
    /// # Errors
    ///
    /// Returns an error if quantity parsing fails.
    pub fn to_order_status_report(
        &self,
        account_id: AccountId,
        instrument_id: InstrumentId,
        size_precision: u8,
        treat_expired_as_canceled: bool,
        ts_init: UnixNanos,
    ) -> anyhow::Result<OrderStatusReport> {
        let ts_event = self
            .update_time
            .map_or(ts_init, |t| UnixNanos::from_millis(t as u64));

        let client_order_id = ClientOrderId::new(decode_broker_id(
            &self.client_order_id,
            BINANCE_NAUTILUS_FUTURES_BROKER_ID,
        ));
        let venue_order_id = VenueOrderId::new(self.order_id.to_string());

        let order_side = match self.side {
            BinanceSide::Buy => OrderSide::Buy,
            BinanceSide::Sell => OrderSide::Sell,
        };

        let order_type = self.order_type.to_nautilus_order_type();
        let time_in_force = self.time_in_force.to_nautilus_time_in_force();
        let order_status = self
            .status
            .to_nautilus_order_status(treat_expired_as_canceled);

        let quantity: Decimal = self.orig_qty.parse().context("invalid orig_qty")?;
        let filled_qty: Decimal = self.executed_qty.parse().context("invalid executed_qty")?;

        Ok(OrderStatusReport::new(
            account_id,
            instrument_id,
            Some(client_order_id),
            venue_order_id,
            order_side,
            order_type,
            time_in_force,
            order_status,
            Quantity::new(quantity.to_string().parse()?, size_precision),
            Quantity::new(filled_qty.to_string().parse()?, size_precision),
            ts_event,
            ts_event,
            ts_init,
            Some(UUID4::new()),
        ))
    }
}

impl BinanceFuturesOrderType {
    /// Returns whether this order type is post-only.
    #[must_use]
    pub fn is_post_only(&self) -> bool {
        false // Binance Futures doesn't have a dedicated post-only type
    }

    /// Converts to Nautilus order type.
    #[must_use]
    pub fn to_nautilus_order_type(&self) -> OrderType {
        match self {
            Self::Market => OrderType::Market,
            Self::Limit => OrderType::Limit,
            Self::Stop => OrderType::StopLimit,
            Self::StopMarket => OrderType::StopMarket,
            Self::TakeProfit => OrderType::LimitIfTouched,
            Self::TakeProfitMarket => OrderType::MarketIfTouched,
            Self::TrailingStopMarket => OrderType::TrailingStopMarket,
            Self::Liquidation | Self::Adl => OrderType::Market, // Forced closes
            Self::Unknown => OrderType::Market,
        }
    }
}

impl BinanceTimeInForce {
    /// Converts to Nautilus time in force.
    #[must_use]
    pub fn to_nautilus_time_in_force(&self) -> TimeInForce {
        match self {
            Self::Gtc => TimeInForce::Gtc,
            Self::Ioc => TimeInForce::Ioc,
            Self::Fok => TimeInForce::Fok,
            Self::Gtx => TimeInForce::Gtc, // GTX is GTC with post-only
            Self::Gtd => TimeInForce::Gtd,
            Self::Rpi => TimeInForce::Ioc, // RPI behaves as immediate
            Self::Unknown => TimeInForce::Gtc, // default
        }
    }
}

impl BinanceOrderStatus {
    /// Converts to Nautilus order status.
    #[must_use]
    pub fn to_nautilus_order_status(&self, treat_expired_as_canceled: bool) -> OrderStatus {
        match self {
            Self::New | Self::PendingNew => OrderStatus::Accepted,
            Self::PartiallyFilled => OrderStatus::PartiallyFilled,
            Self::Filled | Self::NewAdl | Self::NewInsurance => OrderStatus::Filled,
            Self::Canceled => OrderStatus::Canceled,
            Self::PendingCancel => OrderStatus::PendingCancel,
            Self::Rejected => OrderStatus::Rejected,
            Self::Expired | Self::ExpiredInMatch => {
                if treat_expired_as_canceled {
                    OrderStatus::Canceled
                } else {
                    OrderStatus::Expired
                }
            }
            Self::Unknown => OrderStatus::Initialized,
        }
    }
}

impl BinanceUserTrade {
    /// Converts this Binance trade to a Nautilus [`FillReport`].
    ///
    /// # Errors
    ///
    /// Returns an error if quantity or price parsing fails.
    pub fn to_fill_report(
        &self,
        account_id: AccountId,
        instrument_id: InstrumentId,
        price_precision: u8,
        size_precision: u8,
        ts_init: UnixNanos,
    ) -> anyhow::Result<FillReport> {
        let ts_event = UnixNanos::from_millis(self.time as u64);

        let venue_order_id = VenueOrderId::new(self.order_id.to_string());
        let trade_id = TradeId::new(self.id.to_string());

        let order_side = match self.side {
            BinanceSide::Buy => OrderSide::Buy,
            BinanceSide::Sell => OrderSide::Sell,
        };

        let liquidity_side = if self.maker {
            LiquiditySide::Maker
        } else {
            LiquiditySide::Taker
        };

        let last_qty: Decimal = self.qty.parse().context("invalid qty")?;
        let last_px: Decimal = self.price.parse().context("invalid price")?;

        let commission = {
            let comm_val: f64 = self
                .commission
                .as_ref()
                .and_then(|c| c.parse().ok())
                .unwrap_or(0.0);
            let comm_asset = self
                .commission_asset
                .as_ref()
                .map_or_else(Currency::USDT, Currency::from);
            Money::new(comm_val, comm_asset)
        };

        Ok(FillReport::new(
            account_id,
            instrument_id,
            venue_order_id,
            trade_id,
            order_side,
            Quantity::new(last_qty.to_string().parse()?, size_precision),
            Price::new(last_px.to_string().parse()?, price_precision),
            commission,
            liquidity_side,
            None, // client_order_id
            None, // venue_position_id
            ts_event,
            ts_init,
            Some(UUID4::new()),
        ))
    }
}

/// Result of a single order in a batch operation.
///
/// Each item in a batch response can be either a success or an error.
#[derive(Clone, Debug, Deserialize)]
#[serde(untagged)]
pub enum BatchOrderResult {
    /// Successful order operation.
    Success(Box<BinanceFuturesOrder>),
    /// Failed order operation.
    Error(BatchOrderError),
}

/// Error in a batch order response.
#[derive(Clone, Debug, Deserialize)]
pub struct BatchOrderError {
    /// Error code from Binance.
    pub code: i64,
    /// Error message.
    pub msg: String,
}

/// Listen key response from user data stream endpoints.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListenKeyResponse {
    /// The listen key for WebSocket user data stream.
    pub listen_key: String,
}

/// Algo order response from Binance Futures Algo Service API.
///
/// Algo orders are conditional orders (STOP_MARKET, STOP_LIMIT, TAKE_PROFIT,
/// TAKE_PROFIT_MARKET, TRAILING_STOP_MARKET) that are managed by Binance's
/// Algo Service rather than the traditional order matching engine.
///
/// # References
///
/// - <https://developers.binance.com/docs/derivatives/usds-margined-futures/trade/rest-api/New-Algo-Order>
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceFuturesAlgoOrder {
    /// Unique algo order ID assigned by Binance.
    pub algo_id: i64,
    /// Client-specified algo order ID for idempotency.
    pub client_algo_id: String,
    /// Algo type (currently only `Conditional` is supported).
    pub algo_type: BinanceAlgoType,
    /// Order type (STOP_MARKET, STOP, TAKE_PROFIT, TAKE_PROFIT_MARKET, TRAILING_STOP_MARKET).
    #[serde(rename = "orderType", alias = "type")]
    pub order_type: BinanceFuturesOrderType,
    /// Trading symbol.
    pub symbol: Ustr,
    /// Order side (BUY/SELL).
    pub side: BinanceSide,
    /// Position side (BOTH, LONG, SHORT).
    #[serde(default)]
    pub position_side: Option<BinancePositionSide>,
    /// Time in force.
    #[serde(default)]
    pub time_in_force: Option<BinanceTimeInForce>,
    /// Order quantity.
    #[serde(default)]
    pub quantity: Option<String>,
    /// Algo order status.
    #[serde(default)]
    pub algo_status: Option<BinanceAlgoStatus>,
    /// Trigger price for the conditional order.
    #[serde(default)]
    pub trigger_price: Option<String>,
    /// Limit price (for STOP/TAKE_PROFIT limit orders).
    #[serde(default)]
    pub price: Option<String>,
    /// Working type for trigger price calculation (CONTRACT_PRICE or MARK_PRICE).
    #[serde(default)]
    pub working_type: Option<BinanceWorkingType>,
    /// Close all position flag.
    #[serde(default)]
    pub close_position: Option<bool>,
    /// Price protection enabled.
    #[serde(default)]
    pub price_protect: Option<bool>,
    /// Reduce-only flag.
    #[serde(default)]
    pub reduce_only: Option<bool>,
    /// Activation price for TRAILING_STOP_MARKET orders.
    #[serde(default)]
    pub activate_price: Option<String>,
    /// Callback rate for TRAILING_STOP_MARKET orders (0.1 to 10, where 1 = 1%).
    #[serde(default)]
    pub callback_rate: Option<String>,
    /// Order creation time in milliseconds.
    #[serde(default)]
    pub create_time: Option<i64>,
    /// Last update time in milliseconds.
    #[serde(default)]
    pub update_time: Option<i64>,
    /// Trigger time in milliseconds (when the algo order triggered).
    #[serde(default)]
    pub trigger_time: Option<i64>,
    /// Order ID in matching engine (populated when algo order is triggered).
    #[serde(default)]
    pub actual_order_id: Option<String>,
    /// Executed quantity in matching engine (populated when algo order is triggered).
    #[serde(default)]
    pub executed_qty: Option<String>,
    /// Average fill price in matching engine (populated when algo order is triggered).
    #[serde(default)]
    pub avg_price: Option<String>,
}

impl BinanceFuturesAlgoOrder {
    /// Converts this Binance algo order to a Nautilus [`OrderStatusReport`].
    ///
    /// # Errors
    ///
    /// Returns an error if quantity parsing fails.
    pub fn to_order_status_report(
        &self,
        account_id: AccountId,
        instrument_id: InstrumentId,
        size_precision: u8,
        ts_init: UnixNanos,
    ) -> anyhow::Result<OrderStatusReport> {
        let ts_event = self
            .update_time
            .or(self.create_time)
            .map_or(ts_init, |t| UnixNanos::from_millis(t as u64));

        let client_order_id = ClientOrderId::new(decode_broker_id(
            &self.client_algo_id,
            BINANCE_NAUTILUS_FUTURES_BROKER_ID,
        ));
        let venue_order_id = self.actual_order_id.as_ref().map_or_else(
            || VenueOrderId::new(self.algo_id.to_string()),
            |id| VenueOrderId::new(id.clone()),
        );

        let order_side = match self.side {
            BinanceSide::Buy => OrderSide::Buy,
            BinanceSide::Sell => OrderSide::Sell,
        };

        let order_type = self.parse_order_type();
        let time_in_force = self
            .time_in_force
            .as_ref()
            .map_or(TimeInForce::Gtc, |tif| tif.to_nautilus_time_in_force());
        let order_status = self.parse_order_status();

        let quantity: Decimal = self
            .quantity
            .as_ref()
            .map_or(Ok(Decimal::ZERO), |q| q.parse())
            .context("invalid quantity")?;
        let filled_qty: Decimal = self
            .executed_qty
            .as_ref()
            .map_or(Ok(Decimal::ZERO), |q| q.parse())
            .context("invalid executed_qty")?;

        Ok(OrderStatusReport::new(
            account_id,
            instrument_id,
            Some(client_order_id),
            venue_order_id,
            order_side,
            order_type,
            time_in_force,
            order_status,
            Quantity::new(quantity.to_string().parse()?, size_precision),
            Quantity::new(filled_qty.to_string().parse()?, size_precision),
            ts_event,
            ts_event,
            ts_init,
            Some(UUID4::new()),
        ))
    }

    fn parse_order_type(&self) -> OrderType {
        self.order_type.into()
    }

    fn parse_order_status(&self) -> OrderStatus {
        match self.algo_status {
            Some(BinanceAlgoStatus::New) => OrderStatus::Accepted,
            Some(BinanceAlgoStatus::Triggering) => OrderStatus::Accepted,
            Some(BinanceAlgoStatus::Triggered) => OrderStatus::Accepted,
            Some(BinanceAlgoStatus::Finished) => {
                // Check executed_qty to determine if filled or canceled
                if let Some(qty) = &self.executed_qty
                    && let Ok(dec) = qty.parse::<Decimal>()
                    && !dec.is_zero()
                {
                    return OrderStatus::Filled;
                }
                OrderStatus::Canceled
            }
            Some(BinanceAlgoStatus::Canceled) => OrderStatus::Canceled,
            Some(BinanceAlgoStatus::Expired) => OrderStatus::Expired,
            Some(BinanceAlgoStatus::Rejected) => OrderStatus::Rejected,
            Some(BinanceAlgoStatus::Unknown) | None => OrderStatus::Initialized,
        }
    }
}

/// Cancel response for algo orders from Binance Futures Algo Service API.
#[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BinanceFuturesAlgoOrderCancelResponse {
    /// Algo order ID that was canceled.
    pub algo_id: i64,
    /// Client algo order ID.
    pub client_algo_id: String,
    /// Response code (200 for success).
    pub code: String,
    /// Response message.
    pub msg: String,
}

#[cfg(test)]
mod tests {
    use rstest::rstest;

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

    #[rstest]
    fn test_parse_account_info_v2() {
        let json = load_fixture_string("futures/http_json/account_info_v2.json");
        let account: BinanceFuturesAccountInfo =
            serde_json::from_str(&json).expect("Failed to parse account info");

        assert_eq!(
            account.total_wallet_balance,
            Some("23.72469206".to_string())
        );
        assert_eq!(account.assets.len(), 1);
        assert_eq!(account.assets[0].asset.as_str(), "USDT");
        assert_eq!(account.assets[0].wallet_balance, "23.72469206");
        assert_eq!(account.positions.len(), 1);
        assert_eq!(account.positions[0].symbol.as_str(), "BTCUSDT");
        assert_eq!(account.positions[0].leverage, Some("100".to_string()));
    }

    #[rstest]
    fn test_account_info_to_account_state_zero_margins() {
        let json = load_fixture_string("futures/http_json/account_info_v2.json");
        let account: BinanceFuturesAccountInfo =
            serde_json::from_str(&json).expect("Failed to parse account info");

        let account_id = AccountId::from("BINANCE-001");
        let ts_init = UnixNanos::from(1_000_000_000u64);
        let state = account.to_account_state(account_id, ts_init).unwrap();

        assert_eq!(state.account_id, account_id);
        assert_eq!(state.account_type, AccountType::Margin);
        assert!(!state.balances.is_empty());
        assert_eq!(state.margins.len(), 0);
    }

    #[rstest]
    fn test_account_info_to_account_state_with_margins() {
        let json = r#"{
            "totalInitialMargin": "500.25000000",
            "totalMaintMargin": "250.75000000",
            "totalWalletBalance": "10000.00000000",
            "assets": [{
                "asset": "USDT",
                "walletBalance": "10000.00000000",
                "availableBalance": "9500.00000000",
                "updateTime": 1617939110373
            }],
            "positions": []
        }"#;
        let account: BinanceFuturesAccountInfo =
            serde_json::from_str(json).expect("Failed to parse account info");

        let account_id = AccountId::from("BINANCE-001");
        let ts_init = UnixNanos::from(1_000_000_000u64);
        let state = account.to_account_state(account_id, ts_init).unwrap();

        assert_eq!(state.margins.len(), 1);
        let margin = &state.margins[0];
        assert_eq!(margin.instrument_id.symbol.as_str(), "ACCOUNT");
        assert_eq!(margin.instrument_id.venue.as_str(), "BINANCE");
        assert_eq!(margin.initial.as_f64(), 500.25);
        assert_eq!(margin.maintenance.as_f64(), 250.75);
    }

    #[rstest]
    fn test_account_info_to_account_state_empty_balance() {
        // Empty strings for balance fields (inactive/zero-balance accounts)
        let json = r#"{
            "assets": [{
                "asset": "USDT",
                "walletBalance": "",
                "availableBalance": "",
                "updateTime": 0
            }],
            "positions": []
        }"#;
        let account: BinanceFuturesAccountInfo =
            serde_json::from_str(json).expect("Failed to parse account info");

        let account_id = AccountId::from("BINANCE-001");
        let ts_init = UnixNanos::from(1_000_000_000u64);
        let state = account.to_account_state(account_id, ts_init).unwrap();

        assert_eq!(state.balances.len(), 1);
        let balance = &state.balances[0];
        assert_eq!(balance.total, Money::new(0.0, Currency::USDT()));
        assert_eq!(balance.free, Money::new(0.0, Currency::USDT()));
        assert_eq!(balance.locked, Money::new(0.0, Currency::USDT()));
    }

    #[rstest]
    fn test_account_info_to_account_state_empty_assets() {
        // No assets at all (completely empty account)
        let json = r#"{
            "assets": [],
            "positions": []
        }"#;
        let account: BinanceFuturesAccountInfo =
            serde_json::from_str(json).expect("Failed to parse account info");

        let account_id = AccountId::from("BINANCE-001");
        let ts_init = UnixNanos::from(1_000_000_000u64);
        let state = account.to_account_state(account_id, ts_init).unwrap();

        assert_eq!(state.balances.len(), 1);
        let balance = &state.balances[0];
        assert_eq!(balance.total, Money::new(0.0, Currency::USDT()));
    }

    #[rstest]
    fn test_parse_position_risk() {
        let json = load_fixture_string("futures/http_json/position_risk.json");
        let positions: Vec<BinancePositionRisk> =
            serde_json::from_str(&json).expect("Failed to parse position risk");

        assert_eq!(positions.len(), 1);
        assert_eq!(positions[0].symbol.as_str(), "BTCUSDT");
        assert_eq!(positions[0].position_amt, "0.001");
        assert_eq!(positions[0].mark_price, "51000.0");
        assert_eq!(positions[0].leverage, "20");
    }

    #[rstest]
    fn test_parse_balance_with_v1_field() {
        // V1 uses 'balance' field
        let json = load_fixture_string("futures/http_json/balance.json");
        let balances: Vec<BinanceFuturesBalance> =
            serde_json::from_str(&json).expect("Failed to parse balance");

        assert_eq!(balances.len(), 1);
        assert_eq!(balances[0].asset.as_str(), "USDT");
        // Uses alias to parse 'balance' into wallet_balance
        assert_eq!(balances[0].wallet_balance, "122.12345678");
        assert_eq!(balances[0].available_balance, "122.12345678");
    }

    #[rstest]
    fn test_parse_balance_with_v2_field() {
        // V2 uses 'walletBalance' field
        let json = r#"{
            "asset": "USDT",
            "walletBalance": "100.00000000",
            "availableBalance": "100.00000000",
            "updateTime": 1617939110373
        }"#;

        let balance: BinanceFuturesBalance =
            serde_json::from_str(json).expect("Failed to parse balance");

        assert_eq!(balance.asset.as_str(), "USDT");
        assert_eq!(balance.wallet_balance, "100.00000000");
    }

    #[rstest]
    fn test_parse_order() {
        let json = load_fixture_string("futures/http_json/order_response.json");
        let order: BinanceFuturesOrder =
            serde_json::from_str(&json).expect("Failed to parse order");

        assert_eq!(order.order_id, 12345678);
        assert_eq!(order.symbol.as_str(), "BTCUSDT");
        assert_eq!(order.status, BinanceOrderStatus::New);
        assert_eq!(order.time_in_force, BinanceTimeInForce::Gtc);
        assert_eq!(order.side, BinanceSide::Buy);
        assert_eq!(order.order_type, BinanceFuturesOrderType::Limit);
        assert_eq!(order.price_match, Some(BinancePriceMatch::None));
        assert_eq!(
            order.self_trade_prevention_mode,
            Some(BinanceSelfTradePreventionMode::None)
        );
    }

    #[rstest]
    fn test_parse_hedge_mode_response() {
        let json = r#"{"dualSidePosition": true}"#;
        let response: BinanceHedgeModeResponse =
            serde_json::from_str(json).expect("Failed to parse hedge mode");
        assert!(response.dual_side_position);
    }

    #[rstest]
    fn test_parse_leverage_response() {
        let json = r#"{"symbol": "BTCUSDT", "leverage": 20, "maxNotionalValue": "250000"}"#;
        let response: BinanceLeverageResponse =
            serde_json::from_str(json).expect("Failed to parse leverage");
        assert_eq!(response.symbol.as_str(), "BTCUSDT");
        assert_eq!(response.leverage, 20);
    }

    #[rstest]
    fn test_parse_listen_key_response() {
        let json =
            r#"{"listenKey": "pqia91ma19a5s61cv6a81va65sdf19v8a65a1a5s61cv6a81va65sdf19v8a65a1"}"#;
        let response: ListenKeyResponse =
            serde_json::from_str(json).expect("Failed to parse listen key");
        assert!(!response.listen_key.is_empty());
    }

    #[rstest]
    fn test_parse_account_position() {
        let json = r#"{
            "symbol": "ETHUSDT",
            "initialMargin": "100.00",
            "maintMargin": "50.00",
            "unrealizedProfit": "10.00",
            "positionInitialMargin": "100.00",
            "openOrderInitialMargin": "0",
            "leverage": "10",
            "isolated": true,
            "entryPrice": "2000.00",
            "maxNotional": "100000",
            "bidNotional": "0",
            "askNotional": "0",
            "positionSide": "LONG",
            "positionAmt": "0.5",
            "updateTime": 1625474304765
        }"#;

        let position: BinanceAccountPosition =
            serde_json::from_str(json).expect("Failed to parse account position");

        assert_eq!(position.symbol.as_str(), "ETHUSDT");
        assert_eq!(position.leverage, Some("10".to_string()));
        assert_eq!(position.isolated, Some(true));
        assert_eq!(position.position_side, Some(BinancePositionSide::Long));
    }

    #[rstest]
    fn test_parse_algo_order() {
        let json = r#"{
            "algoId": 123456789,
            "clientAlgoId": "test-algo-order-1",
            "algoType": "CONDITIONAL",
            "type": "STOP_MARKET",
            "symbol": "BTCUSDT",
            "side": "BUY",
            "positionSide": "BOTH",
            "timeInForce": "GTC",
            "quantity": "0.001",
            "algoStatus": "NEW",
            "triggerPrice": "45000.00",
            "workingType": "MARK_PRICE",
            "reduceOnly": false,
            "createTime": 1625474304765,
            "updateTime": 1625474304765
        }"#;

        let order: BinanceFuturesAlgoOrder =
            serde_json::from_str(json).expect("Failed to parse algo order");

        assert_eq!(order.algo_id, 123456789);
        assert_eq!(order.client_algo_id, "test-algo-order-1");
        assert_eq!(order.algo_type, BinanceAlgoType::Conditional);
        assert_eq!(order.order_type, BinanceFuturesOrderType::StopMarket);
        assert_eq!(order.symbol.as_str(), "BTCUSDT");
        assert_eq!(order.side, BinanceSide::Buy);
        assert_eq!(order.algo_status, Some(BinanceAlgoStatus::New));
        assert_eq!(order.trigger_price, Some("45000.00".to_string()));
    }

    #[rstest]
    fn test_parse_algo_order_triggered() {
        let json = r#"{
            "algoId": 123456789,
            "clientAlgoId": "test-algo-order-2",
            "algoType": "CONDITIONAL",
            "type": "TAKE_PROFIT",
            "symbol": "ETHUSDT",
            "side": "SELL",
            "algoStatus": "TRIGGERED",
            "triggerPrice": "2500.00",
            "price": "2500.00",
            "actualOrderId": "987654321",
            "executedQty": "0.5",
            "avgPrice": "2499.50"
        }"#;

        let order: BinanceFuturesAlgoOrder =
            serde_json::from_str(json).expect("Failed to parse triggered algo order");

        assert_eq!(order.algo_status, Some(BinanceAlgoStatus::Triggered));
        assert_eq!(order.order_type, BinanceFuturesOrderType::TakeProfit);
        assert_eq!(order.actual_order_id, Some("987654321".to_string()));
        assert_eq!(order.executed_qty, Some("0.5".to_string()));
    }

    #[rstest]
    fn test_parse_algo_order_cancel_response() {
        let json = r#"{
            "algoId": 123456789,
            "clientAlgoId": "test-algo-order-1",
            "code": "200",
            "msg": "success"
        }"#;

        let response: BinanceFuturesAlgoOrderCancelResponse =
            serde_json::from_str(json).expect("Failed to parse algo cancel response");

        assert_eq!(response.algo_id, 123456789);
        assert_eq!(response.client_algo_id, "test-algo-order-1");
        assert_eq!(response.code, "200");
        assert_eq!(response.msg, "success");
    }

    #[rstest]
    fn test_order_to_report_decodes_broker_id() {
        let json = r#"{
            "orderId": 12345678,
            "symbol": "BTCUSDT",
            "status": "NEW",
            "clientOrderId": "x-aHRE4BCj-T0000000000000",
            "price": "50000.00",
            "avgPrice": "0.00",
            "origQty": "0.001",
            "executedQty": "0.000",
            "cumQuote": "0.00",
            "timeInForce": "GTC",
            "type": "LIMIT",
            "reduceOnly": false,
            "closePosition": false,
            "side": "BUY",
            "positionSide": "BOTH",
            "stopPrice": "0.00",
            "workingType": "CONTRACT_PRICE",
            "priceProtect": false,
            "origType": "LIMIT",
            "priceMatch": "NONE",
            "selfTradePreventionMode": "NONE",
            "goodTillDate": 0,
            "time": 1625474304765,
            "updateTime": 1625474304765
        }"#;

        let order: BinanceFuturesOrder = serde_json::from_str(json).unwrap();
        let account_id = AccountId::from("BINANCE-FUTURES-001");
        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
        let ts_init = UnixNanos::from(1_000_000_000u64);

        let report = order
            .to_order_status_report(account_id, instrument_id, 3, false, ts_init)
            .unwrap();

        assert_eq!(
            report.client_order_id,
            Some(ClientOrderId::from("O-20200101-000000-000-000-0")),
        );
    }

    #[rstest]
    fn test_algo_order_to_report_decodes_broker_id() {
        let json = r#"{
            "algoId": 123456789,
            "clientAlgoId": "x-aHRE4BCj-Rmy-algo-order-1",
            "algoType": "CONDITIONAL",
            "type": "STOP_MARKET",
            "symbol": "BTCUSDT",
            "side": "BUY",
            "positionSide": "BOTH",
            "timeInForce": "GTC",
            "quantity": "0.001",
            "algoStatus": "NEW",
            "triggerPrice": "45000.00",
            "workingType": "MARK_PRICE",
            "reduceOnly": false,
            "createTime": 1625474304765,
            "updateTime": 1625474304765
        }"#;

        let order: BinanceFuturesAlgoOrder = serde_json::from_str(json).unwrap();
        let account_id = AccountId::from("BINANCE-FUTURES-001");
        let instrument_id = InstrumentId::from("BTCUSDT-PERP.BINANCE");
        let ts_init = UnixNanos::from(1_000_000_000u64);

        let report = order
            .to_order_status_report(account_id, instrument_id, 3, ts_init)
            .unwrap();

        assert_eq!(
            report.client_order_id,
            Some(ClientOrderId::from("my-algo-order-1")),
        );
    }

    #[rstest]
    #[case(BinanceOrderStatus::Expired, false, OrderStatus::Expired)]
    #[case(BinanceOrderStatus::Expired, true, OrderStatus::Canceled)]
    #[case(BinanceOrderStatus::ExpiredInMatch, false, OrderStatus::Expired)]
    #[case(BinanceOrderStatus::ExpiredInMatch, true, OrderStatus::Canceled)]
    fn test_to_nautilus_order_status_expired_respects_treat_as_canceled(
        #[case] status: BinanceOrderStatus,
        #[case] treat_expired_as_canceled: bool,
        #[case] expected: OrderStatus,
    ) {
        let result = status.to_nautilus_order_status(treat_expired_as_canceled);
        assert_eq!(result, expected);
    }
}