digdigdig3 0.1.19

Unified async Rust API for 44 exchange connectors — crypto, stocks, forex. REST + WebSocket.
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
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
//! # Binance Connector
//!
//! Реализация всех core трейтов для Binance.
//!
//! ## Core трейты
//! - `ExchangeIdentity` - идентификация биржи
//! - `MarketData` - рыночные данные
//! - `Trading` - торговые операции
//! - `Account` - информация об аккаунте
//! - `Positions` - futures позиции

use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use async_trait::async_trait;
use serde_json::{json, Value};

use crate::core::{
    HttpClient, Credentials,
    ExchangeId, ExchangeType, AccountType, Symbol,
    ExchangeError, ExchangeResult,
    Price, Kline, Ticker, OrderBook,
    Order, OrderSide, OrderType, Balance, AccountInfo,
    Position, FundingRate,
    OrderRequest, CancelRequest, CancelScope,
    BalanceQuery, PositionQuery, PositionModification,
    OrderHistoryFilter, PlaceOrderResponse, FeeInfo,
    AmendRequest, CancelAllResponse, OrderResult,
    MarginType,
    UserTrade, UserTradeFilter,
};
use crate::core::types::{
    ConnectorStats, SymbolInfo,
    TransferRequest, TransferHistoryFilter, TransferResponse,
    DepositAddress, WithdrawRequest, WithdrawResponse, FundsRecord,
    FundsHistoryFilter, FundsRecordType,
    SubAccountOperation, SubAccountResult,
};
use crate::core::traits::{
    ExchangeIdentity, MarketData, Trading, Account, Positions,
    CancelAll, AmendOrder, BatchOrders,
    AccountTransfers, CustodialFunds, SubAccounts,
    FundingHistory, AccountLedger,
};
use crate::core::types::{
    FundingPayment, FundingFilter,
    LedgerEntry, LedgerFilter,
};
use crate::core::utils::WeightRateLimiter;

use super::endpoints::{BinanceUrls, BinanceEndpoint, format_symbol, map_kline_interval};
use super::auth::BinanceAuth;
use super::parser::BinanceParser;

// Binance endpoint weights (from API docs)
mod weights {
    pub const PING: u32 = 1;
    pub const KLINES: u32 = 2;
    pub const TICKER_24H: u32 = 1;
    pub const ACCOUNT: u32 = 10;
    pub const ORDER: u32 = 1;
    pub const DEFAULT: u32 = 1;

