nautilus-binance 0.55.0

Binance exchange integration adapter for the Nautilus trading engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
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
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Binance Spot HTTP client with SBE encoding.
//!
//! This client communicates with Binance Spot REST API using SBE (Simple Binary
//! Encoding) for all request/response payloads, providing microsecond timestamp
//! precision and reduced latency compared to JSON.
//!
//! ## Architecture
//!
//! Two-layer client pattern:
//! - [`BinanceRawSpotHttpClient`]: Low-level API methods returning raw bytes.
//! - [`BinanceSpotHttpClient`]: High-level methods with SBE decoding.
//!
//! ## SBE Headers
//!
//! All requests include:
//! - `Accept: application/sbe`
//! - `X-MBX-SBE: 3:3` (schema ID:version)

use std::{collections::HashMap, fmt::Debug, num::NonZeroU32, sync::Arc};

use chrono::{DateTime, Utc};
use dashmap::DashMap;
use nautilus_core::{
    consts::NAUTILUS_USER_AGENT, datetime::SECONDS_IN_DAY, hex, nanos::UnixNanos, time::AtomicTime,
};
use nautilus_model::{
    data::{Bar, BarType, TradeTick},
    enums::{AggregationSource, BarAggregation, OrderSide, OrderType, TimeInForce},
    events::AccountState,
    identifiers::{AccountId, ClientOrderId, InstrumentId, VenueOrderId},
    instruments::{Instrument, any::InstrumentAny},
    reports::{FillReport, OrderStatusReport},
    types::{Price, Quantity},
};
use nautilus_network::{
    http::{HttpClient, HttpResponse, Method},
    ratelimiter::quota::Quota,
};
use serde::Serialize;
use ustr::Ustr;

use super::{
    error::{BinanceSpotHttpError, BinanceSpotHttpResult},
    models::{
        AvgPrice, BatchCancelResult, BatchOrderResult, BinanceAccountInfo, BinanceAccountTrade,
        BinanceCancelOrderResponse, BinanceDepth, BinanceKlines, BinanceNewOrderResponse,
        BinanceOrderResponse, BinanceTrades, BookTicker, ListenKeyResponse, Ticker24hr,
        TickerPrice, TradeFee,
    },
    parse,
    query::{
        AccountInfoParams, AccountTradesParams, AllOrdersParams, AvgPriceParams, BatchCancelItem,
        BatchOrderItem, CancelOpenOrdersParams, CancelOrderParams, CancelReplaceOrderParams,
        DepthParams, KlinesParams, ListenKeyParams, NewOrderParams, OpenOrdersParams,
        QueryOrderParams, TickerParams, TradeFeeParams, TradesParams,
    },
};
use crate::{
    common::{
        consts::{
            BINANCE_API_KEY_HEADER, BINANCE_NAUTILUS_SPOT_BROKER_ID, BINANCE_SPOT_RATE_LIMITS,
            BinanceRateLimitQuota,
        },
        credential::SigningCredential,
        encoder::{decode_broker_id, encode_broker_id},
        enums::{
            BinanceEnvironment, BinanceProductType, BinanceRateLimitInterval, BinanceRateLimitType,
            BinanceSide, BinanceTimeInForce,
        },
        models::BinanceErrorResponse,
        parse::{
            get_currency, parse_fill_report_sbe, parse_klines_to_bars,
            parse_new_order_response_sbe, parse_order_status_report_sbe, parse_spot_instrument_sbe,
            parse_spot_trades_sbe,
        },
        urls::get_http_base_url,
    },
    spot::{
        enums::{
            BinanceCancelReplaceMode, BinanceOrderResponseType, BinanceSpotOrderType,
            order_type_to_binance_spot, time_in_force_to_binance_spot,
        },
        sbe::spot::{
            ReadBuf, SBE_SCHEMA_ID, SBE_SCHEMA_VERSION,
            error_response_codec::{self, ErrorResponseDecoder},
            message_header_codec::MessageHeaderDecoder,
        },
    },
};

/// SBE schema header value for Spot API.
pub const SBE_SCHEMA_HEADER: &str = "3:3";

use crate::common::consts::BINANCE_SPOT_API_PATH as SPOT_API_PATH;

/// Global rate limit key.
const BINANCE_GLOBAL_RATE_KEY: &str = "binance:spot:global";

/// Orders rate limit key prefix.
const BINANCE_ORDERS_RATE_KEY: &str = "binance:spot:orders";

struct RateLimitConfig {
    default_quota: Option<Quota>,
    keyed_quotas: Vec<(String, Quota)>,
    order_keys: Vec<String>,
}

/// Low-level HTTP client for Binance Spot REST API with SBE encoding.
///
/// Handles:
/// - Base URL resolution by environment.
/// - Optional HMAC SHA256 signing for private endpoints.
/// - Rate limiting using Spot API quotas.
/// - SBE decoding to Binance-specific response types.
///
/// Methods are named to match Binance API endpoints and return
/// venue-specific types (decoded from SBE).
#[derive(Debug, Clone)]
pub struct BinanceRawSpotHttpClient {
    client: HttpClient,
    base_url: String,
    credential: Option<SigningCredential>,
    recv_window: Option<u64>,
    order_rate_keys: Vec<String>,
}

impl BinanceRawSpotHttpClient {
    /// Creates a new Binance Spot raw HTTP client.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying [`HttpClient`] fails to build.
    pub fn new(
        environment: BinanceEnvironment,
        api_key: Option<String>,
        api_secret: Option<String>,
        base_url_override: Option<String>,
        recv_window: Option<u64>,
        timeout_secs: Option<u64>,
        proxy_url: Option<String>,
    ) -> BinanceSpotHttpResult<Self> {
        let RateLimitConfig {
            default_quota,
            keyed_quotas,
            order_keys,
        } = Self::rate_limit_config();

        let credential = match (api_key, api_secret) {
            (Some(key), Some(secret)) => Some(SigningCredential::new(key, secret)),
            (None, None) => None,
            _ => return Err(BinanceSpotHttpError::MissingCredentials),
        };

        let base_url = base_url_override.unwrap_or_else(|| {
            get_http_base_url(BinanceProductType::Spot, environment).to_string()
        });

        let headers = Self::default_headers(&credential);

        let client = HttpClient::new(
            headers,
            vec![BINANCE_API_KEY_HEADER.to_string()],
            keyed_quotas,
            default_quota,
            timeout_secs,
            proxy_url,
        )?;

        Ok(Self {
            client,
            base_url,
            credential,
            recv_window,
            order_rate_keys: order_keys,
        })
    }

    /// Returns the SBE schema ID.
    #[must_use]
    pub const fn schema_id() -> u16 {
        SBE_SCHEMA_ID
    }

    /// Returns the SBE schema version.
    #[must_use]
    pub const fn schema_version() -> u16 {
        SBE_SCHEMA_VERSION
    }

    /// Performs a GET request and returns raw response bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn get<P>(&self, path: &str, params: Option<&P>) -> BinanceSpotHttpResult<Vec<u8>>
    where
        P: Serialize + ?Sized,
    {
        self.request(Method::GET, path, params, false, false).await
    }

    /// Performs a signed GET request and returns raw response bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if credentials are missing or the request fails.
    pub async fn get_signed<P>(
        &self,
        path: &str,
        params: Option<&P>,
    ) -> BinanceSpotHttpResult<Vec<u8>>
    where
        P: Serialize + ?Sized,
    {
        self.request(Method::GET, path, params, true, false).await
    }

    /// Performs a signed POST request and returns raw response bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if credentials are missing or the request fails.
    pub async fn post_signed<P>(
        &self,
        path: &str,
        params: Option<&P>,
    ) -> BinanceSpotHttpResult<Vec<u8>>
    where
        P: Serialize + ?Sized,
    {
        self.request(Method::POST, path, params, true, true).await
    }

    /// Performs a signed DELETE request and returns raw response bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if credentials are missing or the request fails.
    pub async fn delete_signed<P>(
        &self,
        path: &str,
        params: Option<&P>,
    ) -> BinanceSpotHttpResult<Vec<u8>>
    where
        P: Serialize + ?Sized,
    {
        self.request(Method::DELETE, path, params, true, true).await
    }

    async fn request<P>(
        &self,
        method: Method,
        path: &str,
        params: Option<&P>,
        signed: bool,
        use_order_quota: bool,
    ) -> BinanceSpotHttpResult<Vec<u8>>
    where
        P: Serialize + ?Sized,
    {
        let mut query = params
            .map(serde_urlencoded::to_string)
            .transpose()
            .map_err(|e| BinanceSpotHttpError::ValidationError(e.to_string()))?
            .unwrap_or_default();

        let mut headers = HashMap::new();

        if signed {
            let cred = self
                .credential
                .as_ref()
                .ok_or(BinanceSpotHttpError::MissingCredentials)?;

            if !query.is_empty() {
                query.push('&');
            }

            let timestamp = Utc::now().timestamp_millis();
            query.push_str(&format!("timestamp={timestamp}"));

            if let Some(recv_window) = self.recv_window {
                query.push_str(&format!("&recvWindow={recv_window}"));
            }

            let signature = cred.sign(&query);
            query.push_str(&format!("&signature={signature}"));
            headers.insert(
                BINANCE_API_KEY_HEADER.to_string(),
                cred.api_key().to_string(),
            );
        }

        let url = self.build_url(path, &query);
        let keys = self.rate_limit_keys(use_order_quota);

        let response = self
            .client
            .request(
                method,
                url,
                None::<&HashMap<String, Vec<String>>>,
                Some(headers),
                None,
                None,
                Some(keys),
            )
            .await?;

        if !response.status.is_success() {
            return self.parse_error_response(&response);
        }

        Ok(response.body.to_vec())
    }

    fn build_url(&self, path: &str, query: &str) -> String {
        let normalized_path = if path.starts_with('/') {
            path.to_string()
        } else {
            format!("/{path}")
        };

        let mut url = format!("{}{}{}", self.base_url, SPOT_API_PATH, normalized_path);

        if !query.is_empty() {
            url.push('?');
            url.push_str(query);
        }
        url
    }

    fn rate_limit_keys(&self, use_orders: bool) -> Vec<String> {
        if use_orders {
            let mut keys = Vec::with_capacity(1 + self.order_rate_keys.len());
            keys.push(BINANCE_GLOBAL_RATE_KEY.to_string());
            keys.extend(self.order_rate_keys.iter().cloned());
            keys
        } else {
            vec![BINANCE_GLOBAL_RATE_KEY.to_string()]
        }
    }

    fn parse_error_response<T>(&self, response: &HttpResponse) -> BinanceSpotHttpResult<T> {
        let status = response.status.as_u16();
        let body = &response.body;

        // Binance may return JSON errors even when SBE was requested
        if let Ok(body_str) = std::str::from_utf8(body)
            && let Ok(err) = serde_json::from_str::<BinanceErrorResponse>(body_str)
        {
            return Err(BinanceSpotHttpError::BinanceError {
                code: err.code,
                message: err.msg,
            });
        }

        // Try to decode SBE error response
        if let Some((code, message)) = Self::try_decode_sbe_error(body) {
            return Err(BinanceSpotHttpError::BinanceError {
                code: code.into(),
                message,
            });
        }

        Err(BinanceSpotHttpError::UnexpectedStatus {
            status,
            body: hex::encode(body),
        })
    }

    /// Attempts to decode an SBE error response.
    ///
    /// Returns Some((code, message)) if successfully decoded, None otherwise.
    fn try_decode_sbe_error(body: &[u8]) -> Option<(i16, String)> {
        const HEADER_LEN: usize = 8;
        if body.len() < HEADER_LEN + error_response_codec::SBE_BLOCK_LENGTH as usize {
            return None;
        }

        let buf = ReadBuf::new(body);

        // Decode message header
        let header = MessageHeaderDecoder::default().wrap(buf, 0);
        if header.template_id() != error_response_codec::SBE_TEMPLATE_ID {
            return None;
        }

        // Decode error response
        let mut decoder = ErrorResponseDecoder::default().header(header, 0);
        let code = decoder.code();

        // Decode the message string (VAR_DATA with 2-byte length prefix)
        let msg_coords = decoder.msg_decoder();
        let msg_bytes = decoder.msg_slice(msg_coords);
        let message = String::from_utf8_lossy(msg_bytes).into_owned();

        Some((code, message))
    }

    fn default_headers(credential: &Option<SigningCredential>) -> HashMap<String, String> {
        let mut headers = HashMap::new();
        headers.insert("User-Agent".to_string(), NAUTILUS_USER_AGENT.to_string());
        headers.insert("Accept".to_string(), "application/sbe".to_string());
        headers.insert("X-MBX-SBE".to_string(), SBE_SCHEMA_HEADER.to_string());

        if let Some(cred) = credential {
            headers.insert(
                BINANCE_API_KEY_HEADER.to_string(),
                cred.api_key().to_string(),
            );
        }
        headers
    }

    fn rate_limit_config() -> RateLimitConfig {
        let quotas = BINANCE_SPOT_RATE_LIMITS;
        let mut keyed = Vec::new();
        let mut order_keys = Vec::new();
        let mut default = None;

        for quota in quotas {
            if let Some(q) = Self::quota_from(quota) {
                match quota.rate_limit_type {
                    BinanceRateLimitType::RequestWeight if default.is_none() => {
                        default = Some(q);
                    }
                    BinanceRateLimitType::Orders => {
                        let key = format!("{}:{:?}", BINANCE_ORDERS_RATE_KEY, quota.interval);
                        order_keys.push(key.clone());
                        keyed.push((key, q));
                    }
                    _ => {}
                }
            }
        }

        let default_quota = default.unwrap_or_else(|| {
            Quota::per_second(NonZeroU32::new(10).expect("non-zero")).expect("valid constant")
        });

        keyed.push((BINANCE_GLOBAL_RATE_KEY.to_string(), default_quota));

        RateLimitConfig {
            default_quota: Some(default_quota),
            keyed_quotas: keyed,
            order_keys,
        }
    }

    fn quota_from(quota: &BinanceRateLimitQuota) -> Option<Quota> {
        let burst = NonZeroU32::new(quota.limit)?;
        match quota.interval {
            BinanceRateLimitInterval::Second => Quota::per_second(burst),
            BinanceRateLimitInterval::Minute => Some(Quota::per_minute(burst)),
            BinanceRateLimitInterval::Day => {
                Quota::with_period(std::time::Duration::from_secs(SECONDS_IN_DAY))
                    .map(|q| q.allow_burst(burst))
            }
            BinanceRateLimitInterval::Unknown => None,
        }
    }