    /// Weight for /depth endpoint, scaled by limit parameter.
    /// Reference: https://binance-docs.github.io/apidocs/spot/en/#order-book
    pub const fn depth_weight(limit: u16) -> u32 {
        match limit {
            0..=100 => 5,
            101..=500 => 25,
            501..=1000 => 50,
            _ => 250,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// CONNECTOR
// ═══════════════════════════════════════════════════════════════════════════════

/// Binance коннектор
pub struct BinanceConnector {
    /// HTTP клиент
    http: HttpClient,
    /// Аутентификация (None для публичных методов)
    auth: Option<BinanceAuth>,
    /// URL'ы (mainnet/testnet)
    urls: BinanceUrls,
    /// Testnet mode
    testnet: bool,
    /// Weight-based rate limiter (6000 weight per minute)
    weight_limiter: Arc<Mutex<WeightRateLimiter>>,
    /// Per-symbol precision cache (populated from get_exchange_info)
    precision: crate::core::utils::precision::PrecisionCache,
}

impl BinanceConnector {
    /// Создать новый коннектор
    pub async fn new(credentials: Option<Credentials>, testnet: bool) -> ExchangeResult<Self> {
        let urls = if testnet {
            BinanceUrls::TESTNET
        } else {
            BinanceUrls::MAINNET
        };

        let http = HttpClient::new(30_000)?; // 30 sec timeout

        let mut auth = credentials
            .as_ref()
            .map(BinanceAuth::new)
            .transpose()?;

        // Sync time with server if we have auth
        if auth.is_some() {
            let base_url = urls.rest_url(AccountType::Spot);
            let url = format!("{}/api/v3/time", base_url);
            if let Ok(response) = http.get(&url, &HashMap::new()).await {
                if let Some(server_time) = response.get("serverTime").and_then(|t| t.as_i64()) {
                    if let Some(ref mut a) = auth {
                        a.sync_time(server_time);
                    }
                }
            }
        }

        // Initialize weight limiter: 6000 weight per minute
        let weight_limiter = Arc::new(Mutex::new(
            WeightRateLimiter::new(6000, Duration::from_secs(60))
        ));

        Ok(Self {
            http,
            auth,
            urls,
            testnet,
            weight_limiter,
            precision: crate::core::utils::precision::PrecisionCache::new(),
        })
    }

    /// Создать коннектор только для публичных методов
    pub async fn public(testnet: bool) -> ExchangeResult<Self> {
        Self::new(None, testnet).await
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // BINANCE-SPECIFIC PUBLIC METHODS
    // ═══════════════════════════════════════════════════════════════════════════

    /// Fetch up to `total_bars` klines with backward pagination.
    ///
    /// Binance limits to 1000 klines per request. This method chains
    /// multiple requests, walking backward in time from `end_time` (or now
    /// if `None`), until `total_bars` klines are collected or no more data
    /// is available.
    ///
    /// The returned slice is in chronological order (oldest first).
    pub async fn get_klines_paginated(
        &self,
        symbol: Symbol,
        interval: &str,
        total_bars: usize,
        account_type: AccountType,
    ) -> ExchangeResult<Vec<Kline>> {
        const LIMIT_PER_REQUEST: usize = 1000;

        let endpoint = match account_type {
            AccountType::Spot | AccountType::Margin => BinanceEndpoint::SpotKlines,
            _ => BinanceEndpoint::FuturesKlines,
        };

        let symbol_str = format_symbol(&symbol.base, &symbol.quote, account_type);
        let interval_str = map_kline_interval(interval).to_string();

        let mut all_klines: Vec<Kline> = Vec::with_capacity(total_bars);
        let mut end_time: Option<i64> = None; // None = latest (now)

        loop {
            let mut params = HashMap::new();
            params.insert("symbol".to_string(), symbol_str.clone());
            params.insert("interval".to_string(), interval_str.clone());
            params.insert("limit".to_string(), LIMIT_PER_REQUEST.to_string());

            if let Some(et) = end_time {
                params.insert("endTime".to_string(), et.to_string());
            }

            let response = self.get(endpoint, params, account_type).await?;
            let batch = BinanceParser::parse_klines(&response)?;

            if batch.is_empty() {
                break;
            }

            let batch_len = batch.len();

            // Use the first bar's open_time - 1ms as the next endTime cursor,
            // so the next request fetches bars strictly before this batch.
            end_time = Some(batch[0].open_time - 1);

            // Prepend the batch to keep chronological order: older data goes first.
            let mut combined = batch;
            combined.append(&mut all_klines);
            all_klines = combined;

            if all_klines.len() >= total_bars {
                break;
            }

            // If the exchange returned fewer bars than the limit, there is no
            // more historical data available.
            if batch_len < LIMIT_PER_REQUEST {
                break;
            }
        }

        // Trim to the requested count, keeping the most recent bars.
        if all_klines.len() > total_bars {
            all_klines = all_klines.split_off(all_klines.len() - total_bars);
        }

        Ok(all_klines)
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // RATE LIMITING
    // ═══════════════════════════════════════════════════════════════════════════

    /// Wait for rate limit if necessary before making a request
    async fn rate_limit_wait(&self, weight: u32) {
        loop {
            let wait_time = {
                let mut limiter = self.weight_limiter.lock()
                    .expect("Weight limiter mutex poisoned");
                if limiter.try_acquire(weight) {
                    return;
                }
                limiter.time_until_ready(weight)
            };
            if wait_time > Duration::ZERO {
                tokio::time::sleep(wait_time).await;
            }
        }
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // HTTP HELPERS
    // ═══════════════════════════════════════════════════════════════════════════

    /// Обновить weight limiter из заголовка ответа X-MBX-USED-WEIGHT-1M
    fn update_weight_from_headers(&self, headers: &reqwest::header::HeaderMap) {
        if let Some(weight) = headers
            .get("X-MBX-USED-WEIGHT-1M")
            .and_then(|v| v.to_str().ok())
            .and_then(|s| s.parse::<u32>().ok())
        {
            if let Ok(mut limiter) = self.weight_limiter.lock() {
                limiter.update_from_server(weight);
            }
        }
    }

    /// GET запрос
    async fn get(
        &self,
        endpoint: BinanceEndpoint,
        mut params: HashMap<String, String>,
        account_type: AccountType,
    ) -> ExchangeResult<Value> {
        // Rate limit check with per-endpoint weights
        let weight = match endpoint {
            BinanceEndpoint::Ping => weights::PING,
            BinanceEndpoint::SpotKlines | BinanceEndpoint::FuturesKlines => weights::KLINES,
            BinanceEndpoint::SpotOrderbook | BinanceEndpoint::FuturesOrderbook => {
                let limit: u16 = params.get("limit")
                    .and_then(|v| v.parse().ok())
                    .unwrap_or(100);
                weights::depth_weight(limit)
            }
            BinanceEndpoint::SpotTicker | BinanceEndpoint::FuturesTicker => weights::TICKER_24H,
            BinanceEndpoint::SpotAccount | BinanceEndpoint::FuturesAccount => weights::ACCOUNT,
            BinanceEndpoint::SpotGetOrder | BinanceEndpoint::FuturesGetOrder => weights::ORDER,
            BinanceEndpoint::SpotOpenOrders | BinanceEndpoint::FuturesOpenOrders => weights::ORDER,
            BinanceEndpoint::FuturesPositions => weights::ACCOUNT,
            BinanceEndpoint::FundingRate => weights::DEFAULT,
            _ => weights::DEFAULT,
        };
        self.rate_limit_wait(weight).await;

        let base_url = self.urls.rest_url(account_type);
        let path = endpoint.path();

        // Add auth if needed
        let headers = if endpoint.requires_auth() {
            let auth = self.auth.as_ref()
                .ok_or_else(|| ExchangeError::Auth("Authentication required".to_string()))?;
            auth.sign_request(&mut params)
        } else {
            HashMap::new()
        };

        // Build query string
        let query = if params.is_empty() {
            String::new()
        } else {
            let qs: Vec<String> = params.iter()
                .map(|(k, v)| format!("{}={}", k, v))
                .collect();
            format!("?{}", qs.join("&"))
        };

        let url = format!("{}{}{}", base_url, path, query);

        let (response, resp_headers) = self.http.get_with_response_headers(&url, &HashMap::new(), &headers).await?;
        self.update_weight_from_headers(&resp_headers);
        BinanceParser::check_error(&response)?;
        Ok(response)
    }

    /// POST запрос
    async fn post(
        &self,
        endpoint: BinanceEndpoint,
        mut params: HashMap<String, String>,
        account_type: AccountType,
    ) -> ExchangeResult<Value> {
        // POST endpoints: order placement/amend = weight 1
        let weight = match endpoint {
            BinanceEndpoint::SpotCreateOrder | BinanceEndpoint::FuturesCreateOrder => weights::ORDER,
            BinanceEndpoint::FuturesSetLeverage => weights::DEFAULT,
            _ => weights::DEFAULT,
        };
        self.rate_limit_wait(weight).await;

        let base_url = self.urls.rest_url(account_type);
        let path = endpoint.path();

        // Auth required for POST
        let auth = self.auth.as_ref()
            .ok_or_else(|| ExchangeError::Auth("Authentication required".to_string()))?;

        let headers = auth.sign_request(&mut params);

        // Build query string (Binance uses query params for POST too)
        let query = if params.is_empty() {
            String::new()
        } else {
            let qs: Vec<String> = params.iter()
                .map(|(k, v)| format!("{}={}", k, v))
                .collect();
            format!("?{}", qs.join("&"))
        };

        let url = format!("{}{}{}", base_url, path, query);

        // POST with empty body, params in query string
        let (response, resp_headers) = self.http.post_with_response_headers(&url, &json!({}), &headers).await?;
        self.update_weight_from_headers(&resp_headers);
        BinanceParser::check_error(&response)?;
        Ok(response)
    }

    /// PUT запрос (for order amend)
    async fn put(
        &self,
        endpoint: BinanceEndpoint,
        mut params: HashMap<String, String>,
        account_type: AccountType,
    ) -> ExchangeResult<Value> {
        self.rate_limit_wait(weights::ORDER).await;

        let base_url = self.urls.rest_url(account_type);
        let path = endpoint.path();

        let auth = self.auth.as_ref()
            .ok_or_else(|| ExchangeError::Auth("Authentication required".to_string()))?;

        let headers = auth.sign_request(&mut params);

        let query = if params.is_empty() {
            String::new()
        } else {
            let qs: Vec<String> = params.iter()
                .map(|(k, v)| format!("{}={}", k, v))
                .collect();
            format!("?{}", qs.join("&"))
        };

        let url = format!("{}{}{}", base_url, path, query);

        // HttpClient::put does not return headers; use it directly
        let response = self.http.put(&url, &json!({}), &headers).await?;
        BinanceParser::check_error(&response)?;
        Ok(response)
    }

    /// PATCH запрос (for batch amend)
    async fn patch(
        &self,
        endpoint: BinanceEndpoint,
        mut params: HashMap<String, String>,
        account_type: AccountType,
    ) -> ExchangeResult<Value> {
        self.rate_limit_wait(weights::DEFAULT).await;

        let base_url = self.urls.rest_url(account_type);
        let path = endpoint.path();

        let auth = self.auth.as_ref()
            .ok_or_else(|| ExchangeError::Auth("Authentication required".to_string()))?;

        let headers = auth.sign_request(&mut params);

        let query = if params.is_empty() {
            String::new()
        } else {
            let qs: Vec<String> = params.iter()
                .map(|(k, v)| format!("{}={}", k, v))
                .collect();
            format!("?{}", qs.join("&"))
        };

        let url = format!("{}{}{}", base_url, path, query);

        let response = self.http.patch(&url, &json!({}), &headers).await?;
        BinanceParser::check_error(&response)?;
        Ok(response)
    }

    /// DELETE запрос
    async fn delete(
        &self,
        endpoint: BinanceEndpoint,
        mut params: HashMap<String, String>,
        account_type: AccountType,
    ) -> ExchangeResult<Value> {
        // DELETE endpoints: cancel order = weight 1
        let weight = match endpoint {
            BinanceEndpoint::SpotCancelOrder | BinanceEndpoint::FuturesCancelOrder => weights::ORDER,
            _ => weights::DEFAULT,
        };
        self.rate_limit_wait(weight).await;

        let base_url = self.urls.rest_url(account_type);
        let path = endpoint.path();

        // Auth required for DELETE
        let auth = self.auth.as_ref()
            .ok_or_else(|| ExchangeError::Auth("Authentication required".to_string()))?;

        let headers = auth.sign_request(&mut params);

        // Build query string
        let query = if params.is_empty() {
            String::new()
        } else {
            let qs: Vec<String> = params.iter()
                .map(|(k, v)| format!("{}={}", k, v))
                .collect();
            format!("?{}", qs.join("&"))
        };

        let url = format!("{}{}{}", base_url, path, query);

        let (response, resp_headers) = self.http.delete_with_response_headers(&url, &HashMap::new(), &headers).await?;
        self.update_weight_from_headers(&resp_headers);
        BinanceParser::check_error(&response)?;
        Ok(response)
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // MARKET DATA EXTENSIONS
    // ═══════════════════════════════════════════════════════════════════════════

    /// Get recent trades for a symbol.
    ///
    /// Returns up to `limit` recent trades (max 1000).
    pub async fn get_recent_trades(
        &self,
        symbol: &str,
        limit: Option<u32>,
        account_type: AccountType,
    ) -> ExchangeResult<Value> {
        let endpoint = match account_type {
            AccountType::Spot | AccountType::Margin => BinanceEndpoint::SpotRecentTrades,
            _ => BinanceEndpoint::FuturesRecentTrades,
        };
        let mut params = HashMap::new();
        params.insert("symbol".to_string(), symbol.to_string());
        if let Some(l) = limit {
            params.insert("limit".to_string(), l.to_string());
        }
        self.get(endpoint, params, account_type).await
    }

    /// Get current average price for a symbol (spot only).
    pub async fn get_avg_price(&self, symbol: &str) -> ExchangeResult<Value> {
        let mut params = HashMap::new();
        params.insert("symbol".to_string(), symbol.to_string());
        self.get(BinanceEndpoint::SpotAvgPrice, params, AccountType::Spot).await
    }

    /// Get best bid/ask price for a symbol (or all symbols if `symbol` is None).
    pub async fn get_book_ticker(&self, symbol: Option<&str>) -> ExchangeResult<Value> {
        let mut params = HashMap::new();
        if let Some(s) = symbol {
            params.insert("symbol".to_string(), s.to_string());
        }
        self.get(BinanceEndpoint::SpotBookTicker, params, AccountType::Spot).await
    }

    /// Get open interest for a futures symbol.
    pub async fn get_open_interest(&self, symbol: &str) -> ExchangeResult<Value> {
        let mut params = HashMap::new();
        params.insert("symbol".to_string(), symbol.to_string());
        self.get(BinanceEndpoint::FuturesOpenInterest, params, AccountType::FuturesCross).await
    }

    /// Get mark price and funding rate for a futures symbol.
    pub async fn get_premium_index(&self, symbol: Option<&str>) -> ExchangeResult<Value> {
        let mut params = HashMap::new();
        if let Some(s) = symbol {
            params.insert("symbol".to_string(), s.to_string());
        }
        self.get(BinanceEndpoint::FuturesPremiumIndex, params, AccountType::FuturesCross).await
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // FILL / TRADE HISTORY
    // ═══════════════════════════════════════════════════════════════════════════

    /// Get personal trade fills for a symbol.
    ///
    /// `account_type` selects spot vs futures endpoint.
    /// `start_time` and `end_time` are Unix milliseconds.
    pub async fn get_my_trades(
        &self,
        symbol: &str,
        account_type: AccountType,
        limit: Option<u32>,
        start_time: Option<i64>,
        end_time: Option<i64>,
    ) -> ExchangeResult<Value> {
        let endpoint = match account_type {
            AccountType::Spot | AccountType::Margin => BinanceEndpoint::SpotMyTrades,
            _ => BinanceEndpoint::FuturesMyTrades,
        };
        let mut params = HashMap::new();
        params.insert("symbol".to_string(), symbol.to_string());
        if let Some(l) = limit {
            params.insert("limit".to_string(), l.to_string());
        }
        if let Some(st) = start_time {
            params.insert("startTime".to_string(), st.to_string());
        }
        if let Some(et) = end_time {
            params.insert("endTime".to_string(), et.to_string());
        }
        self.get(endpoint, params, account_type).await
    }

    /// Get futures income history (PnL, funding fees, etc.).
    ///
    /// `income_type`: e.g. `"REALIZED_PNL"`, `"FUNDING_FEE"`, `"COMMISSION"`.
    pub async fn get_income_history(
        &self,
        symbol: Option<&str>,
        income_type: Option<&str>,
        limit: Option<u32>,
    ) -> ExchangeResult<Value> {
        let mut params = HashMap::new();
        if let Some(s) = symbol {
            params.insert("symbol".to_string(), s.to_string());
        }
        if let Some(t) = income_type {
            params.insert("incomeType".to_string(), t.to_string());
        }
        if let Some(l) = limit {
            params.insert("limit".to_string(), l.to_string());
        }
        self.get(BinanceEndpoint::FuturesIncomeHistory, params, AccountType::FuturesCross).await
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // LISTEN KEY MANAGEMENT
    // ═══════════════════════════════════════════════════════════════════════════

    /// Keepalive a spot user data stream listen key (extend 60-min TTL).
    pub async fn keepalive_listen_key(&self, listen_key: &str) -> ExchangeResult<Value> {
        self.rate_limit_wait(weights::DEFAULT).await;
        let base_url = self.urls.rest_url(AccountType::Spot);
        let auth = self.auth.as_ref()
            .ok_or_else(|| ExchangeError::Auth("Authentication required".to_string()))?;
        let mut params = HashMap::new();
        params.insert("listenKey".to_string(), listen_key.to_string());
        let headers = auth.sign_request(&mut params);
        let query = format!("?listenKey={}", listen_key);
        let url = format!("{}{}{}", base_url, BinanceEndpoint::ListenKeyKeepAlive.path(), query);
        let response = self.http.put(&url, &json!({}), &headers).await?;
        BinanceParser::check_error(&response)?;
        Ok(response)
    }

    /// Close a spot user data stream listen key.
    pub async fn close_listen_key(&self, listen_key: &str) -> ExchangeResult<Value> {
        let mut params = HashMap::new();
        params.insert("listenKey".to_string(), listen_key.to_string());
        self.delete(BinanceEndpoint::ListenKeyClose, params, AccountType::Spot).await
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// EXCHANGE IDENTITY
// ═══════════════════════════════════════════════════════════════════════════════

impl ExchangeIdentity for BinanceConnector {
    fn exchange_id(&self) -> ExchangeId {
        ExchangeId::Binance
    }

    fn is_testnet(&self) -> bool {
        self.testnet
    }

    fn supported_account_types(&self) -> Vec<AccountType> {
        vec![
            AccountType::Spot,
            AccountType::Margin,
            AccountType::FuturesCross,
            AccountType::FuturesIsolated,
        ]
    }

    fn exchange_type(&self) -> ExchangeType {
        ExchangeType::Cex
    }

    fn metrics(&self) -> ConnectorStats {
        let (http_requests, http_errors, last_latency_ms) = self.http.stats();
        let (rate_used, rate_max) = if let Ok(mut limiter) = self.weight_limiter.lock() {
            (limiter.current_weight(), limiter.max_weight())
        } else {
            (0, 0)
        };
        ConnectorStats {
            http_requests,
            http_errors,
            last_latency_ms,
            rate_used,
            rate_max,
            rate_groups: Vec::new(),
            ws_ping_rtt_ms: 0,
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// MARKET DATA
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl MarketData for BinanceConnector {
    async fn get_price(
        &self,
        symbol: Symbol,
        account_type: AccountType,
    ) -> ExchangeResult<Price> {
        let endpoint = match account_type {
            AccountType::Spot | AccountType::Margin => BinanceEndpoint::SpotPrice,
            _ => BinanceEndpoint::FuturesPrice,
        };

        let mut params = HashMap::new();
        params.insert("symbol".to_string(), format_symbol(&symbol.base, &symbol.quote, account_type));

        let response = self.get(endpoint, params, account_type).await?;
        BinanceParser::parse_price(&response)
    }

    async fn get_orderbook(
        &self,
        symbol: Symbol,
        depth: Option<u16>,
        account_type: AccountType,
    ) -> ExchangeResult<OrderBook> {
        let endpoint = match account_type {
            AccountType::Spot | AccountType::Margin => BinanceEndpoint::SpotOrderbook,
            _ => BinanceEndpoint::FuturesOrderbook,
        };

        let mut params = HashMap::new();
        params.insert("symbol".to_string(), format_symbol(&symbol.base, &symbol.quote, account_type));

        if let Some(d) = depth {
            params.insert("limit".to_string(), d.to_string());
        }

        let response = self.get(endpoint, params, account_type).await?;
        BinanceParser::parse_orderbook(&response)
    }

    async fn get_klines(
        &self,
        symbol: Symbol,
        interval: &str,
        limit: Option<u16>,
        account_type: AccountType,
        end_time: Option<i64>,
    ) -> ExchangeResult<Vec<Kline>> {
        let endpoint = match account_type {
            AccountType::Spot | AccountType::Margin => BinanceEndpoint::SpotKlines,
            _ => BinanceEndpoint::FuturesKlines,
        };

        let mut params = HashMap::new();
        params.insert("symbol".to_string(), format_symbol(&symbol.base, &symbol.quote, account_type));
        params.insert("interval".to_string(), map_kline_interval(interval).to_string());

        if let Some(l) = limit {
            params.insert("limit".to_string(), l.min(1000).to_string());
        }

        if let Some(et) = end_time {
            params.insert("endTime".to_string(), et.to_string());
        }

        let response = self.get(endpoint, params, account_type).await?;
        BinanceParser::parse_klines(&response)
    }

    async fn get_ticker(
        &self,
        symbol: Symbol,
        account_type: AccountType,
    ) -> ExchangeResult<Ticker> {
        let endpoint = match account_type {
            AccountType::Spot | AccountType::Margin => BinanceEndpoint::SpotTicker,
            _ => BinanceEndpoint::FuturesTicker,
        };

        let mut params = HashMap::new();
        params.insert("symbol".to_string(), format_symbol(&symbol.base, &symbol.quote, account_type));

        let response = self.get(endpoint, params, account_type).await?;
        BinanceParser::parse_ticker(&response)
    }

    async fn ping(&self) -> ExchangeResult<()> {
        let response = self.get(BinanceEndpoint::Ping, HashMap::new(), AccountType::Spot).await?;
        BinanceParser::check_error(&response)
    }

    /// Получить информацию о всех торговых символах биржи
    ///
    /// Returns only symbols with `status == "TRADING"`.
    /// Use `AccountType::Spot` for spot markets, any other for futures.
    async fn get_exchange_info(&self, account_type: AccountType) -> ExchangeResult<Vec<SymbolInfo>> {
        let endpoint = match account_type {
            AccountType::Spot => BinanceEndpoint::SpotExchangeInfo,
            _ => BinanceEndpoint::FuturesExchangeInfo,
        };
        let response = self.get(endpoint, HashMap::new(), account_type).await?;
        let symbols = BinanceParser::parse_exchange_info(&response, account_type)?;
        self.precision.load_from_symbols(&symbols);
        Ok(symbols)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// TRADING
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl Trading for BinanceConnector {
    async fn place_order(&self, req: OrderRequest) -> ExchangeResult<PlaceOrderResponse> {
        let symbol = req.symbol;
        let side = req.side;
        let quantity = req.quantity;
        let account_type = req.account_type;
        let symbol_str = format_symbol(&symbol.base, &symbol.quote, account_type);

        match req.order_type {
            OrderType::Market => {
                let endpoint = match account_type {
                    AccountType::Spot | AccountType::Margin => BinanceEndpoint::SpotCreateOrder,
                    _ => BinanceEndpoint::FuturesCreateOrder,
                };

                let mut params = HashMap::new();
                params.insert("symbol".to_string(), format_symbol(&symbol.base, &symbol.quote, account_type));
                params.insert("side".to_string(), match side {
                    OrderSide::Buy => "BUY".to_string(),
                    OrderSide::Sell => "SELL".to_string(),
                });
                params.insert("type".to_string(), "MARKET".to_string());
                params.insert("quantity".to_string(), self.precision.qty(&symbol_str, quantity));

                let response = self.post(endpoint, params, account_type).await?;
                let order = BinanceParser::parse_order(&response, &symbol.to_string())?;
                Ok(PlaceOrderResponse::Simple(order))
            }
            OrderType::Limit { price } => {
                let endpoint = match account_type {
                    AccountType::Spot | AccountType::Margin => BinanceEndpoint::SpotCreateOrder,
                    _ => BinanceEndpoint::FuturesCreateOrder,
                };

                let mut params = HashMap::new();
                params.insert("symbol".to_string(), format_symbol(&symbol.base, &symbol.quote, account_type));
                params.insert("side".to_string(), side.as_str().to_string());
                params.insert("type".to_string(), "LIMIT".to_string());
                params.insert("quantity".to_string(), self.precision.qty(&symbol_str, quantity));
                params.insert("price".to_string(), self.precision.price(&symbol_str, price));
                params.insert("timeInForce".to_string(), "GTC".to_string());

                if let Some(cid) = &req.client_order_id {
                    params.insert("newClientOrderId".to_string(), cid.clone());
                }

                let response = self.post(endpoint, params, account_type).await?;
                let order = BinanceParser::parse_order(&response, &symbol.to_string())?;
                Ok(PlaceOrderResponse::Simple(order))
            }

            OrderType::StopMarket { stop_price } => {
                // Spot: no native STOP_MARKET. Futures only.
                match account_type {
                    AccountType::Spot | AccountType::Margin => {
                        return Err(ExchangeError::UnsupportedOperation(
                            "StopMarket not supported on Spot/Margin (Binance Futures only)".to_string()
                        ));
                    }
                    _ => {}
                }

                // Post-2025-12-09: STOP_MARKET moved to /fapi/v1/order/algo on Futures.
                let mut params = HashMap::new();
                params.insert("symbol".to_string(), format_symbol(&symbol.base, &symbol.quote, account_type));
                params.insert("side".to_string(), side.as_str().to_string());
                params.insert("type".to_string(), "STOP_MARKET".to_string());
                params.insert("quantity".to_string(), self.precision.qty(&symbol_str, quantity));
                params.insert("stopPrice".to_string(), self.precision.price(&symbol_str, stop_price));

                if req.reduce_only {
                    params.insert("reduceOnly".to_string(), "true".to_string());
                }
                if let Some(cid) = &req.client_order_id {
                    params.insert("newClientOrderId".to_string(), cid.clone());
                }

                let response = self.post(BinanceEndpoint::FuturesAlgoOrder, params, account_type).await?;
                let order = BinanceParser::parse_order(&response, &symbol.to_string())?;
                Ok(PlaceOrderResponse::Simple(order))
            }

            OrderType::StopLimit { stop_price, limit_price } => {
                let mut params = HashMap::new();
                params.insert("symbol".to_string(), format_symbol(&symbol.base, &symbol.quote, account_type));
                params.insert("side".to_string(), side.as_str().to_string());
                params.insert("quantity".to_string(), self.precision.qty(&symbol_str, quantity));
                params.insert("stopPrice".to_string(), self.precision.price(&symbol_str, stop_price));
                params.insert("price".to_string(), self.precision.price(&symbol_str, limit_price));

                // Spot uses STOP_LOSS_LIMIT on /api/v3/order (unchanged).
                // Futures: post-2025-12-09 STOP type moved to /fapi/v1/order/algo.
                let endpoint = match account_type {
                    AccountType::Spot | AccountType::Margin => {
                        params.insert("type".to_string(), "STOP_LOSS_LIMIT".to_string());
                        params.insert("timeInForce".to_string(), "GTC".to_string());
                        BinanceEndpoint::SpotCreateOrder
                    }
                    _ => {
                        params.insert("type".to_string(), "STOP".to_string());
                        params.insert("timeInForce".to_string(), "GTC".to_string());
                        BinanceEndpoint::FuturesAlgoOrder
                    }
                };

                if req.reduce_only {
                    params.insert("reduceOnly".to_string(), "true".to_string());
                }
                if let Some(cid) = &req.client_order_id {
                    params.insert("newClientOrderId".to_string(), cid.clone());
                }

                let response = self.post(endpoint, params, account_type).await?;
                let order = BinanceParser::parse_order(&response, &symbol.to_string())?;
                Ok(PlaceOrderResponse::Simple(order))
            }

            OrderType::TrailingStop { callback_rate, activation_price } => {
                // Futures only
                match account_type {
                    AccountType::Spot | AccountType::Margin => {
                        return Err(ExchangeError::UnsupportedOperation(
                            "TrailingStop not supported on Spot/Margin (Binance Futures only)".to_string()
                        ));
                    }
                    _ => {}
                }

                // Post-2025-12-09: TRAILING_STOP_MARKET moved to /fapi/v1/order/algo on Futures.
                let mut params = HashMap::new();
                params.insert("symbol".to_string(), format_symbol(&symbol.base, &symbol.quote, account_type));
                params.insert("side".to_string(), side.as_str().to_string());
                params.insert("type".to_string(), "TRAILING_STOP_MARKET".to_string());
                params.insert("quantity".to_string(), self.precision.qty(&symbol_str, quantity));
                params.insert("callbackRate".to_string(), callback_rate.to_string());

                if let Some(ap) = activation_price {
                    params.insert("activationPrice".to_string(), ap.to_string());
                }
                if req.reduce_only {
                    params.insert("reduceOnly".to_string(), "true".to_string());
                }
                if let Some(cid) = &req.client_order_id {
                    params.insert("newClientOrderId".to_string(), cid.clone());
                }

                let response = self.post(BinanceEndpoint::FuturesAlgoOrder, params, account_type).await?;
                let order = BinanceParser::parse_order(&response, &symbol.to_string())?;
                Ok(PlaceOrderResponse::Simple(order))
            }

            OrderType::Oco { price, stop_price, stop_limit_price } => {
                // Spot only — Binance OCO is not available on Futures
                match account_type {
                    AccountType::Spot | AccountType::Margin => {}
                    _ => {
                        return Err(ExchangeError::UnsupportedOperation(
                            "OCO orders not supported on Futures (Binance Spot only)".to_string()
                        ));
                    }
                }

                let mut params = HashMap::new();
                params.insert("symbol".to_string(), format_symbol(&symbol.base, &symbol.quote, account_type));
                params.insert("side".to_string(), side.as_str().to_string());
                params.insert("quantity".to_string(), self.precision.qty(&symbol_str, quantity));
                params.insert("price".to_string(), self.precision.price(&symbol_str, price));
                params.insert("stopPrice".to_string(), self.precision.price(&symbol_str, stop_price));

                if let Some(slp) = stop_limit_price {
                    params.insert("stopLimitPrice".to_string(), self.precision.price(&symbol_str, slp));
                    params.insert("stopLimitTimeInForce".to_string(), "GTC".to_string());
                }
                if let Some(cid) = &req.client_order_id {
                    params.insert("listClientOrderId".to_string(), cid.clone());
                }

                let response = self.post(BinanceEndpoint::SpotOcoOrder, params, account_type).await?;
                let oco = BinanceParser::parse_oco_response(&response)?;
                Ok(PlaceOrderResponse::Oco(Box::new(oco)))
            }

            OrderType::Bracket { price, take_profit, stop_loss } => {
                // Spot: map to OTOCO (One-Triggers-a-One-Cancels-the-Other)
                // Futures: no native bracket — conditional orders are via algo endpoint separately
                match account_type {
                    AccountType::Spot | AccountType::Margin => {
                        // OTOCO: working order must be LIMIT or LIMIT_MAKER.
                        // entry price is required for OTOCO.
                        let entry_price = price.ok_or_else(|| ExchangeError::InvalidRequest(
                            "Bracket order on Binance Spot requires an entry price (market entry not supported for OTOCO)".to_string()
                        ))?;

                        let mut params = HashMap::new();
                        params.insert("symbol".to_string(), format_symbol(&symbol.base, &symbol.quote, account_type));
                        params.insert("side".to_string(), side.as_str().to_string());
                        params.insert("quantity".to_string(), self.precision.qty(&symbol_str, quantity));
                        // Working leg: LIMIT entry
                        params.insert("workingType".to_string(), "LIMIT".to_string());
                        params.insert("workingPrice".to_string(), self.precision.price(&symbol_str, entry_price));
                        params.insert("workingTimeInForce".to_string(), "GTC".to_string());
                        // Pending above leg: take-profit limit order (above entry for buy)
                        params.insert("pendingAboveType".to_string(), "LIMIT_MAKER".to_string());
                        params.insert("pendingAbovePrice".to_string(), self.precision.price(&symbol_str, take_profit));
                        // Pending below leg: stop-loss stop order (below entry for buy)
                        params.insert("pendingBelowType".to_string(), "STOP_LOSS".to_string());
                        params.insert("pendingBelowStopPrice".to_string(), self.precision.price(&symbol_str, stop_loss));

                        if let Some(cid) = &req.client_order_id {
                            params.insert("listClientOrderId".to_string(), cid.clone());
                        }

                        let response = self.post(BinanceEndpoint::SpotOtocoOrder, params, account_type).await?;
                        let bracket = BinanceParser::parse_otoco_response(&response)?;
                        Ok(PlaceOrderResponse::Bracket(Box::new(bracket)))
                    }
                    _ => {
                        Err(ExchangeError::UnsupportedOperation(
                            "Bracket orders not supported on Binance Futures. Use separate conditional/algo orders for TP/SL.".to_string()
                        ))
                    }
                }
            }

            OrderType::Iceberg { price, display_quantity } => {
                // Spot only — Binance Futures does not support iceberg
                match account_type {
                    AccountType::Spot | AccountType::Margin => {}
                    _ => {
                        return Err(ExchangeError::UnsupportedOperation(
                            "Iceberg orders not supported on Futures (Binance Spot only)".to_string()
                        ));
                    }
                }

                let mut params = HashMap::new();
                params.insert("symbol".to_string(), format_symbol(&symbol.base, &symbol.quote, account_type));
                params.insert("side".to_string(), side.as_str().to_string());
                params.insert("type".to_string(), "LIMIT".to_string());
                params.insert("quantity".to_string(), self.precision.qty(&symbol_str, quantity));
                params.insert("price".to_string(), self.precision.price(&symbol_str, price));
                params.insert("icebergQty".to_string(), self.precision.qty(&symbol_str, display_quantity));
                params.insert("timeInForce".to_string(), "GTC".to_string());

                if let Some(cid) = &req.client_order_id {
                    params.insert("newClientOrderId".to_string(), cid.clone());
                }

                let response = self.post(BinanceEndpoint::SpotCreateOrder, params, account_type).await?;
                let order = BinanceParser::parse_order(&response, &symbol.to_string())?;
                Ok(PlaceOrderResponse::Simple(order))
            }

            OrderType::Twap { duration_seconds, .. } => {
                // Binance TWAP lives in a separate Algo API namespace:
                // Spot:    POST /sapi/v1/algo/spot/newOrderTwap
                // Futures: POST /sapi/v1/algo/futures/newOrderTwap
                // Both use api.binance.com (not fapi) as the base URL.
                // Constraints: duration 300–86400 seconds; notional 1,000–100,000 USDT (Spot),
                //              1,000–1,000,000 USDT (Futures).

                // Validate duration range
                if !(300..=86_400).contains(&duration_seconds) {
                    return Err(ExchangeError::InvalidRequest(format!(
                        "Binance TWAP duration must be between 300 and 86400 seconds, got {}",
                        duration_seconds
                    )));
                }

                let endpoint = match account_type {
                    AccountType::Spot | AccountType::Margin => BinanceEndpoint::SpotAlgoTwap,
                    _ => BinanceEndpoint::FuturesAlgoTwap,
                };

                let mut params = HashMap::new();
                params.insert("symbol".to_string(), format_symbol(&symbol.base, &symbol.quote, account_type));
                params.insert("side".to_string(), side.as_str().to_string());
                params.insert("quantity".to_string(), self.precision.qty(&symbol_str, quantity));
                params.insert("duration".to_string(), duration_seconds.to_string());

                if let Some(cid) = &req.client_order_id {
                    params.insert("clientAlgoId".to_string(), cid.clone());
                }

                // Algo API base URL is always api.binance.com (Spot REST), even for Futures TWAP.
                // We force Spot account type for URL routing since both /sapi endpoints
                // live on api.binance.com.
                let response = self.post(endpoint, params, AccountType::Spot).await?;
                let algo = BinanceParser::parse_algo_order_response(&response)?;
                Ok(PlaceOrderResponse::Algo(algo))
            }

            OrderType::PostOnly { price } => {
                let endpoint = match account_type {
                    AccountType::Spot | AccountType::Margin => BinanceEndpoint::SpotCreateOrder,
                    _ => BinanceEndpoint::FuturesCreateOrder,
                };

                let mut params = HashMap::new();
                params.insert("symbol".to_string(), format_symbol(&symbol.base, &symbol.quote, account_type));
                params.insert("side".to_string(), side.as_str().to_string());
                params.insert("type".to_string(), "LIMIT".to_string());
                params.insert("quantity".to_string(), self.precision.qty(&symbol_str, quantity));
                params.insert("price".to_string(), self.precision.price(&symbol_str, price));
                // GTX = Post-Only on Binance (Good Till Crossing)
                params.insert("timeInForce".to_string(), "GTX".to_string());

                if let Some(cid) = &req.client_order_id {
                    params.insert("newClientOrderId".to_string(), cid.clone());
                }

                let response = self.post(endpoint, params, account_type).await?;
                let order = BinanceParser::parse_order(&response, &symbol.to_string())?;
                Ok(PlaceOrderResponse::Simple(order))
            }

            OrderType::Ioc { price } => {
                let endpoint = match account_type {
                    AccountType::Spot | AccountType::Margin => BinanceEndpoint::SpotCreateOrder,
                    _ => BinanceEndpoint::FuturesCreateOrder,
                };

                let mut params = HashMap::new();
                params.insert("symbol".to_string(), format_symbol(&symbol.base, &symbol.quote, account_type));
                params.insert("side".to_string(), side.as_str().to_string());
                params.insert("type".to_string(), "LIMIT".to_string());
                params.insert("quantity".to_string(), self.precision.qty(&symbol_str, quantity));
                params.insert("timeInForce".to_string(), "IOC".to_string());

                // Use the provided price, or fall back to a limit order at market
                if let Some(p) = price {
                    params.insert("price".to_string(), self.precision.price(&symbol_str, p));
                } else {
                    // IOC with no price — use MARKET type instead
                    params.insert("type".to_string(), "MARKET".to_string());
                    params.remove("timeInForce");
                }

                if let Some(cid) = &req.client_order_id {
                    params.insert("newClientOrderId".to_string(), cid.clone());
                }

                let response = self.post(endpoint, params, account_type).await?;
                let order = BinanceParser::parse_order(&response, &symbol.to_string())?;
                Ok(PlaceOrderResponse::Simple(order))
            }

            OrderType::Fok { price } => {
                let endpoint = match account_type {
                    AccountType::Spot | AccountType::Margin => BinanceEndpoint::SpotCreateOrder,
                    _ => BinanceEndpoint::FuturesCreateOrder,
                };

                let mut params = HashMap::new();
                params.insert("symbol".to_string(), format_symbol(&symbol.base, &symbol.quote, account_type));
                params.insert("side".to_string(), side.as_str().to_string());
                params.insert("type".to_string(), "LIMIT".to_string());
                params.insert("quantity".to_string(), self.precision.qty(&symbol_str, quantity));
                params.insert("price".to_string(), self.precision.price(&symbol_str, price));
                params.insert("timeInForce".to_string(), "FOK".to_string());

                if let Some(cid) = &req.client_order_id {
                    params.insert("newClientOrderId".to_string(), cid.clone());
                }

                let response = self.post(endpoint, params, account_type).await?;
                let order = BinanceParser::parse_order(&response, &symbol.to_string())?;
                Ok(PlaceOrderResponse::Simple(order))
            }

            OrderType::Gtd { price, expire_time } => {
                // GTD is only supported on Binance USDS-M Futures.
                // Spot only supports GTC, IOC, FOK — GTD returns UnsupportedOperation.
                match account_type {
                    AccountType::Spot | AccountType::Margin => {
                        return Err(ExchangeError::UnsupportedOperation(
                            "GTD (Good-Till-Date) is not supported on Binance Spot/Margin. \
                             Binance Spot only supports GTC, IOC, FOK timeInForce.".to_string()
                        ));
                    }
                    _ => {}
                }

                // Binance requires goodTillDate > current_time + 600s.
                // We validate the value is a valid ms timestamp in range:
                // max = 253402300799000 (year 9999).
                if expire_time <= 0 || expire_time > 253_402_300_799_000 {
                    return Err(ExchangeError::InvalidRequest(
                        "GTD expire_time must be a valid Unix ms timestamp (>0 and < 253402300799000)".to_string()
                    ));
                }

                let mut params = HashMap::new();
                params.insert("symbol".to_string(), format_symbol(&symbol.base, &symbol.quote, account_type));
                params.insert("side".to_string(), side.as_str().to_string());
                params.insert("type".to_string(), "LIMIT".to_string());
                params.insert("quantity".to_string(), self.precision.qty(&symbol_str, quantity));
                params.insert("price".to_string(), self.precision.price(&symbol_str, price));
                params.insert("timeInForce".to_string(), "GTD".to_string());
                params.insert("goodTillDate".to_string(), expire_time.to_string());

                if req.reduce_only {
                    params.insert("reduceOnly".to_string(), "true".to_string());
                }
                if let Some(cid) = &req.client_order_id {
                    params.insert("newClientOrderId".to_string(), cid.clone());
                }

                let response = self.post(BinanceEndpoint::FuturesCreateOrder, params, account_type).await?;
                let order = BinanceParser::parse_order(&response, &symbol.to_string())?;
                Ok(PlaceOrderResponse::Simple(order))
            }

            OrderType::ReduceOnly { price } => {
                // Futures only
                match account_type {
                    AccountType::Spot | AccountType::Margin => {
                        return Err(ExchangeError::UnsupportedOperation(
                            "ReduceOnly not supported on Spot/Margin".to_string()
                        ));
                    }
                    _ => {}
                }

                let mut params = HashMap::new();
                params.insert("symbol".to_string(), format_symbol(&symbol.base, &symbol.quote, account_type));
                params.insert("side".to_string(), side.as_str().to_string());
                params.insert("reduceOnly".to_string(), "true".to_string());
                params.insert("quantity".to_string(), self.precision.qty(&symbol_str, quantity));

                if let Some(p) = price {
                    params.insert("type".to_string(), "LIMIT".to_string());
                    params.insert("price".to_string(), self.precision.price(&symbol_str, p));
                    params.insert("timeInForce".to_string(), "GTC".to_string());
                } else {
                    params.insert("type".to_string(), "MARKET".to_string());
                }

                if let Some(cid) = &req.client_order_id {
                    params.insert("newClientOrderId".to_string(), cid.clone());
                }

                let response = self.post(BinanceEndpoint::FuturesCreateOrder, params, account_type).await?;
                let order = BinanceParser::parse_order(&response, &symbol.to_string())?;
                Ok(PlaceOrderResponse::Simple(order))
            }
            _ => Err(ExchangeError::UnsupportedOperation(
                "This order type is not supported by Binance".to_string()
            )),
        }
    }

    async fn cancel_order(&self, req: CancelRequest) -> ExchangeResult<Order> {
        match req.scope {
            CancelScope::Single { ref order_id } => {
                let symbol = req.symbol.as_ref()
                    .ok_or_else(|| ExchangeError::InvalidRequest("Symbol required for cancel".into()))?;
                let account_type = req.account_type;

                let endpoint = match account_type {
                    AccountType::Spot | AccountType::Margin => BinanceEndpoint::SpotCancelOrder,
                    _ => BinanceEndpoint::FuturesCancelOrder,
                };

                let mut params = HashMap::new();
                params.insert("symbol".to_string(), format_symbol(&symbol.base, &symbol.quote, account_type));
                params.insert("orderId".to_string(), order_id.to_string());

                let response = self.delete(endpoint, params, account_type).await?;
                BinanceParser::parse_order(&response, &symbol.to_string())
            }
            CancelScope::Batch { .. } => {
                // Batch cancel is handled by BatchOrders trait; not available via Trading::cancel_order
                Err(ExchangeError::UnsupportedOperation(
                    "Use BatchOrders::cancel_orders_batch for batch cancellation on Binance".to_string()
                ))
            }
            CancelScope::All { .. } | CancelScope::BySymbol { .. } => {
                // Delegate to CancelAll logic but return a placeholder order since Trading::cancel_order
                // returns a single Order. Users should call CancelAll::cancel_all_orders instead.
                Err(ExchangeError::UnsupportedOperation(
                    "Use CancelAll::cancel_all_orders for cancel-all on Binance".to_string()
                ))
            }
            _ => Err(ExchangeError::UnsupportedOperation(
                "This cancel scope is not supported by Binance".to_string()
            )),
        }
    }

    async fn get_order(
        &self,
        symbol: &str,
        order_id: &str,
        account_type: AccountType,
    ) -> ExchangeResult<Order> {
        // Parse symbol string into base/quote for format_symbol
        let parts: Vec<&str> = symbol.split('/').collect();
        let (base, quote) = if parts.len() == 2 {
            (parts[0], parts[1])
        } else {
            (symbol, "")
        };

        let endpoint = match account_type {
            AccountType::Spot | AccountType::Margin => BinanceEndpoint::SpotGetOrder,
            _ => BinanceEndpoint::FuturesGetOrder,
        };

        let mut params = HashMap::new();
        params.insert("symbol".to_string(), if quote.is_empty() {
            symbol.to_string()
        } else {
            format_symbol(base, quote, account_type)
        });
        params.insert("orderId".to_string(), order_id.to_string());

        let response = self.get(endpoint, params, account_type).await?;
        BinanceParser::parse_order(&response, symbol)
    }

    async fn get_open_orders(
        &self,
        symbol: Option<&str>,
        account_type: AccountType,
    ) -> ExchangeResult<Vec<Order>> {
        let endpoint = match account_type {
            AccountType::Spot | AccountType::Margin => BinanceEndpoint::SpotOpenOrders,
            _ => BinanceEndpoint::FuturesOpenOrders,
        };

        let mut params = HashMap::new();
        if let Some(s) = symbol {
            let parts: Vec<&str> = s.split('/').collect();
            let formatted = if parts.len() == 2 {
                format_symbol(parts[0], parts[1], account_type)
            } else {
                s.to_string()
            };
            params.insert("symbol".to_string(), formatted);
        }

        let response = self.get(endpoint, params, account_type).await?;
        BinanceParser::parse_orders(&response)
    }

    async fn get_order_history(
        &self,
        filter: OrderHistoryFilter,
        account_type: AccountType,
    ) -> ExchangeResult<Vec<Order>> {
        let endpoint = match account_type {
            AccountType::Spot | AccountType::Margin => BinanceEndpoint::SpotAllOrders,
            _ => BinanceEndpoint::FuturesAllOrders,
        };

        let mut params = HashMap::new();

        // Symbol is required for Binance allOrders endpoint
        if let Some(ref sym) = filter.symbol {
            params.insert("symbol".to_string(), format_symbol(&sym.base, &sym.quote, account_type));
        } else {
            return Err(ExchangeError::InvalidRequest(
                "Symbol is required for get_order_history on Binance".to_string()
            ));
        }

        if let Some(start) = filter.start_time {
            params.insert("startTime".to_string(), start.to_string());
        }
        if let Some(end) = filter.end_time {
            params.insert("endTime".to_string(), end.to_string());
        }
        if let Some(lim) = filter.limit {
            params.insert("limit".to_string(), lim.min(1000).to_string());
        }

        let response = self.get(endpoint, params, account_type).await?;
        BinanceParser::parse_orders(&response)
    }

    async fn get_user_trades(
        &self,
        filter: UserTradeFilter,
        account_type: AccountType,
    ) -> ExchangeResult<Vec<UserTrade>> {
        // Binance requires a symbol for both myTrades endpoints.
        let symbol_raw = filter.symbol.as_deref()
            .ok_or_else(|| ExchangeError::InvalidRequest(
                "Symbol is required for get_user_trades on Binance".to_string()
            ))?;

        let is_futures = !matches!(account_type, AccountType::Spot | AccountType::Margin);

        let endpoint = if is_futures {
            BinanceEndpoint::FuturesMyTrades
        } else {
            BinanceEndpoint::SpotMyTrades
        };

        let mut params = HashMap::new();
        params.insert("symbol".to_string(), symbol_raw.to_string());

        if let Some(oid) = filter.order_id {
            params.insert("orderId".to_string(), oid);
        }
        if let Some(st) = filter.start_time {
            params.insert("startTime".to_string(), st.to_string());
        }
        if let Some(et) = filter.end_time {
            params.insert("endTime".to_string(), et.to_string());
        }
        if let Some(lim) = filter.limit {
            params.insert("limit".to_string(), lim.min(1000).to_string());
        }

        let response = self.get(endpoint, params, account_type).await?;
        BinanceParser::parse_user_trades(&response, is_futures)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ACCOUNT
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl Account for BinanceConnector {
    async fn get_balance(&self, query: BalanceQuery) -> ExchangeResult<Vec<Balance>> {
        let _asset = query.asset.as_deref();
        let account_type = query.account_type;

        let endpoint = match account_type {
            AccountType::Spot | AccountType::Margin => BinanceEndpoint::SpotAccount,
            _ => BinanceEndpoint::FuturesAccount,
        };

        let mut params = HashMap::new();
        // Optionally exclude zero balances
        if matches!(account_type, AccountType::Spot | AccountType::Margin) {
            params.insert("omitZeroBalances".to_string(), "true".to_string());
        }

        let response = self.get(endpoint, params, account_type).await?;

        match account_type {
            AccountType::Spot | AccountType::Margin => BinanceParser::parse_balances(&response),
            _ => BinanceParser::parse_futures_balances(&response),
        }
    }

    async fn get_account_info(&self, account_type: AccountType) -> ExchangeResult<AccountInfo> {
        let endpoint = match account_type {
            AccountType::Spot | AccountType::Margin => BinanceEndpoint::SpotAccount,
            _ => BinanceEndpoint::FuturesAccount,
        };

        let mut params = HashMap::new();
        if matches!(account_type, AccountType::Spot | AccountType::Margin) {
            params.insert("omitZeroBalances".to_string(), "false".to_string());
        }

        let response = self.get(endpoint, params, account_type).await?;

        let balances = match account_type {
            AccountType::Spot | AccountType::Margin => BinanceParser::parse_balances(&response)?,
            _ => BinanceParser::parse_futures_balances(&response)?,
        };

        // Parse commission rates
        let (maker_commission, taker_commission) = if let Some(rates) = response.get("commissionRates") {
            let maker = rates.get("maker")
                .and_then(|m| m.as_str())
                .and_then(|s| s.parse::<f64>().ok())
                .map(|r| r * 100.0) // Convert to percentage
                .unwrap_or(0.1);
            let taker = rates.get("taker")
                .and_then(|t| t.as_str())
                .and_then(|s| s.parse::<f64>().ok())
                .map(|r| r * 100.0)
                .unwrap_or(0.1);
            (maker, taker)
        } else {
            (0.1, 0.1) // Default
        };

        Ok(AccountInfo {
            account_type,
            can_trade: response.get("canTrade").and_then(|c| c.as_bool()).unwrap_or(true),
            can_withdraw: response.get("canWithdraw").and_then(|c| c.as_bool()).unwrap_or(true),
            can_deposit: response.get("canDeposit").and_then(|c| c.as_bool()).unwrap_or(true),
            maker_commission,
            taker_commission,
            balances,
        })
    }

    async fn get_fees(&self, symbol: Option<&str>) -> ExchangeResult<FeeInfo> {
        // Priority order:
        // 1. GET /sapi/v1/asset/tradeFee  — spot per-symbol rates (best accuracy)
        // 2. GET /fapi/v1/commissionRate  — futures per-symbol rates (when symbol given)
        // 3. GET /api/v3/account          — spot account-wide commissionRates fallback
        // 4. GET /fapi/v2/account         — futures feeTier fallback (tier → estimated rates)

        let formatted_symbol = symbol.map(|s| s.replace('/', "").to_uppercase());

        // Attempt 1: Spot /sapi trade fee (per-symbol or account-wide)
        let mut spot_params = HashMap::new();
        if let Some(ref sym) = formatted_symbol {
            spot_params.insert("symbol".to_string(), sym.clone());
        }
        if let Ok(response) = self.get(BinanceEndpoint::SpotTradeFee, spot_params, AccountType::Spot).await {
            return BinanceParser::parse_fee_info(&response, symbol);
        }

        // Attempt 2: Futures /fapi/v1/commissionRate (requires symbol)
        if let Some(ref sym) = formatted_symbol {
            let mut futures_params = HashMap::new();
            futures_params.insert("symbol".to_string(), sym.clone());
            if let Ok(response) = self.get(
                BinanceEndpoint::FuturesCommissionRate,
                futures_params,
                AccountType::FuturesCross,
            ).await {
                return BinanceParser::parse_fee_info(&response, symbol);
            }
        }

        // Attempt 3: Spot account commissionRates
        let mut account_params = HashMap::new();
        account_params.insert("omitZeroBalances".to_string(), "true".to_string());
        if let Ok(response) = self.get(BinanceEndpoint::SpotAccount, account_params, AccountType::Spot).await {
            return BinanceParser::parse_fee_info(&response, symbol);
        }

        // Attempt 4: Futures account feeTier
        let response = self.get(BinanceEndpoint::FuturesAccount, HashMap::new(), AccountType::FuturesCross).await?;
        BinanceParser::parse_fee_info(&response, symbol)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// POSITIONS
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl Positions for BinanceConnector {
    async fn get_positions(&self, query: PositionQuery) -> ExchangeResult<Vec<Position>> {
        let symbol = query.symbol;
        let account_type = query.account_type;
        match account_type {
            AccountType::Spot | AccountType::Margin => {
                return Err(ExchangeError::UnsupportedOperation(
                    "Positions not supported for Spot/Margin".to_string()
                ));
            }
            _ => {}
        }

        let mut params = HashMap::new();
        if let Some(s) = symbol {
            params.insert("symbol".to_string(), format_symbol(&s.base, &s.quote, account_type));
        }

        let response = self.get(BinanceEndpoint::FuturesPositions, params, account_type).await?;
        BinanceParser::parse_positions(&response)
    }

    async fn get_funding_rate(
        &self,
        symbol: &str,
        account_type: AccountType,
    ) -> ExchangeResult<FundingRate> {
        match account_type {
            AccountType::Spot | AccountType::Margin => {
                return Err(ExchangeError::UnsupportedOperation(
                    "Funding rate not supported for Spot/Margin".to_string()
                ));
            }
            _ => {}
        }

        // Parse symbol string into parts for format_symbol
        let parts: Vec<&str> = symbol.split('/').collect();
        let formatted = if parts.len() == 2 {
            format_symbol(parts[0], parts[1], account_type)
        } else {
            symbol.to_string()
        };

        let mut params = HashMap::new();
        params.insert("symbol".to_string(), formatted);
        params.insert("limit".to_string(), "1".to_string());

        let response = self.get(BinanceEndpoint::FundingRate, params, account_type).await?;
        BinanceParser::parse_funding_rate(&response)
    }

    async fn modify_position(&self, req: PositionModification) -> ExchangeResult<()> {
        match req {
            PositionModification::SetLeverage { ref symbol, leverage, account_type } => {
                match account_type {
                    AccountType::Spot | AccountType::Margin => {
                        return Err(ExchangeError::UnsupportedOperation(
                            "Leverage not supported for Spot/Margin".to_string()
                        ));
                    }
                    _ => {}
                }

                let formatted = format_symbol(&symbol.base, &symbol.quote, account_type);

                let mut params = HashMap::new();
                params.insert("symbol".to_string(), formatted);
                params.insert("leverage".to_string(), leverage.to_string());

                let response = self.post(BinanceEndpoint::FuturesSetLeverage, params, account_type).await?;
                BinanceParser::check_error(&response)?;

                Ok(())
            }

            PositionModification::SetMarginMode { ref symbol, margin_type, account_type } => {
                match account_type {
                    AccountType::Spot | AccountType::Margin => {
                        return Err(ExchangeError::UnsupportedOperation(
                            "SetMarginMode not supported for Spot/Margin".to_string()
                        ));
                    }
                    _ => {}
                }

                let formatted = format_symbol(&symbol.base, &symbol.quote, account_type);
                let margin_type_str = match margin_type {
                    MarginType::Isolated => "ISOLATED",
                    MarginType::Cross => "CROSSED",
                };

                let mut params = HashMap::new();
                params.insert("symbol".to_string(), formatted);
                params.insert("marginType".to_string(), margin_type_str.to_string());

                let response = self.post(BinanceEndpoint::FuturesSetMarginType, params, account_type).await?;
                BinanceParser::check_error(&response)?;
                Ok(())
            }

            PositionModification::AddMargin { ref symbol, amount, account_type } => {
                match account_type {
                    AccountType::Spot | AccountType::Margin => {
                        return Err(ExchangeError::UnsupportedOperation(
                            "AddMargin not supported for Spot/Margin".to_string()
                        ));
                    }
                    _ => {}
                }

                let formatted = format_symbol(&symbol.base, &symbol.quote, account_type);

                let mut params = HashMap::new();
                params.insert("symbol".to_string(), formatted);
                params.insert("amount".to_string(), amount.to_string());
                params.insert("type".to_string(), "1".to_string()); // 1 = add margin

                let response = self.post(BinanceEndpoint::FuturesPositionMargin, params, account_type).await?;
                BinanceParser::check_error(&response)?;
                Ok(())
            }

            PositionModification::RemoveMargin { ref symbol, amount, account_type } => {
                match account_type {
                    AccountType::Spot | AccountType::Margin => {
                        return Err(ExchangeError::UnsupportedOperation(
                            "RemoveMargin not supported for Spot/Margin".to_string()
                        ));
                    }
                    _ => {}
                }

                let formatted = format_symbol(&symbol.base, &symbol.quote, account_type);

                let mut params = HashMap::new();
                params.insert("symbol".to_string(), formatted);
                params.insert("amount".to_string(), amount.to_string());
                params.insert("type".to_string(), "2".to_string()); // 2 = remove margin

                let response = self.post(BinanceEndpoint::FuturesPositionMargin, params, account_type).await?;
                BinanceParser::check_error(&response)?;
                Ok(())
            }

            PositionModification::ClosePosition { ref symbol, account_type } => {
                match account_type {
                    AccountType::Spot | AccountType::Margin => {
                        return Err(ExchangeError::UnsupportedOperation(
                            "ClosePosition not supported for Spot/Margin".to_string()
                        ));
                    }
                    _ => {}
                }

                // Get the open position to find its quantity
                let positions = self.get_positions(PositionQuery {
                    symbol: Some(symbol.clone()),
                    account_type,
                }).await?;

                let position = positions.into_iter().next()
                    .ok_or_else(|| ExchangeError::InvalidRequest(
                        format!("No open position found for {}", symbol)
                    ))?;

                // Place a reduce-only market order in the opposite direction
                let close_side = if position.side == crate::core::PositionSide::Long {
                    OrderSide::Sell
                } else {
                    OrderSide::Buy
                };

                let formatted = format_symbol(&symbol.base, &symbol.quote, account_type);

                let mut params = HashMap::new();
                params.insert("symbol".to_string(), formatted);
                params.insert("side".to_string(), close_side.as_str().to_string());
                params.insert("type".to_string(), "MARKET".to_string());
                params.insert("quantity".to_string(), position.quantity.to_string());
                params.insert("reduceOnly".to_string(), "true".to_string());

                let response = self.post(BinanceEndpoint::FuturesCreateOrder, params, account_type).await?;
                BinanceParser::check_error(&response)?;
                Ok(())
            }

            PositionModification::SetTpSl { .. } => {
                Err(ExchangeError::UnsupportedOperation(
                    "SetTpSl is not a single native endpoint on Binance. Place separate TP/SL orders.".to_string()
                ))
            }
            _ => Err(ExchangeError::UnsupportedOperation(
                "This position modification is not supported by Binance".to_string()
            )),
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// CANCEL ALL
// ═══════════════════════════════════════════════════════════════════════════════

/// Cancel all open orders (optionally filtered to a single symbol).
///
/// - Spot: `DELETE /api/v3/openOrders` — requires `symbol` param
/// - Futures: `DELETE /fapi/v1/allOpenOrders` — requires `symbol` param
///
/// Note: Binance requires `symbol` on both endpoints; passing `All` with
/// `symbol = None` is not supported and returns `UnsupportedOperation`.
#[async_trait]
impl CancelAll for BinanceConnector {
    async fn cancel_all_orders(
        &self,
        scope: CancelScope,
        account_type: AccountType,
    ) -> ExchangeResult<CancelAllResponse> {
        let symbol = match &scope {
            CancelScope::All { symbol } => symbol.clone(),
            CancelScope::BySymbol { symbol } => Some(symbol.clone()),
            _ => {
                return Err(ExchangeError::InvalidRequest(
                    "cancel_all_orders only accepts All or BySymbol scope".to_string()
                ));
            }
        };

        let sym = symbol.ok_or_else(|| ExchangeError::InvalidRequest(
            "Binance cancel-all requires a symbol. Pass CancelScope::BySymbol or CancelScope::All with Some(symbol).".to_string()
        ))?;

        let endpoint = match account_type {
            AccountType::Spot | AccountType::Margin => BinanceEndpoint::SpotCancelAllOrders,
            _ => BinanceEndpoint::FuturesCancelAllOrders,
        };

        let mut params = HashMap::new();
        params.insert("symbol".to_string(), format_symbol(&sym.base, &sym.quote, account_type));

        let response = self.delete(endpoint, params, account_type).await?;
        BinanceParser::parse_cancel_all_response(&response)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// AMEND ORDER
// ═══════════════════════════════════════════════════════════════════════════════

/// Modify a live futures order in-place.
///
/// Binance Futures: `PUT /fapi/v1/order`
/// Spot does NOT support amend — this returns `UnsupportedOperation` for Spot/Margin.
#[async_trait]
impl AmendOrder for BinanceConnector {
    async fn amend_order(&self, req: AmendRequest) -> ExchangeResult<Order> {
        match req.account_type {
            AccountType::Spot | AccountType::Margin => {
                return Err(ExchangeError::UnsupportedOperation(
                    "Amend order not supported on Spot/Margin (Binance Futures only)".to_string()
                ));
            }
            _ => {}
        }

        // At least one field must be changed
        if req.fields.price.is_none() && req.fields.quantity.is_none() {
            return Err(ExchangeError::InvalidRequest(
                "At least one of price or quantity must be provided for amend".to_string()
            ));
        }

        let account_type = req.account_type;
        let amend_symbol_str = format_symbol(&req.symbol.base, &req.symbol.quote, account_type);
        let mut params = HashMap::new();
        params.insert("symbol".to_string(), amend_symbol_str.clone());
        params.insert("orderId".to_string(), req.order_id.clone());

        if let Some(price) = req.fields.price {
            params.insert("price".to_string(), self.precision.price(&amend_symbol_str, price));
        }
        if let Some(quantity) = req.fields.quantity {
            params.insert("quantity".to_string(), self.precision.qty(&amend_symbol_str, quantity));
        }
        if let Some(stop_price) = req.fields.trigger_price {
            params.insert("stopPrice".to_string(), self.precision.price(&amend_symbol_str, stop_price));
        }

        let response = self.put(BinanceEndpoint::FuturesAmendOrder, params, account_type).await?;
        BinanceParser::parse_order(&response, &req.symbol.to_string())
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// BATCH ORDERS
// ═══════════════════════════════════════════════════════════════════════════════

/// Native batch order placement and cancellation.
///
/// - Futures: `POST /fapi/v1/batchOrders` — max 5 orders per batch
/// - Spot: no native batch endpoint → returns `UnsupportedOperation`
#[async_trait]
impl BatchOrders for BinanceConnector {
    async fn place_orders_batch(
        &self,
        orders: Vec<OrderRequest>,
    ) -> ExchangeResult<Vec<OrderResult>> {
        if orders.is_empty() {
            return Ok(vec![]);
        }

        // Detect account type from first order — all orders in batch must be same type
        let account_type = orders[0].account_type;

        match account_type {
            AccountType::Spot | AccountType::Margin => {
                return Err(ExchangeError::UnsupportedOperation(
                    "Batch orders not supported on Spot/Margin (Binance Futures only)".to_string()
                ));
            }
            _ => {}
        }

        if orders.len() > self.max_batch_place_size() {
            return Err(ExchangeError::InvalidRequest(
                format!("Batch size {} exceeds Binance limit of {}", orders.len(), self.max_batch_place_size())
            ));
        }

        // Build each order as a JSON object for the batchOrders array
        let batch_orders_json: Vec<serde_json::Value> = orders.iter().map(|req| {
            let mut obj = serde_json::Map::new();
            obj.insert("symbol".to_string(), json!(format_symbol(&req.symbol.base, &req.symbol.quote, account_type)));
            obj.insert("side".to_string(), json!(req.side.as_str()));

            let batch_sym_str = format_symbol(&req.symbol.base, &req.symbol.quote, account_type);
            match &req.order_type {
                OrderType::Market => {
                    obj.insert("type".to_string(), json!("MARKET"));
                    obj.insert("quantity".to_string(), json!(self.precision.qty(&batch_sym_str, req.quantity)));
                }
                OrderType::Limit { price } => {
                    obj.insert("type".to_string(), json!("LIMIT"));
                    obj.insert("quantity".to_string(), json!(self.precision.qty(&batch_sym_str, req.quantity)));
                    obj.insert("price".to_string(), json!(self.precision.price(&batch_sym_str, *price)));
                    obj.insert("timeInForce".to_string(), json!("GTC"));
                }
                _ => {
                    // For other types, encode as MARKET (best-effort fallback)
                    obj.insert("type".to_string(), json!("MARKET"));
                    obj.insert("quantity".to_string(), json!(self.precision.qty(&batch_sym_str, req.quantity)));
                }
            }

            if req.reduce_only {
                obj.insert("reduceOnly".to_string(), json!("true"));
            }
            if let Some(ref cid) = req.client_order_id {
                obj.insert("newClientOrderId".to_string(), json!(cid));
            }

            serde_json::Value::Object(obj)
        }).collect();

        let batch_json_str = serde_json::to_string(&batch_orders_json)
            .map_err(|e| ExchangeError::Parse(format!("Failed to serialize batch orders: {}", e)))?;

        let mut params = HashMap::new();
        params.insert("batchOrders".to_string(), batch_json_str);

        let response = self.post(BinanceEndpoint::FuturesBatchOrders, params, account_type).await?;
        BinanceParser::parse_batch_orders_response(&response)
    }

    async fn cancel_orders_batch(
        &self,
        order_ids: Vec<String>,
        symbol: Option<&str>,
        account_type: AccountType,
    ) -> ExchangeResult<Vec<OrderResult>> {
        match account_type {
            AccountType::Spot | AccountType::Margin => {
                return Err(ExchangeError::UnsupportedOperation(
                    "Batch cancel not supported on Spot/Margin (Binance Futures only)".to_string()
                ));
            }
            _ => {}
        }

        let sym = symbol.ok_or_else(|| ExchangeError::InvalidRequest(
            "Symbol is required for batch cancel on Binance".to_string()
        ))?;

        // Futures batch cancel: DELETE /fapi/v1/batchOrders with orderIdList param
        let order_ids_json = serde_json::to_string(&order_ids)
            .map_err(|e| ExchangeError::Parse(format!("Failed to serialize order IDs: {}", e)))?;

        let mut params = HashMap::new();
        // Symbol for batch cancel needs to be formatted — we have it as a raw string
        params.insert("symbol".to_string(), sym.replace('/', "").to_uppercase());
        params.insert("orderIdList".to_string(), order_ids_json);

        let response = self.delete(BinanceEndpoint::FuturesBatchOrders, params, account_type).await?;
        BinanceParser::parse_batch_orders_response(&response)
    }

    fn max_batch_place_size(&self) -> usize {
        5 // Binance Futures limit
    }

    fn max_batch_cancel_size(&self) -> usize {
        10 // Binance Futures limit
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// BATCH AMEND
// ═══════════════════════════════════════════════════════════════════════════════

impl BinanceConnector {
    /// Batch amend multiple futures orders via `PATCH /fapi/v1/batchOrders`.
    ///
    /// Each entry in `amends` is a JSON object with required fields:
    /// `symbol`, `orderId` (or `origClientOrderId`), plus at least one of:
    /// `price`, `quantity`, `stopPrice`.
    ///
    /// Max 5 orders per batch (Binance Futures limit).
    ///
    /// Returns the raw JSON response from Binance.
    pub async fn batch_amend_orders(
        &self,
        amends: Vec<serde_json::Value>,
    ) -> ExchangeResult<Value> {
        if amends.is_empty() {
            return Ok(serde_json::Value::Array(vec![]));
        }
        if amends.len() > 5 {
            return Err(ExchangeError::InvalidRequest(
                format!("Batch amend size {} exceeds Binance Futures limit of 5", amends.len())
            ));
        }

        let batch_json_str = serde_json::to_string(&amends)
            .map_err(|e| ExchangeError::Parse(format!("Failed to serialize batch amend orders: {}", e)))?;

        let mut params = HashMap::new();
        params.insert("batchOrders".to_string(), batch_json_str);

        self.patch(BinanceEndpoint::FuturesBatchAmend, params, AccountType::FuturesCross).await
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ACCOUNT TRANSFERS
// ═══════════════════════════════════════════════════════════════════════════════

/// Map our AccountType pair to Binance universal transfer type string.
///
/// Binance transfer types (SAPI v1): MAIN_UMFUTURE, UMFUTURE_MAIN, MAIN_MARGIN,
/// MARGIN_MAIN, UMFUTURE_MARGIN, MARGIN_UMFUTURE, etc.
fn map_transfer_type(from: AccountType, to: AccountType) -> ExchangeResult<&'static str> {
    match (from, to) {
        (AccountType::Spot, AccountType::FuturesCross) => Ok("MAIN_UMFUTURE"),
        (AccountType::FuturesCross, AccountType::Spot) => Ok("UMFUTURE_MAIN"),
        (AccountType::Spot, AccountType::FuturesIsolated) => Ok("MAIN_CMFUTURE"),
        (AccountType::FuturesIsolated, AccountType::Spot) => Ok("CMFUTURE_MAIN"),
        (AccountType::Spot, AccountType::Margin) => Ok("MAIN_MARGIN"),
        (AccountType::Margin, AccountType::Spot) => Ok("MARGIN_MAIN"),
        (AccountType::FuturesCross, AccountType::Margin) => Ok("UMFUTURE_MARGIN"),
        (AccountType::Margin, AccountType::FuturesCross) => Ok("MARGIN_UMFUTURE"),
        (AccountType::FuturesIsolated, AccountType::Margin) => Ok("CMFUTURE_MARGIN"),
        (AccountType::Margin, AccountType::FuturesIsolated) => Ok("MARGIN_CMFUTURE"),
        _ => Err(ExchangeError::InvalidRequest(format!(
            "Unsupported transfer direction: {:?}{:?}",
            from, to
        ))),
    }
}

#[async_trait]
impl AccountTransfers for BinanceConnector {
    async fn transfer(&self, req: TransferRequest) -> ExchangeResult<TransferResponse> {
        let transfer_type = map_transfer_type(req.from_account, req.to_account)?;

        let mut params = HashMap::new();
        params.insert("type".to_string(), transfer_type.to_string());
        params.insert("asset".to_string(), req.asset.clone());
        params.insert("amount".to_string(), req.amount.to_string());

        let response = self.post(BinanceEndpoint::AssetTransfer, params, AccountType::Spot).await?;
        BinanceParser::parse_transfer_response(&response, &req.asset, req.amount)
    }

    async fn get_transfer_history(
        &self,
        filter: TransferHistoryFilter,
    ) -> ExchangeResult<Vec<TransferResponse>> {
        // Binance requires a `type` param for history; we default to MAIN_UMFUTURE
        // as the most common query. Callers who need a specific type should filter
        // the result or extend the filter type in the future.
        let mut params: HashMap<String, String> = HashMap::new();
        params.insert("type".to_string(), "MAIN_UMFUTURE".to_string());

        if let Some(start) = filter.start_time {
            params.insert("startTime".to_string(), start.to_string());
        }
        if let Some(end) = filter.end_time {
            params.insert("endTime".to_string(), end.to_string());
        }
        if let Some(limit) = filter.limit {
            params.insert("size".to_string(), limit.to_string());
        }

        let response = self.get(BinanceEndpoint::AssetTransferHistory, params, AccountType::Spot).await?;
        BinanceParser::parse_transfer_history(&response)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// CUSTODIAL FUNDS
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl CustodialFunds for BinanceConnector {
    async fn get_deposit_address(
        &self,
        asset: &str,
        network: Option<&str>,
    ) -> ExchangeResult<DepositAddress> {
        let mut params: HashMap<String, String> = HashMap::new();
        params.insert("coin".to_string(), asset.to_uppercase());

        if let Some(net) = network {
            params.insert("network".to_string(), net.to_string());
        }

        let response = self.get(BinanceEndpoint::DepositAddress, params, AccountType::Spot).await?;
        BinanceParser::parse_deposit_address(&response)
    }

    async fn withdraw(&self, req: WithdrawRequest) -> ExchangeResult<WithdrawResponse> {
        let mut params: HashMap<String, String> = HashMap::new();
        params.insert("coin".to_string(), req.asset.to_uppercase());
        params.insert("address".to_string(), req.address.clone());
        params.insert("amount".to_string(), req.amount.to_string());

        if let Some(net) = &req.network {
            params.insert("network".to_string(), net.clone());
        }
        if let Some(tag) = &req.tag {
            params.insert("addressTag".to_string(), tag.clone());
        }

        let response = self.post(BinanceEndpoint::Withdraw, params, AccountType::Spot).await?;
        BinanceParser::parse_withdraw_response(&response)
    }

    async fn get_funds_history(
        &self,
        filter: FundsHistoryFilter,
    ) -> ExchangeResult<Vec<FundsRecord>> {
        match filter.record_type {
            FundsRecordType::Deposit => {
                let mut params: HashMap<String, String> = HashMap::new();
                if let Some(asset) = &filter.asset {
                    params.insert("coin".to_string(), asset.to_uppercase());
                }
                if let Some(start) = filter.start_time {
                    params.insert("startTime".to_string(), start.to_string());
                }
                if let Some(end) = filter.end_time {
                    params.insert("endTime".to_string(), end.to_string());
                }
                if let Some(limit) = filter.limit {
                    params.insert("limit".to_string(), limit.to_string());
                }
                let response = self.get(BinanceEndpoint::DepositHistory, params, AccountType::Spot).await?;
                BinanceParser::parse_deposit_history(&response)
            }
            FundsRecordType::Withdrawal => {
                let mut params: HashMap<String, String> = HashMap::new();
                if let Some(asset) = &filter.asset {
                    params.insert("coin".to_string(), asset.to_uppercase());
                }
                if let Some(start) = filter.start_time {
                    params.insert("startTime".to_string(), start.to_string());
                }
                if let Some(end) = filter.end_time {
                    params.insert("endTime".to_string(), end.to_string());
                }
                if let Some(limit) = filter.limit {
                    params.insert("limit".to_string(), limit.to_string());
                }
                let response = self.get(BinanceEndpoint::WithdrawHistory, params, AccountType::Spot).await?;
                BinanceParser::parse_withdrawal_history(&response)
            }
            FundsRecordType::Both => {
                // Binance has separate endpoints — fetch both and merge
                let deposit_filter = FundsHistoryFilter {
                    record_type: FundsRecordType::Deposit,
                    asset: filter.asset.clone(),
                    start_time: filter.start_time,
                    end_time: filter.end_time,
                    limit: filter.limit,
                };
                let withdrawal_filter = FundsHistoryFilter {
                    record_type: FundsRecordType::Withdrawal,
                    asset: filter.asset.clone(),
                    start_time: filter.start_time,
                    end_time: filter.end_time,
                    limit: filter.limit,
                };
                let mut deposits = self.get_funds_history(deposit_filter).await?;
                let withdrawals = self.get_funds_history(withdrawal_filter).await?;
                deposits.extend(withdrawals);
                Ok(deposits)
            }
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// SUB-ACCOUNTS
// ═══════════════════════════════════════════════════════════════════════════════

#[async_trait]
impl SubAccounts for BinanceConnector {
    async fn sub_account_operation(
        &self,
        op: SubAccountOperation,
    ) -> ExchangeResult<SubAccountResult> {
        match op {
            SubAccountOperation::Create { label } => {
                let mut params = HashMap::new();
                params.insert("subAccountString".to_string(), label);

                let response = self.post(BinanceEndpoint::SubAccountCreate, params, AccountType::Spot).await?;
                BinanceParser::parse_sub_account_create(&response)
            }

            SubAccountOperation::List => {
                let params = HashMap::new();
                let response = self.get(BinanceEndpoint::SubAccountList, params, AccountType::Spot).await?;
                BinanceParser::parse_sub_account_list(&response)
            }

            SubAccountOperation::Transfer { sub_account_id, asset, amount, to_sub } => {
                // universalTransfer: fromEmail/toEmail + fromAccountType/toAccountType
                // We treat sub_account_id as the sub-account email.
                // Master account email is not known here, so we use a placeholder approach:
                // if to_sub = true: master(SPOT) → sub(SPOT)
                // if to_sub = false: sub(SPOT) → master(SPOT)
                let mut params = HashMap::new();

                if to_sub {
                    // fromEmail = master (we pass empty, Binance treats missing as master)
                    params.insert("toEmail".to_string(), sub_account_id.clone());
                    params.insert("fromAccountType".to_string(), "SPOT".to_string());
                    params.insert("toAccountType".to_string(), "SPOT".to_string());
                } else {
                    params.insert("fromEmail".to_string(), sub_account_id.clone());
                    params.insert("fromAccountType".to_string(), "SPOT".to_string());
                    params.insert("toAccountType".to_string(), "SPOT".to_string());
                }

                params.insert("asset".to_string(), asset);
                params.insert("amount".to_string(), amount.to_string());

                let response = self.post(BinanceEndpoint::SubAccountTransfer, params, AccountType::Spot).await?;
                BinanceParser::parse_sub_account_transfer(&response)
            }

            SubAccountOperation::GetBalance { sub_account_id } => {
                let mut params = HashMap::new();
                params.insert("email".to_string(), sub_account_id);

                let response = self.get(BinanceEndpoint::SubAccountAssets, params, AccountType::Spot).await?;
                BinanceParser::parse_sub_account_assets(&response)
            }
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// FUNDING HISTORY
// ═══════════════════════════════════════════════════════════════════════════════

/// Funding payment history via `GET /fapi/v1/income?incomeType=FUNDING_FEE`
///
/// Only available for futures account types. Spot returns `UnsupportedOperation`.
#[async_trait]
impl FundingHistory for BinanceConnector {
    async fn get_funding_payments(
        &self,
        filter: FundingFilter,
        account_type: AccountType,
    ) -> ExchangeResult<Vec<FundingPayment>> {
        match account_type {
            AccountType::FuturesCross | AccountType::FuturesIsolated => {}
            _ => {
                return Err(ExchangeError::UnsupportedOperation(
                    "Binance funding payments are futures-only".to_string(),
                ))
            }
        }

        let mut params: HashMap<String, String> = HashMap::new();
        params.insert("incomeType".to_string(), "FUNDING_FEE".to_string());

        if let Some(symbol) = &filter.symbol {
            params.insert("symbol".to_string(), symbol.to_uppercase());
        }
        if let Some(start) = filter.start_time {
            params.insert("startTime".to_string(), start.to_string());
        }
        if let Some(end) = filter.end_time {
            params.insert("endTime".to_string(), end.to_string());
        }
        let limit = filter.limit.unwrap_or(500).min(1000);
        params.insert("limit".to_string(), limit.to_string());

        let response = self.get(BinanceEndpoint::FuturesIncomeHistory, params, account_type).await?;
        BinanceParser::parse_funding_payments(&response)
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// ACCOUNT LEDGER
// ═══════════════════════════════════════════════════════════════════════════════

/// Full account ledger via `GET /fapi/v1/income` (all income types).
///
/// Only available for futures account types.
#[async_trait]
impl AccountLedger for BinanceConnector {
    async fn get_ledger(
        &self,
        filter: LedgerFilter,
        account_type: AccountType,
    ) -> ExchangeResult<Vec<LedgerEntry>> {
        match account_type {
            AccountType::FuturesCross | AccountType::FuturesIsolated => {}
            _ => {
                return Err(ExchangeError::UnsupportedOperation(
                    "Binance income ledger is futures-only".to_string(),
                ))
            }
        }

        let mut params: HashMap<String, String> = HashMap::new();

        if let Some(start) = filter.start_time {
            params.insert("startTime".to_string(), start.to_string());
        }
        if let Some(end) = filter.end_time {
            params.insert("endTime".to_string(), end.to_string());
        }
        let limit = filter.limit.unwrap_or(500).min(1000);
        params.insert("limit".to_string(), limit.to_string());

        let response = self.get(BinanceEndpoint::FuturesIncomeHistory, params, account_type).await?;
        let mut entries = BinanceParser::parse_ledger(&response)?;

        // Apply client-side filters that Binance does not natively support
        if let Some(ref type_filter) = filter.entry_type {
            entries.retain(|e| &e.entry_type == type_filter);
        }
        if let Some(ref asset_filter) = filter.asset {
            let asset_upper = asset_filter.to_uppercase();
            entries.retain(|e| e.asset.to_uppercase() == asset_upper);
        }

        Ok(entries)
    }
}