    /// Tests connectivity to the API.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    pub async fn ping(&self) -> BinanceSpotHttpResult<()> {
        let bytes = self.get("ping", None::<&()>).await?;
        parse::decode_ping(&bytes)?;
        Ok(())
    }

    /// Returns the server time in **microseconds** since epoch.
    ///
    /// Note: SBE provides microsecond precision vs JSON's milliseconds.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    pub async fn server_time(&self) -> BinanceSpotHttpResult<i64> {
        let bytes = self.get("time", None::<&()>).await?;
        let timestamp = parse::decode_server_time(&bytes)?;
        Ok(timestamp)
    }

    /// Returns exchange information including trading symbols.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    pub async fn exchange_info(
        &self,
    ) -> BinanceSpotHttpResult<super::models::BinanceExchangeInfoSbe> {
        let bytes = self.get("exchangeInfo", None::<&()>).await?;
        let info = parse::decode_exchange_info(&bytes)?;
        Ok(info)
    }

    /// Returns order book depth for a symbol.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    pub async fn depth(&self, params: &DepthParams) -> BinanceSpotHttpResult<BinanceDepth> {
        let bytes = self.get("depth", Some(params)).await?;
        let depth = parse::decode_depth(&bytes)?;
        Ok(depth)
    }

    /// Returns recent trades for a symbol.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    pub async fn trades(
        &self,
        symbol: &str,
        limit: Option<u32>,
    ) -> BinanceSpotHttpResult<BinanceTrades> {
        let params = TradesParams {
            symbol: symbol.to_string(),
            limit,
        };
        let bytes = self.get("trades", Some(&params)).await?;
        let trades = parse::decode_trades(&bytes)?;
        Ok(trades)
    }

    /// Returns kline (candlestick) data for a symbol.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    pub async fn klines(
        &self,
        symbol: &str,
        interval: &str,
        start_time: Option<i64>,
        end_time: Option<i64>,
        limit: Option<u32>,
    ) -> BinanceSpotHttpResult<BinanceKlines> {
        let params = KlinesParams {
            symbol: symbol.to_string(),
            interval: interval.to_string(),
            start_time,
            end_time,
            time_zone: None,
            limit,
        };
        let bytes = self.get("klines", Some(&params)).await?;
        let klines = parse::decode_klines(&bytes)?;
        Ok(klines)
    }

    /// Performs a public GET request that returns JSON.
    async fn get_json<P>(&self, path: &str, params: Option<&P>) -> BinanceSpotHttpResult<Vec<u8>>
    where
        P: Serialize + ?Sized,
    {
        let query = params
            .map(serde_urlencoded::to_string)
            .transpose()
            .map_err(|e| BinanceSpotHttpError::ValidationError(e.to_string()))?
            .unwrap_or_default();

        let url = self.build_url(path, &query);
        let keys = vec![BINANCE_GLOBAL_RATE_KEY.to_string()];

        let response = self
            .client
            .request(
                Method::GET,
                url,
                None::<&HashMap<String, Vec<String>>>,
                None,
                None,
                None,
                Some(keys),
            )
            .await?;

        if !response.status.is_success() {
            return self.parse_error_response(&response);
        }

        Ok(response.body.to_vec())
    }

    /// Returns 24-hour ticker price change statistics.
    ///
    /// If `symbol` is None, returns statistics for all symbols.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn ticker_24hr(
        &self,
        symbol: Option<&str>,
    ) -> BinanceSpotHttpResult<Vec<Ticker24hr>> {
        let params = symbol.map(TickerParams::for_symbol);
        let bytes = self.get_json("ticker/24hr", params.as_ref()).await?;

        // Single symbol returns object, multiple returns array
        if symbol.is_some() {
            let ticker: Ticker24hr = serde_json::from_slice(&bytes)
                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
            Ok(vec![ticker])
        } else {
            let tickers: Vec<Ticker24hr> = serde_json::from_slice(&bytes)
                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
            Ok(tickers)
        }
    }

    /// Returns latest price for a symbol or all symbols.
    ///
    /// If `symbol` is None, returns prices for all symbols.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn ticker_price(
        &self,
        symbol: Option<&str>,
    ) -> BinanceSpotHttpResult<Vec<TickerPrice>> {
        let params = symbol.map(TickerParams::for_symbol);
        let bytes = self.get_json("ticker/price", params.as_ref()).await?;

        // Single symbol returns object, multiple returns array
        if symbol.is_some() {
            let ticker: TickerPrice = serde_json::from_slice(&bytes)
                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
            Ok(vec![ticker])
        } else {
            let tickers: Vec<TickerPrice> = serde_json::from_slice(&bytes)
                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
            Ok(tickers)
        }
    }

    /// Returns best bid/ask price for a symbol or all symbols.
    ///
    /// If `symbol` is None, returns book ticker for all symbols.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn ticker_book(
        &self,
        symbol: Option<&str>,
    ) -> BinanceSpotHttpResult<Vec<BookTicker>> {
        let params = symbol.map(TickerParams::for_symbol);
        let bytes = self.get_json("ticker/bookTicker", params.as_ref()).await?;

        // Single symbol returns object, multiple returns array
        if symbol.is_some() {
            let ticker: BookTicker = serde_json::from_slice(&bytes)
                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
            Ok(vec![ticker])
        } else {
            let tickers: Vec<BookTicker> = serde_json::from_slice(&bytes)
                .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
            Ok(tickers)
        }
    }

    /// Returns current average price for a symbol.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub async fn avg_price(&self, symbol: &str) -> BinanceSpotHttpResult<AvgPrice> {
        let params = AvgPriceParams::new(symbol);
        let bytes = self.get_json("avgPrice", Some(&params)).await?;

        let avg_price: AvgPrice = serde_json::from_slice(&bytes)
            .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
        Ok(avg_price)
    }

    /// Returns trading fee rates for symbols.
    ///
    /// If `symbol` is None, returns fee rates for all symbols.
    /// Uses SAPI endpoint (requires authentication).
    ///
    /// # Errors
    ///
    /// Returns an error if credentials are missing or the request fails.
    pub async fn get_trade_fee(
        &self,
        symbol: Option<&str>,
    ) -> BinanceSpotHttpResult<Vec<TradeFee>> {
        let params = symbol.map(TradeFeeParams::for_symbol);
        let bytes = self
            .get_signed_sapi("asset/tradeFee", params.as_ref())
            .await?;

        let fees: Vec<TradeFee> = serde_json::from_slice(&bytes)
            .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;
        Ok(fees)
    }

    /// Performs a signed GET request to SAPI endpoints (returns JSON).
    async fn get_signed_sapi<P>(
        &self,
        path: &str,
        params: Option<&P>,
    ) -> BinanceSpotHttpResult<Vec<u8>>
    where
        P: Serialize + ?Sized,
    {
        let cred = self
            .credential
            .as_ref()
            .ok_or(BinanceSpotHttpError::MissingCredentials)?;

        let mut query = params
            .map(serde_urlencoded::to_string)
            .transpose()
            .map_err(|e| BinanceSpotHttpError::ValidationError(e.to_string()))?
            .unwrap_or_default();

        if !query.is_empty() {
            query.push('&');
        }

        let timestamp = Utc::now().timestamp_millis();
        query.push_str(&format!("timestamp={timestamp}"));

        if let Some(recv_window) = self.recv_window {
            query.push_str(&format!("&recvWindow={recv_window}"));
        }

        let signature = cred.sign(&query);
        query.push_str(&format!("&signature={signature}"));

        // Build SAPI URL (different from regular API path)
        let normalized_path = if path.starts_with('/') {
            path.to_string()
        } else {
            format!("/{path}")
        };

        let mut url = format!("{}/sapi/v1{}", self.base_url, normalized_path);

        if !query.is_empty() {
            url.push('?');
            url.push_str(&query);
        }

        let mut headers = HashMap::new();
        headers.insert(
            BINANCE_API_KEY_HEADER.to_string(),
            cred.api_key().to_string(),
        );

        let keys = vec![BINANCE_GLOBAL_RATE_KEY.to_string()];

        let response = self
            .client
            .request(
                Method::GET,
                url,
                None::<&HashMap<String, Vec<String>>>,
                Some(headers),
                None,
                None,
                Some(keys),
            )
            .await?;

        if !response.status.is_success() {
            return self.parse_error_response(&response);
        }

        Ok(response.body.to_vec())
    }

    /// Percent-encodes a string for use in URL query parameters.
    fn percent_encode(input: &str) -> String {
        let mut result = String::with_capacity(input.len() * 3);
        for byte in input.bytes() {
            match byte {
                // Unreserved characters (RFC 3986)
                b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                    result.push(byte as char);
                }
                _ => {
                    result.push('%');
                    result.push_str(&format!("{byte:02X}"));
                }
            }
        }
        result
    }

    /// Submits multiple orders in a single request (up to 5 orders).
    ///
    /// Each order in the batch is processed independently. The response contains
    /// the result for each order, which can be either a success or an error.
    ///
    /// # Errors
    ///
    /// Returns an error if credentials are missing, the request fails, or
    /// JSON parsing fails. Individual order failures are returned in the
    /// response array as `BatchOrderResult::Error`.
    pub async fn batch_submit_orders(
        &self,
        orders: &[BatchOrderItem],
    ) -> BinanceSpotHttpResult<Vec<BatchOrderResult>> {
        if orders.is_empty() {
            return Ok(Vec::new());
        }

        if orders.len() > 5 {
            return Err(BinanceSpotHttpError::ValidationError(
                "Batch order limit is 5 orders maximum".to_string(),
            ));
        }

        let batch_json = serde_json::to_string(orders)
            .map_err(|e| BinanceSpotHttpError::ValidationError(e.to_string()))?;

        let bytes = self
            .batch_request(Method::POST, "batchOrders", &batch_json)
            .await?;

        let results: Vec<BatchOrderResult> = serde_json::from_slice(&bytes)
            .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;

        Ok(results)
    }

    /// Cancels multiple orders in a single request (up to 5 orders).
    ///
    /// Each cancel in the batch is processed independently. The response contains
    /// the result for each cancel, which can be either a success or an error.
    ///
    /// # Errors
    ///
    /// Returns an error if credentials are missing, the request fails, or
    /// JSON parsing fails. Individual cancel failures are returned in the
    /// response array as `BatchCancelResult::Error`.
    pub async fn batch_cancel_orders(
        &self,
        cancels: &[BatchCancelItem],
    ) -> BinanceSpotHttpResult<Vec<BatchCancelResult>> {
        if cancels.is_empty() {
            return Ok(Vec::new());
        }

        if cancels.len() > 5 {
            return Err(BinanceSpotHttpError::ValidationError(
                "Batch cancel limit is 5 orders maximum".to_string(),
            ));
        }

        let batch_json = serde_json::to_string(cancels)
            .map_err(|e| BinanceSpotHttpError::ValidationError(e.to_string()))?;

        let bytes = self
            .batch_request(Method::DELETE, "batchOrders", &batch_json)
            .await?;

        let results: Vec<BatchCancelResult> = serde_json::from_slice(&bytes)
            .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;

        Ok(results)
    }

    /// Performs a signed batch request with the batchOrders parameter.
    async fn batch_request(
        &self,
        method: Method,
        path: &str,
        batch_json: &str,
    ) -> BinanceSpotHttpResult<Vec<u8>> {
        let cred = self
            .credential
            .as_ref()
            .ok_or(BinanceSpotHttpError::MissingCredentials)?;

        let encoded_batch = Self::percent_encode(batch_json);
        let timestamp = Utc::now().timestamp_millis();
        let mut query = format!("batchOrders={encoded_batch}&timestamp={timestamp}");

        if let Some(recv_window) = self.recv_window {
            query.push_str(&format!("&recvWindow={recv_window}"));
        }

        let signature = cred.sign(&query);
        query.push_str(&format!("&signature={signature}"));

        let url = self.build_url(path, &query);

        let mut headers = HashMap::new();
        headers.insert(
            BINANCE_API_KEY_HEADER.to_string(),
            cred.api_key().to_string(),
        );

        let keys = self.rate_limit_keys(true);

        let response = self
            .client
            .request(
                method,
                url,
                None::<&HashMap<String, Vec<String>>>,
                Some(headers),
                None,
                None,
                Some(keys),
            )
            .await?;

        if !response.status.is_success() {
            return self.parse_error_response(&response);
        }

        Ok(response.body.to_vec())
    }

    /// Returns account information including balances.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    pub async fn account(
        &self,
        params: &AccountInfoParams,
    ) -> BinanceSpotHttpResult<BinanceAccountInfo> {
        let bytes = self.get_signed("account", Some(params)).await?;
        let response = parse::decode_account(&bytes)?;
        Ok(response)
    }

    /// Returns account trade history for a symbol.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    pub async fn account_trades(
        &self,
        symbol: &str,
        order_id: Option<i64>,
        start_time: Option<i64>,
        end_time: Option<i64>,
        limit: Option<u32>,
    ) -> BinanceSpotHttpResult<Vec<BinanceAccountTrade>> {
        let params = AccountTradesParams {
            symbol: symbol.to_string(),
            order_id,
            start_time,
            end_time,
            from_id: None,
            limit,
        };
        let bytes = self.get_signed("myTrades", Some(&params)).await?;
        let response = parse::decode_account_trades(&bytes)?;
        Ok(response)
    }

    /// Queries an order's status.
    ///
    /// Either `order_id` or `client_order_id` must be provided.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    pub async fn query_order(
        &self,
        symbol: &str,
        order_id: Option<i64>,
        client_order_id: Option<&str>,
    ) -> BinanceSpotHttpResult<BinanceOrderResponse> {
        let params = QueryOrderParams {
            symbol: symbol.to_string(),
            order_id,
            orig_client_order_id: client_order_id.map(|s| s.to_string()),
        };
        let bytes = self.get_signed("order", Some(&params)).await?;
        let response = parse::decode_order(&bytes)?;
        Ok(response)
    }

    /// Returns all open orders for a symbol or all symbols.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    pub async fn open_orders(
        &self,
        symbol: Option<&str>,
    ) -> BinanceSpotHttpResult<Vec<BinanceOrderResponse>> {
        let params = OpenOrdersParams {
            symbol: symbol.map(|s| s.to_string()),
        };
        let bytes = self.get_signed("openOrders", Some(&params)).await?;
        let response = parse::decode_orders(&bytes)?;
        Ok(response)
    }

    /// Returns all orders (including closed) for a symbol.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    pub async fn all_orders(
        &self,
        symbol: &str,
        start_time: Option<i64>,
        end_time: Option<i64>,
        limit: Option<u32>,
    ) -> BinanceSpotHttpResult<Vec<BinanceOrderResponse>> {
        let params = AllOrdersParams {
            symbol: symbol.to_string(),
            order_id: None,
            start_time,
            end_time,
            limit,
        };
        let bytes = self.get_signed("allOrders", Some(&params)).await?;
        let response = parse::decode_orders(&bytes)?;
        Ok(response)
    }

    /// Performs a signed POST request for order operations.
    async fn post_order<P>(&self, path: &str, params: Option<&P>) -> BinanceSpotHttpResult<Vec<u8>>
    where
        P: Serialize + ?Sized,
    {
        self.post_signed(path, params).await
    }

    /// Performs a signed DELETE request for cancel operations.
    async fn delete_order<P>(
        &self,
        path: &str,
        params: Option<&P>,
    ) -> BinanceSpotHttpResult<Vec<u8>>
    where
        P: Serialize + ?Sized,
    {
        self.delete_signed(path, params).await
    }

    /// Creates a new order.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    #[allow(clippy::too_many_arguments)]
    pub async fn new_order(
        &self,
        symbol: &str,
        side: BinanceSide,
        order_type: BinanceSpotOrderType,
        time_in_force: Option<BinanceTimeInForce>,
        quantity: Option<&str>,
        price: Option<&str>,
        client_order_id: Option<&str>,
        stop_price: Option<&str>,
    ) -> BinanceSpotHttpResult<BinanceNewOrderResponse> {
        let params = NewOrderParams {
            symbol: symbol.to_string(),
            side,
            order_type,
            time_in_force,
            quantity: quantity.map(|s| s.to_string()),
            quote_order_qty: None,
            price: price.map(|s| s.to_string()),
            new_client_order_id: client_order_id.map(|s| s.to_string()),
            stop_price: stop_price.map(|s| s.to_string()),
            trailing_delta: None,
            iceberg_qty: None,
            new_order_resp_type: Some(BinanceOrderResponseType::Full),
            self_trade_prevention_mode: None,
            strategy_id: None,
            strategy_type: None,
        };
        let bytes = self.post_order("order", Some(&params)).await?;
        let response = parse::decode_new_order_full(&bytes)?;
        Ok(response)
    }

    /// Creates a new order with full parameter support.
    ///
    /// Extends [`new_order`](Self::new_order) with `quote_order_qty` (for market
    /// orders denominated in quote currency) and `iceberg_qty` (display
    /// quantity for iceberg orders).
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    #[allow(clippy::too_many_arguments)]
    pub async fn new_order_full(
        &self,
        symbol: &str,
        side: BinanceSide,
        order_type: BinanceSpotOrderType,
        time_in_force: Option<BinanceTimeInForce>,
        quantity: Option<&str>,
        quote_order_qty: Option<&str>,
        price: Option<&str>,
        client_order_id: Option<&str>,
        stop_price: Option<&str>,
        iceberg_qty: Option<&str>,
    ) -> BinanceSpotHttpResult<BinanceNewOrderResponse> {
        let params = NewOrderParams {
            symbol: symbol.to_string(),
            side,
            order_type,
            time_in_force,
            quantity: quantity.map(|s| s.to_string()),
            quote_order_qty: quote_order_qty.map(|s| s.to_string()),
            price: price.map(|s| s.to_string()),
            new_client_order_id: client_order_id.map(|s| s.to_string()),
            stop_price: stop_price.map(|s| s.to_string()),
            trailing_delta: None,
            iceberg_qty: iceberg_qty.map(|s| s.to_string()),
            new_order_resp_type: Some(BinanceOrderResponseType::Full),
            self_trade_prevention_mode: None,
            strategy_id: None,
            strategy_type: None,
        };
        let bytes = self.post_order("order", Some(&params)).await?;
        let response = parse::decode_new_order_full(&bytes)?;
        Ok(response)
    }

    /// Cancels an existing order and places a new order atomically.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    #[allow(clippy::too_many_arguments)]
    pub async fn cancel_replace_order(
        &self,
        symbol: &str,
        side: BinanceSide,
        order_type: BinanceSpotOrderType,
        time_in_force: Option<BinanceTimeInForce>,
        quantity: Option<&str>,
        price: Option<&str>,
        cancel_order_id: Option<i64>,
        cancel_client_order_id: Option<&str>,
        new_client_order_id: Option<&str>,
    ) -> BinanceSpotHttpResult<BinanceNewOrderResponse> {
        let params = CancelReplaceOrderParams {
            symbol: symbol.to_string(),
            side,
            order_type,
            cancel_replace_mode: BinanceCancelReplaceMode::StopOnFailure,
            time_in_force,
            quantity: quantity.map(|s| s.to_string()),
            quote_order_qty: None,
            price: price.map(|s| s.to_string()),
            cancel_order_id,
            cancel_orig_client_order_id: cancel_client_order_id.map(|s| s.to_string()),
            new_client_order_id: new_client_order_id.map(|s| s.to_string()),
            stop_price: None,
            trailing_delta: None,
            iceberg_qty: None,
            new_order_resp_type: Some(BinanceOrderResponseType::Full),
            self_trade_prevention_mode: None,
        };
        let bytes = self
            .post_order("order/cancelReplace", Some(&params))
            .await?;
        let response = parse::decode_new_order_full(&bytes)?;
        Ok(response)
    }

    /// Cancels an existing order.
    ///
    /// Either `order_id` or `client_order_id` must be provided.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    pub async fn cancel_order(
        &self,
        symbol: &str,
        order_id: Option<i64>,
        client_order_id: Option<&str>,
    ) -> BinanceSpotHttpResult<BinanceCancelOrderResponse> {
        let params = match (order_id, client_order_id) {
            (Some(id), _) => CancelOrderParams::by_order_id(symbol, id),
            (None, Some(id)) => CancelOrderParams::by_client_order_id(symbol, id.to_string()),
            (None, None) => {
                return Err(BinanceSpotHttpError::ValidationError(
                    "Either order_id or client_order_id must be provided".to_string(),
                ));
            }
        };
        let bytes = self.delete_order("order", Some(&params)).await?;
        let response = parse::decode_cancel_order(&bytes)?;
        Ok(response)
    }

    /// Cancels all open orders for a symbol.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    pub async fn cancel_open_orders(
        &self,
        symbol: &str,
    ) -> BinanceSpotHttpResult<Vec<BinanceCancelOrderResponse>> {
        let params = CancelOpenOrdersParams::new(symbol.to_string());
        let bytes = self.delete_order("openOrders", Some(&params)).await?;
        let response = parse::decode_cancel_open_orders(&bytes)?;
        Ok(response)
    }

    /// Performs an API-key authenticated request (no signature) that returns JSON.
    async fn request_with_api_key<P>(
        &self,
        method: Method,
        path: &str,
        params: Option<&P>,
    ) -> BinanceSpotHttpResult<Vec<u8>>
    where
        P: Serialize + ?Sized,
    {
        let cred = self
            .credential
            .as_ref()
            .ok_or(BinanceSpotHttpError::MissingCredentials)?;

        let query = params
            .map(serde_urlencoded::to_string)
            .transpose()
            .map_err(|e| BinanceSpotHttpError::ValidationError(e.to_string()))?
            .unwrap_or_default();

        let url = self.build_url(path, &query);

        let mut headers = HashMap::new();
        headers.insert(
            BINANCE_API_KEY_HEADER.to_string(),
            cred.api_key().to_string(),
        );

        let keys = vec![BINANCE_GLOBAL_RATE_KEY.to_string()];

        let response = self
            .client
            .request(
                method,
                url,
                None::<&HashMap<String, Vec<String>>>,
                Some(headers),
                None,
                None,
                Some(keys),
            )
            .await?;

        if !response.status.is_success() {
            return self.parse_error_response(&response);
        }

        Ok(response.body.to_vec())
    }

    /// Creates a new listen key for the user data stream.
    ///
    /// Listen keys are valid for 60 minutes. Use `extend_listen_key` to keep
    /// the stream alive.
    ///
    /// # Errors
    ///
    /// Returns an error if credentials are missing or the request fails.
    pub async fn create_listen_key(&self) -> BinanceSpotHttpResult<ListenKeyResponse> {
        let bytes = self
            .request_with_api_key(Method::POST, "userDataStream", None::<&()>)
            .await?;

        let response: ListenKeyResponse = serde_json::from_slice(&bytes)
            .map_err(|e| BinanceSpotHttpError::JsonError(e.to_string()))?;

        Ok(response)
    }

    /// Extends the validity of a listen key by 60 minutes.
    ///
    /// Should be called periodically to keep the user data stream alive.
    ///
    /// # Errors
    ///
    /// Returns an error if credentials are missing or the request fails.
    pub async fn extend_listen_key(&self, listen_key: &str) -> BinanceSpotHttpResult<()> {
        let params = ListenKeyParams::new(listen_key);
        self.request_with_api_key(Method::PUT, "userDataStream", Some(&params))
            .await?;
        Ok(())
    }

    /// Closes a listen key, terminating the user data stream.
    ///
    /// # Errors
    ///
    /// Returns an error if credentials are missing or the request fails.
    pub async fn close_listen_key(&self, listen_key: &str) -> BinanceSpotHttpResult<()> {
        let params = ListenKeyParams::new(listen_key);
        self.request_with_api_key(Method::DELETE, "userDataStream", Some(&params))
            .await?;
        Ok(())
    }
}

/// High-level HTTP client for Binance Spot API.
///
/// Wraps [`BinanceRawSpotHttpClient`] and provides domain-level methods:
/// - Simple types (ping, server_time): Pass through from raw client.
/// - Complex types (instruments, orders): Transform to Nautilus domain types.
pub struct BinanceSpotHttpClient {
    inner: Arc<BinanceRawSpotHttpClient>,
    clock: &'static AtomicTime,
    instruments_cache: Arc<DashMap<Ustr, InstrumentAny>>,
}

impl Clone for BinanceSpotHttpClient {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            clock: self.clock,
            instruments_cache: self.instruments_cache.clone(),
        }
    }
}

impl Debug for BinanceSpotHttpClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct(stringify!(BinanceSpotHttpClient))
            .field("inner", &self.inner)
            .field("instruments_cached", &self.instruments_cache.len())
            .finish()
    }
}

impl BinanceSpotHttpClient {
    /// Creates a new Binance Spot HTTP client.
    ///
    /// # Errors
    ///
    /// Returns an error if the underlying HTTP client cannot be created.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        environment: BinanceEnvironment,
        clock: &'static AtomicTime,
        api_key: Option<String>,
        api_secret: Option<String>,
        base_url_override: Option<String>,
        recv_window: Option<u64>,
        timeout_secs: Option<u64>,
        proxy_url: Option<String>,
    ) -> BinanceSpotHttpResult<Self> {
        let inner = BinanceRawSpotHttpClient::new(
            environment,
            api_key,
            api_secret,
            base_url_override,
            recv_window,
            timeout_secs,
            proxy_url,
        )?;

        Ok(Self {
            inner: Arc::new(inner),
            clock,
            instruments_cache: Arc::new(DashMap::new()),
        })
    }

    /// Returns a reference to the inner raw client.
    #[must_use]
    pub fn inner(&self) -> &BinanceRawSpotHttpClient {
        &self.inner
    }

    /// Returns the SBE schema ID.
    #[must_use]
    pub const fn schema_id() -> u16 {
        SBE_SCHEMA_ID
    }

    /// Returns the SBE schema version.
    #[must_use]
    pub const fn schema_version() -> u16 {
        SBE_SCHEMA_VERSION
    }

    /// Generates a timestamp for initialization.
    fn generate_ts_init(&self) -> UnixNanos {
        self.clock.get_time_ns()
    }

    /// Retrieves an instrument from the cache.
    fn instrument_from_cache(&self, symbol: Ustr) -> anyhow::Result<InstrumentAny> {
        self.instruments_cache
            .get(&symbol)
            .map(|entry| entry.value().clone())
            .ok_or_else(|| anyhow::anyhow!("Instrument {symbol} not in cache"))
    }

    /// Caches multiple instruments.
    pub fn cache_instruments(&self, instruments: Vec<InstrumentAny>) {
        for inst in instruments {
            self.instruments_cache
                .insert(inst.raw_symbol().inner(), inst);
        }
    }

    /// Caches a single instrument.
    pub fn cache_instrument(&self, instrument: InstrumentAny) {
        self.instruments_cache
            .insert(instrument.raw_symbol().inner(), instrument);
    }

    /// Gets an instrument from the cache by symbol.
    #[must_use]
    pub fn get_instrument(&self, symbol: &Ustr) -> Option<InstrumentAny> {
        self.instruments_cache
            .get(symbol)
            .map(|entry| entry.value().clone())
    }

    /// Tests connectivity to the API.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    pub async fn ping(&self) -> BinanceSpotHttpResult<()> {
        self.inner.ping().await
    }

    /// Returns the server time in **microseconds** since epoch.
    ///
    /// Note: SBE provides microsecond precision vs JSON's milliseconds.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    pub async fn server_time(&self) -> BinanceSpotHttpResult<i64> {
        self.inner.server_time().await
    }

    /// Returns exchange information including trading symbols.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    pub async fn exchange_info(
        &self,
    ) -> BinanceSpotHttpResult<super::models::BinanceExchangeInfoSbe> {
        self.inner.exchange_info().await
    }

    /// Requests Nautilus instruments for all trading symbols.
    ///
    /// Fetches exchange info via SBE and parses each symbol into a CurrencyPair.
    /// Non-trading symbols are skipped with a debug log.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    pub async fn request_instruments(&self) -> BinanceSpotHttpResult<Vec<InstrumentAny>> {
        let info = self.exchange_info().await?;
        let ts_init = self.generate_ts_init();

        let mut instruments = Vec::with_capacity(info.symbols.len());
        for symbol in &info.symbols {
            match parse_spot_instrument_sbe(symbol, ts_init, ts_init) {
                Ok(instrument) => instruments.push(instrument),
                Err(e) => {
                    log::debug!(
                        "Skipping symbol during instrument parsing: symbol={}, error={e}",
                        symbol.symbol
                    );
                }
            }
        }

        // Cache instruments for use by other domain methods
        self.cache_instruments(instruments.clone());

        log::info!("Loaded spot instruments: count={}", instruments.len());
        Ok(instruments)
    }

    /// Requests recent trades for an instrument.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails, the instrument is not cached,
    /// or trade parsing fails.
    pub async fn request_trades(
        &self,
        instrument_id: InstrumentId,
        limit: Option<u32>,
    ) -> anyhow::Result<Vec<TradeTick>> {
        let symbol = instrument_id.symbol.inner();
        let instrument = self.instrument_from_cache(symbol)?;
        let ts_init = self.generate_ts_init();

        let trades = self
            .inner
            .trades(symbol.as_str(), limit)
            .await
            .map_err(|e| anyhow::anyhow!(e))?;

        parse_spot_trades_sbe(&trades, &instrument, ts_init)
    }

    /// Requests bar (kline/candlestick) data.
    ///
    /// # Errors
    ///
    /// Returns an error if the bar type is not supported, instrument is not cached,
    /// or the request fails.
    pub async fn request_bars(
        &self,
        bar_type: BarType,
        start: Option<DateTime<Utc>>,
        end: Option<DateTime<Utc>>,
        limit: Option<u32>,
    ) -> anyhow::Result<Vec<Bar>> {
        anyhow::ensure!(
            bar_type.aggregation_source() == AggregationSource::External,
            "Only EXTERNAL aggregation is supported"
        );

        let spec = bar_type.spec();
        let step = spec.step.get();
        let interval = match spec.aggregation {
            BarAggregation::Second => {
                anyhow::bail!("Binance Spot does not support second-level kline intervals")
            }
            BarAggregation::Minute => format!("{step}m"),
            BarAggregation::Hour => format!("{step}h"),
            BarAggregation::Day => format!("{step}d"),
            BarAggregation::Week => format!("{step}w"),
            BarAggregation::Month => format!("{step}M"),
            a => anyhow::bail!("Binance does not support {a:?} aggregation"),
        };

        let symbol = bar_type.instrument_id().symbol;
        let instrument = self.instrument_from_cache(symbol.inner())?;
        let ts_init = self.generate_ts_init();

        let klines = self
            .inner
            .klines(
                symbol.as_str(),
                &interval,
                start.map(|dt| dt.timestamp_millis()),
                end.map(|dt| dt.timestamp_millis()),
                limit,
            )
            .await
            .map_err(|e| anyhow::anyhow!(e))?;

        parse_klines_to_bars(&klines, bar_type, &instrument, ts_init)
    }

    /// Requests the account state with Nautilus types.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    pub async fn request_account_state(
        &self,
        account_id: AccountId,
    ) -> anyhow::Result<AccountState> {
        let ts_init = self.clock.get_time_ns();
        let params = AccountInfoParams::default();
        let account_info = self.inner.account(&params).await?;
        Ok(account_info.to_account_state(account_id, ts_init))
    }

    /// Requests the status of a specific order.
    ///
    /// Either `venue_order_id` or `client_order_id` must be provided.
    ///
    /// # Errors
    ///
    /// Returns an error if neither identifier is provided, the request fails,
    /// instrument is not cached, or parsing fails.
    pub async fn request_order_status_report(
        &self,
        account_id: AccountId,
        instrument_id: InstrumentId,
        venue_order_id: Option<VenueOrderId>,
        client_order_id: Option<ClientOrderId>,
    ) -> anyhow::Result<OrderStatusReport> {
        anyhow::ensure!(
            venue_order_id.is_some() || client_order_id.is_some(),
            "Either venue_order_id or client_order_id must be provided"
        );

        let symbol = instrument_id.symbol.inner();
        let instrument = self.instrument_from_cache(symbol)?;
        let ts_init = self.generate_ts_init();

        let order_id = venue_order_id
            .map(|id| id.inner().parse::<i64>())
            .transpose()
            .map_err(|_| anyhow::anyhow!("Invalid venue order ID"))?;

        let client_id_str =
            client_order_id.map(|id| encode_broker_id(&id, BINANCE_NAUTILUS_SPOT_BROKER_ID));

        let order = self
            .inner
            .query_order(symbol.as_str(), order_id, client_id_str.as_deref())
            .await
            .map_err(|e| anyhow::anyhow!(e))?;

        parse_order_status_report_sbe(
            &order,
            account_id,
            &instrument,
            BINANCE_NAUTILUS_SPOT_BROKER_ID,
            ts_init,
        )
    }

    /// Requests order status reports.
    ///
    /// When `open_only` is true, returns only open orders (instrument_id optional).
    /// When `open_only` is false, returns order history (instrument_id required).
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails, any order's instrument is not cached,
    /// or parsing fails.
    #[allow(clippy::too_many_arguments)]
    pub async fn request_order_status_reports(
        &self,
        account_id: AccountId,
        instrument_id: Option<InstrumentId>,
        start: Option<DateTime<Utc>>,
        end: Option<DateTime<Utc>>,
        open_only: bool,
        limit: Option<u32>,
    ) -> anyhow::Result<Vec<OrderStatusReport>> {
        let ts_init = self.generate_ts_init();
        let symbol = instrument_id.map(|id| id.symbol.to_string());

        let orders = if open_only {
            self.inner
                .open_orders(symbol.as_deref())
                .await
                .map_err(|e| anyhow::anyhow!(e))?
        } else {
            let symbol = symbol
                .ok_or_else(|| anyhow::anyhow!("instrument_id is required when open_only=false"))?;
            self.inner
                .all_orders(
                    &symbol,
                    start.map(|dt| dt.timestamp_millis()),
                    end.map(|dt| dt.timestamp_millis()),
                    limit,
                )
                .await
                .map_err(|e| anyhow::anyhow!(e))?
        };

        orders
            .iter()
            .map(|order| {
                let symbol = Ustr::from(&order.symbol);
                let instrument = self.instrument_from_cache(symbol)?;
                parse_order_status_report_sbe(
                    order,
                    account_id,
                    &instrument,
                    BINANCE_NAUTILUS_SPOT_BROKER_ID,
                    ts_init,
                )
            })
            .collect()
    }

    /// Requests fill reports (trade history) for an instrument.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails, any trade's instrument is not cached,
    /// or parsing fails.
    #[allow(clippy::too_many_arguments)]
    pub async fn request_fill_reports(
        &self,
        account_id: AccountId,
        instrument_id: InstrumentId,
        venue_order_id: Option<VenueOrderId>,
        start: Option<DateTime<Utc>>,
        end: Option<DateTime<Utc>>,
        limit: Option<u32>,
    ) -> anyhow::Result<Vec<FillReport>> {
        let ts_init = self.generate_ts_init();
        let symbol = instrument_id.symbol.inner();

        let order_id = venue_order_id
            .map(|id| id.inner().parse::<i64>())
            .transpose()
            .map_err(|_| anyhow::anyhow!("Invalid venue order ID"))?;

        let trades = self
            .inner
            .account_trades(
                symbol.as_str(),
                order_id,
                start.map(|dt| dt.timestamp_millis()),
                end.map(|dt| dt.timestamp_millis()),
                limit,
            )
            .await
            .map_err(|e| anyhow::anyhow!(e))?;

        trades
            .iter()
            .map(|trade| {
                let symbol = Ustr::from(&trade.symbol);
                let instrument = self.instrument_from_cache(symbol)?;
                let commission_currency = get_currency(&trade.commission_asset);
                parse_fill_report_sbe(trade, account_id, &instrument, commission_currency, ts_init)
            })
            .collect()
    }

    /// Submits a new order to the venue.
    ///
    /// Converts Nautilus domain types to Binance-specific parameters
    /// and returns an `OrderStatusReport`.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The instrument is not cached.
    /// - The order type or time-in-force is unsupported.
    /// - Stop orders are submitted without a trigger price.
    /// - The request fails or SBE decoding fails.
    #[allow(clippy::too_many_arguments)]
    pub async fn submit_order(
        &self,
        account_id: AccountId,
        instrument_id: InstrumentId,
        client_order_id: ClientOrderId,
        order_side: OrderSide,
        order_type: OrderType,
        quantity: Quantity,
        time_in_force: TimeInForce,
        price: Option<Price>,
        trigger_price: Option<Price>,
        post_only: bool,
        quote_quantity: bool,
        display_qty: Option<Quantity>,
    ) -> anyhow::Result<OrderStatusReport> {
        let symbol = instrument_id.symbol.inner();
        let instrument = self.instrument_from_cache(symbol)?;
        let ts_init = self.generate_ts_init();

        let binance_side = BinanceSide::try_from(order_side)?;
        let binance_order_type = order_type_to_binance_spot(order_type, post_only)?;

        // Validate trigger price for conditional orders
        let requires_trigger = matches!(
            order_type,
            OrderType::StopMarket
                | OrderType::StopLimit
                | OrderType::MarketIfTouched
                | OrderType::LimitIfTouched
        );

        if requires_trigger && trigger_price.is_none() {
            anyhow::bail!("Conditional orders require a trigger price");
        }

        // Validate price for order types that require it
        let requires_price = matches!(
            binance_order_type,
            BinanceSpotOrderType::Limit
                | BinanceSpotOrderType::StopLossLimit
                | BinanceSpotOrderType::TakeProfitLimit
                | BinanceSpotOrderType::LimitMaker
        );

        if requires_price && price.is_none() {
            anyhow::bail!("{binance_order_type:?} orders require a price");
        }

        // Only send TIF for order types that support it
        let supports_tif = matches!(
            binance_order_type,
            BinanceSpotOrderType::Limit
                | BinanceSpotOrderType::StopLossLimit
                | BinanceSpotOrderType::TakeProfitLimit
        );
        let binance_tif = if supports_tif {
            Some(time_in_force_to_binance_spot(time_in_force)?)
        } else {
            None
        };

        let qty_str = quantity.to_string();
        let price_str = price.map(|p| p.to_string());
        let stop_price_str = trigger_price.map(|p| p.to_string());
        let iceberg_qty_str = display_qty.map(|q| q.to_string());
        let client_id_str = encode_broker_id(&client_order_id, BINANCE_NAUTILUS_SPOT_BROKER_ID);

        if quote_quantity && binance_order_type != BinanceSpotOrderType::Market {
            anyhow::bail!("quoteOrderQty is only supported for MARKET orders");
        }

        let (base_qty, quote_qty) = if quote_quantity {
            (None, Some(qty_str.as_str()))
        } else {
            (Some(qty_str.as_str()), None)
        };

        let response = self
            .inner
            .new_order_full(
                symbol.as_str(),
                binance_side,
                binance_order_type,
                binance_tif,
                base_qty,
                quote_qty,
                price_str.as_deref(),
                Some(&client_id_str),
                stop_price_str.as_deref(),
                iceberg_qty_str.as_deref(),
            )
            .await?;

        parse_new_order_response_sbe(
            &response,
            account_id,
            &instrument,
            BINANCE_NAUTILUS_SPOT_BROKER_ID,
            ts_init,
        )
    }

    /// Submits multiple orders in a single batch request.
    ///
    /// Binance limits batch submit to 5 orders maximum.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or JSON parsing fails.
    pub async fn submit_order_list(
        &self,
        orders: &[BatchOrderItem],
    ) -> BinanceSpotHttpResult<Vec<BatchOrderResult>> {
        self.inner.batch_submit_orders(orders).await
    }

    /// Modifies an existing order (cancel and replace atomically).
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The instrument is not cached.
    /// - The order type or time-in-force is unsupported.
    /// - The request fails or SBE decoding fails.
    #[allow(clippy::too_many_arguments)]
    pub async fn modify_order(
        &self,
        account_id: AccountId,
        instrument_id: InstrumentId,
        venue_order_id: VenueOrderId,
        client_order_id: ClientOrderId,
        order_side: OrderSide,
        order_type: OrderType,
        quantity: Quantity,
        time_in_force: TimeInForce,
        price: Option<Price>,
    ) -> anyhow::Result<OrderStatusReport> {
        let symbol = instrument_id.symbol.inner();
        let instrument = self.instrument_from_cache(symbol)?;
        let ts_init = self.generate_ts_init();

        let binance_side = BinanceSide::try_from(order_side)?;
        let binance_order_type = order_type_to_binance_spot(order_type, false)?;
        let binance_tif = time_in_force_to_binance_spot(time_in_force)?;

        let cancel_order_id: i64 = venue_order_id
            .inner()
            .parse()
            .map_err(|_| anyhow::anyhow!("Invalid venue order ID: {venue_order_id}"))?;

        let qty_str = quantity.to_string();
        let price_str = price.map(|p| p.to_string());
        let client_id_str = encode_broker_id(&client_order_id, BINANCE_NAUTILUS_SPOT_BROKER_ID);

        let response = self
            .inner
            .cancel_replace_order(
                symbol.as_str(),
                binance_side,
                binance_order_type,
                Some(binance_tif),
                Some(&qty_str),
                price_str.as_deref(),
                Some(cancel_order_id),
                None,
                Some(&client_id_str),
            )
            .await
            .map_err(|e| anyhow::anyhow!(e))?;

        parse_new_order_response_sbe(
            &response,
            account_id,
            &instrument,
            BINANCE_NAUTILUS_SPOT_BROKER_ID,
            ts_init,
        )
    }

    /// Cancels an existing order on the venue.
    ///
    /// Either `venue_order_id` or `client_order_id` must be provided.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    pub async fn cancel_order(
        &self,
        instrument_id: InstrumentId,
        venue_order_id: Option<VenueOrderId>,
        client_order_id: Option<ClientOrderId>,
    ) -> anyhow::Result<VenueOrderId> {
        let symbol = instrument_id.symbol.inner();

        let order_id = venue_order_id
            .map(|id| id.inner().parse::<i64>())
            .transpose()
            .map_err(|_| anyhow::anyhow!("Invalid venue order ID"))?;

        let client_id_str =
            client_order_id.map(|id| encode_broker_id(&id, BINANCE_NAUTILUS_SPOT_BROKER_ID));

        let response = self
            .inner
            .cancel_order(symbol.as_str(), order_id, client_id_str.as_deref())
            .await
            .map_err(|e| anyhow::anyhow!(e))?;

        Ok(VenueOrderId::new(response.order_id.to_string()))
    }

    /// Cancels multiple orders in a single batch request.
    ///
    /// Binance limits batch cancel to 5 orders maximum.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or JSON parsing fails.
    pub async fn batch_cancel_orders(
        &self,
        cancels: &[BatchCancelItem],
    ) -> BinanceSpotHttpResult<Vec<BatchCancelResult>> {
        self.inner.batch_cancel_orders(cancels).await
    }

    /// Cancels all open orders for a symbol.
    ///
    /// Returns the venue order IDs of all canceled orders.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or SBE decoding fails.
    pub async fn cancel_all_orders(
        &self,
        instrument_id: InstrumentId,
    ) -> anyhow::Result<Vec<(VenueOrderId, ClientOrderId)>> {
        let symbol = instrument_id.symbol.inner();

        let responses = self
            .inner
            .cancel_open_orders(symbol.as_str())
            .await
            .map_err(|e| anyhow::anyhow!(e))?;

        Ok(responses
            .into_iter()
            .map(|r| {
                (
                    VenueOrderId::new(r.order_id.to_string()),
                    ClientOrderId::new(decode_broker_id(
                        &r.orig_client_order_id,
                        BINANCE_NAUTILUS_SPOT_BROKER_ID,
                    )),
                )
            })
            .collect())
    }
}

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

    use super::*;

    #[rstest]
    fn test_schema_constants() {
        assert_eq!(BinanceRawSpotHttpClient::schema_id(), 3);
        assert_eq!(BinanceRawSpotHttpClient::schema_version(), 3);
        assert_eq!(BinanceSpotHttpClient::schema_id(), 3);
        assert_eq!(BinanceSpotHttpClient::schema_version(), 3);
    }

    #[rstest]
    fn test_sbe_schema_header() {
        assert_eq!(SBE_SCHEMA_HEADER, "3:3");
    }

    #[rstest]
    fn test_default_headers_include_sbe() {
        let headers = BinanceRawSpotHttpClient::default_headers(&None);

        assert_eq!(headers.get("Accept"), Some(&"application/sbe".to_string()));
        assert_eq!(headers.get("X-MBX-SBE"), Some(&"3:3".to_string()));
    }

    #[rstest]
    fn test_rate_limit_config() {
        let config = BinanceRawSpotHttpClient::rate_limit_config();

        assert!(config.default_quota.is_some());
        // Spot has 2 ORDERS quotas (SECOND and DAY)
        assert_eq!(config.order_keys.len(), 2);
    }

    #[rstest]
    fn test_quota_from_unknown_interval_returns_none() {
        let quota = BinanceRateLimitQuota {
            rate_limit_type: BinanceRateLimitType::Orders,
            interval: BinanceRateLimitInterval::Unknown,
            interval_num: 1,
            limit: 10,
        };

        assert!(BinanceRawSpotHttpClient::quota_from(&quota).is_none());
    }
}