wickra-exchange-core 0.2.1

Core traits, types and shared connectivity machinery for wickra-exchange: a typed, unified API over the ten largest crypto exchanges.
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
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
//! Binance — the reference exchange implementation.
//!
//! This module is generic over the injected [`HttpTransport`], so the entire
//! request-build → parse → normalise path is exercised offline against
//! [`MockHttpTransport`] with recorded Binance responses. Only the production
//! wiring of a real socket lives elsewhere.
//!
//! Covered here: the public REST market data (ticker, klines, depth), the
//! URL/symbol mapping, the Binance error taxonomy, HMAC-SHA256 signed execution
//! (place/cancel/query/open orders, balances) with `exchangeInfo` filter
//! validation, and the pull-based WebSocket market streams (trade/depth/ticker
//! subscribe + `poll_events`), and the private user-data stream (listen key ->
//! `wss://.../ws/<listenKey>`, whose order/balance frames `poll_events` surfaces
//! as [`Event::OrderUpdate`]/[`Event::BalanceUpdate`]; `keepalive_user_data`
//! refreshes the listen key with a `PUT`, and a dropped stream re-subscribes on
//! the next `poll_events`). The real socket adapter lands in a later slice.
//!
//! Binance is also the reference for [`AdvancedOrders`]: self-trade-prevention
//! (the `stp` field maps to `selfTradePreventionMode`), amend (native
//! `PUT /fapi/v1/order` on futures, atomic `cancelReplace` on spot), batch place
//! and cancel (native single-call `/fapi/v1/batchOrders` on futures, sequential
//! on spot), and OCO brackets (`/api/v3/order/oco`, a spot order-list;
//! unsupported on USDⓈ-M futures, which has no order-list).
//!
//! Binance is also the reference for [`WsExecution`]: `place_order_ws` /
//! `cancel_order_ws` sign the request exactly like REST, wrap it in a
//! `{id, method, params}` frame and exchange it on a dedicated `ws-api`
//! connection (`wss://ws-api.binance.com/ws-api/v3`, or `ws-fapi` on futures).

use crate::clock::ServerClock;
use crate::credentials::Credentials;
use crate::error::{Error, Result};
use crate::events::{BookDelta, BookLevel, Event, OrderBookSnapshot, TradePrint};
use crate::feeds::{
    DerivativesChannel, DerivativesFeed, FundingRate, Liquidation, LongShortRatio, MarkIndex,
    OpenInterest,
};
use crate::instruments::{Instrument, InstrumentCache, InstrumentFilters};
use crate::normalize::{format_decimal, parse_decimal};
use crate::options::{ExchangeOptions, MarginMode, MarketType, PositionMode, SelfTradePrevention};
use crate::positions::{Position, PositionSide};
use crate::signing::hmac_sha256_hex;
use crate::symbol::Symbol;
use crate::traits::{
    AdvancedOrders, Derivatives, DerivativesStream, Exchange, Execution, MarketData, WsExecution,
    WsUserData,
};
use crate::transport::{
    HttpMethod, HttpRequest, HttpResponse, HttpTransport, WsConnection, WsTransport,
};
use crate::types::{
    Balance, OcoRequest, Order, OrderRequest, OrderSide, OrderStatus, OrderType, Ticker,
    TimeInForce,
};
use rust_decimal::Decimal;
use serde::Deserialize;
use std::collections::HashMap;
use std::fmt;
use wickra_core::Candle;

/// The current Unix time in milliseconds, from the system clock.
fn system_now_ms() -> i64 {
    use std::time::{SystemTime, UNIX_EPOCH};
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("system clock is before the Unix epoch")
        .as_millis() as i64
}

/// A Binance client over an injected HTTP transport.
pub struct Binance {
    http: Box<dyn HttpTransport>,
    ws: Option<Box<dyn WsTransport>>,
    rest_base: String,
    market_type: MarketType,
    /// One-way or hedge. In hedge mode every futures order names the side of
    /// the account it acts on, and `reduceOnly` is not accepted.
    position_mode: PositionMode,
    testnet: bool,
    credentials: Option<Credentials>,
    recv_window_ms: u64,
    now_ms: Box<dyn Fn() -> i64 + Send + Sync>,
    connection: Option<Box<dyn WsConnection>>,
    subscriptions: Vec<(String, Symbol)>,
    /// Which derivatives channels were subscribed, per wire symbol. Binance
    /// carries funding and mark/index on one stream, so the frame alone cannot
    /// say which the caller asked for -- emitting both would invent a print the
    /// caller never subscribed to.
    derivatives_channels: Vec<(String, DerivativesChannel)>,
    sub_id: u64,
    sub_messages: Vec<String>,
    instruments: InstrumentCache,
    /// Offset between this machine's clock and the venue's, applied to every
    /// signed timestamp. Zero until [`sync_time`](Self::sync_time) is called.
    clock: ServerClock,
    /// A dedicated connection to the WebSocket order API (`ws-api`), opened lazily
    /// on the first [`place_order_ws`](Self::place_order_ws) call.
    ws_api_connection: Option<Box<dyn WsConnection>>,
    /// A dedicated connection to the private user-data stream, opened by
    /// [`subscribe_user_data`](Self::subscribe_user_data) and drained by
    /// [`poll_events`](Self::poll_events) alongside the public stream.
    user_data_connection: Option<Box<dyn WsConnection>>,
    /// The active listen key for the private stream, used by
    /// [`keepalive_user_data`](Self::keepalive_user_data) to refresh it.
    user_data_listen_key: Option<String>,
    /// Set once the private stream is subscribed, so [`poll_events`](Self::poll_events)
    /// re-subscribes it after a drop.
    user_data_active: bool,
}

/// Hand-written: the client holds `Box<dyn HttpTransport>`, `Box<dyn WsTransport>`
/// and a `Box<dyn Fn() -> i64>` clock, none of which a derive can reach. The
/// transports are shown by whether a connection is open rather than by value, and
/// the credentials only by whether they are set -- printing them would put secret
/// material into every log line that formats a client.
impl fmt::Debug for Binance {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Binance")
            .field("ws", &self.ws.is_some())
            .field("rest_base", &self.rest_base)
            .field("market_type", &self.market_type)
            .field("testnet", &self.testnet)
            .field("authenticated", &self.credentials.is_some())
            .field("recv_window_ms", &self.recv_window_ms)
            .field("connection", &self.connection.is_some())
            .field("subscriptions", &self.subscriptions.len())
            .field("sub_id", &self.sub_id)
            .field("sub_messages", &self.sub_messages.len())
            .field("instruments", &self.instruments)
            .field("clock_offset_ms", &self.clock.offset_ms())
            .field("ws_api_connection", &self.ws_api_connection.is_some())
            .field("user_data_connection", &self.user_data_connection.is_some())
            // Presence, never the value: a listen key grants read access to
            // the account's private order and balance stream, so it is
            // credential material and must not reach a log line.
            .field("user_data_listen_key", &self.user_data_listen_key.is_some())
            .field("user_data_active", &self.user_data_active)
            .finish_non_exhaustive()
    }
}

impl Binance {
    /// Refuse a market this client does not route.
    ///
    /// Called at every seam that reaches the venue -- the HTTP helpers and each
    /// WebSocket connect -- so an unrouted market is refused before a request
    /// is built rather than answered by whichever market the URL happened to
    /// name. See [`ensure_market_is_routed`](super::ensure_market_is_routed)
    /// for what each client used to answer instead.
    fn ensure_market_is_routed(&self) -> Result<()> {
        super::ensure_market_is_routed("Binance", self.market_type, super::SPOT_AND_LINEAR)
    }

    fn build(
        http: Box<dyn HttpTransport>,
        options: &ExchangeOptions,
        credentials: Option<Credentials>,
    ) -> Self {
        Self {
            http,
            ws: None,
            rest_base: rest_base_url(options.market_type, options.testnet).to_string(),
            market_type: options.market_type,
            position_mode: options.position_mode,
            testnet: options.testnet,
            credentials,
            recv_window_ms: options.recv_window_ms,
            now_ms: Box::new(system_now_ms),
            connection: None,
            subscriptions: Vec::new(),
            derivatives_channels: Vec::new(),
            sub_id: 0,
            sub_messages: Vec::new(),
            instruments: InstrumentCache::new(),
            clock: ServerClock::new(),
            ws_api_connection: None,
            user_data_connection: None,
            user_data_listen_key: None,
            user_data_active: false,
        }
    }

    /// Build a public (unauthenticated) Binance client over the given transport.
    #[must_use]
    pub fn with_http(http: Box<dyn HttpTransport>, options: &ExchangeOptions) -> Self {
        Self::build(http, options, None)
    }

    /// Build an authenticated Binance client for signed endpoints.
    #[must_use]
    pub fn with_credentials(
        http: Box<dyn HttpTransport>,
        options: &ExchangeOptions,
        credentials: Credentials,
    ) -> Self {
        Self::build(http, options, Some(credentials))
    }

    /// Override the timestamp source (used for deterministic signing in tests).
    #[must_use]
    pub fn with_clock(mut self, now_ms: Box<dyn Fn() -> i64 + Send + Sync>) -> Self {
        self.now_ms = now_ms;
        self
    }

    /// Attach a WebSocket transport, enabling the streaming subscriptions.
    #[must_use]
    pub fn with_ws(mut self, ws: Box<dyn WsTransport>) -> Self {
        self.ws = Some(ws);
        self
    }

    /// The market type this client is configured for.
    #[must_use]
    pub fn market_type(&self) -> MarketType {
        self.market_type
    }

    /// Whether this client targets the USDⓈ-M futures market (fapi paths) rather
    /// than spot (api/v3 paths).
    fn is_futures(&self) -> bool {
        matches!(self.market_type, MarketType::UsdMFutures)
    }

    /// The position half of an order: `positionSide` and `reduceOnly`.
    ///
    /// Binance treats these as alternatives rather than as two independent
    /// flags. In one-way mode a futures order carries `reduceOnly` and no
    /// `positionSide` (the venue defaults it to `BOTH`). In hedge mode it
    /// carries `positionSide` and **must not** carry `reduceOnly`: the venue
    /// rejects the combination with `-1106 Parameter 'reduceonly' sent when not
    /// required`, because naming the side is already what says whether the
    /// order opens or closes.
    ///
    /// Only a hedged *futures* client takes the second branch. Spot is
    /// untouched, and so is one-way futures.
    /// The position-related parameters as key/value pairs.
    ///
    /// The REST body and the WebSocket frame are different encodings of the same
    /// order, so they resolve this once here rather than each spelling it out.
    /// They did each spell it out, and drifted: the frame carried the hedged
    /// `positionSide` but never `reduceOnly`, so a one-way futures close sent
    /// over the socket opened a position instead, and a spot order carrying
    /// `reduce_only` was sent rather than refused.
    fn position_fields(&self, request: &OrderRequest) -> Result<Vec<(&'static str, String)>> {
        if self.is_futures() && self.position_mode == PositionMode::Hedge {
            let side = match PositionSide::for_order(request.side, request.reduce_only) {
                PositionSide::Long => "LONG",
                PositionSide::Short => "SHORT",
            };
            return Ok(vec![("positionSide", side.to_string())]);
        }
        if !request.reduce_only {
            return Ok(Vec::new());
        }
        // Spot has no positions to reduce and rejects the parameter outright
        // (-1104, "not all sent parameters were read"). Sending the order
        // without it would place an opening order where a closing one was
        // asked for, so the spot path refuses instead.
        if !self.is_futures() {
            return Err(Error::unsupported_field(
                "Binance",
                "reduce_only on a spot order",
                "spot holds balances, not positions, and rejects the parameter",
            ));
        }
        Ok(vec![("reduceOnly", "true".to_string())])
    }

    /// [`position_fields`](Self::position_fields) as a query-string fragment,
    /// for the REST body.
    fn position_params(&self, request: &OrderRequest) -> Result<String> {
        use std::fmt::Write as _;
        Ok(self.position_fields(request)?.into_iter().fold(
            String::new(),
            |mut out, (key, value)| {
                let _ = write!(out, "&{key}={value}");
                out
            },
        ))
    }

    /// The single-order endpoint (place/cancel/query) for this market.
    fn order_path(&self) -> &'static str {
        if self.is_futures() {
            "/fapi/v1/order"
        } else {
            "/api/v3/order"
        }
    }

    /// The open-orders endpoint for this market.
    fn open_orders_path(&self) -> &'static str {
        if self.is_futures() {
            "/fapi/v1/openOrders"
        } else {
            "/api/v3/openOrders"
        }
    }

    /// The Binance wire symbol for a canonical [`Symbol`] (`BTC/USDT` -> `BTCUSDT`).
    #[must_use]
    pub fn wire_symbol(symbol: &Symbol) -> String {
        symbol.to_concatenated()
    }

    /// A 24-hour ticker for `symbol`.
    ///
    /// # Errors
    /// Returns an [`Error`] if the request fails or the symbol is unknown.
    pub fn ticker(&self, symbol: &Symbol) -> Result<Ticker> {
        let query = format!("symbol={}", Self::wire_symbol(symbol));
        if self.is_futures() {
            // The futures 24-hour ticker carries no bid/ask, so combine it with
            // the book ticker for the top-of-book quote.
            let stats: RawFuturesTicker = deserialize(&self.get("/fapi/v1/ticker/24hr", &query)?)?;
            let book: RawBookTicker =
                deserialize(&self.get("/fapi/v1/ticker/bookTicker", &query)?)?;
            return Ok(Ticker {
                symbol: symbol.clone(),
                last: parse_decimal(&stats.last_price)?,
                bid: parse_decimal(&book.bid_price)?,
                ask: parse_decimal(&book.ask_price)?,
                volume: parse_decimal(&stats.volume)?,
                timestamp: stats.close_time,
            });
        }
        let raw: RawTicker = deserialize(&self.get("/api/v3/ticker/24hr", &query)?)?;
        Ok(Ticker {
            symbol: symbol.clone(),
            last: parse_decimal(&raw.last_price)?,
            bid: parse_decimal(&raw.bid_price)?,
            ask: parse_decimal(&raw.ask_price)?,
            volume: parse_decimal(&raw.volume)?,
            timestamp: raw.close_time,
        })
    }

    /// Up to `limit` candles for `symbol` at `interval` (e.g. `"1m"`, `"1h"`).
    ///
    /// # Errors
    /// Returns an [`Error`] if the request fails or a row cannot be parsed.
    pub fn klines(&self, symbol: &Symbol, interval: &str, limit: u32) -> Result<Vec<Candle>> {
        let query = format!(
            "symbol={}&interval={interval}&limit={limit}",
            Self::wire_symbol(symbol)
        );
        let path = if self.is_futures() {
            "/fapi/v1/klines"
        } else {
            "/api/v3/klines"
        };
        let body = self.get(path, &query)?;
        let rows: Vec<Vec<serde_json::Value>> = deserialize(&body)?;
        rows.iter().map(|row| parse_kline_row(row)).collect()
    }

    /// A depth snapshot of `symbol` up to `depth` levels per side.
    ///
    /// # Errors
    /// Returns an [`Error`] if the request fails or the response cannot be parsed.
    pub fn order_book(&self, symbol: &Symbol, depth: u32) -> Result<OrderBookSnapshot> {
        let query = format!("symbol={}&limit={depth}", Self::wire_symbol(symbol));
        let path = if self.is_futures() {
            "/fapi/v1/depth"
        } else {
            "/api/v3/depth"
        };
        let body = self.get(path, &query)?;
        let raw: RawDepth = deserialize(&body)?;
        Ok(OrderBookSnapshot {
            symbol: symbol.clone(),
            last_update_id: raw.last_update_id,
            bids: parse_levels(&raw.bids)?,
            asks: parse_levels(&raw.asks)?,
            timestamp: raw.transaction_time,
        })
    }

    /// Fetch `exchangeInfo` and populate the instrument/filter cache, so that
    /// [`place_order`](Self::place_order) validates against the venue's per-symbol
    /// filters (lot size, price tick, min-notional).
    ///
    /// # Errors
    /// Returns an [`Error`] if the request fails or the response cannot be parsed.
    pub fn load_instruments(&mut self) -> Result<()> {
        let path = if self.is_futures() {
            "/fapi/v1/exchangeInfo"
        } else {
            "/api/v3/exchangeInfo"
        };
        let body = self.get(path, "")?;
        let raw: RawExchangeInfo = deserialize(&body)?;
        let now = (self.now_ms)();
        let instruments: Vec<Instrument> = raw.symbols.iter().map(parse_instrument).collect();
        self.instruments.replace(instruments, now);
        Ok(())
    }

    /// The cached instrument metadata for `symbol`, if [`load_instruments`](Self::load_instruments)
    /// has been called.
    #[must_use]
    pub fn instrument(&self, symbol: &Symbol) -> Option<&Instrument> {
        self.instruments.get(symbol)
    }

    /// Subscribe to the public trade stream for `symbol`.
    ///
    /// # Errors
    /// Returns [`Error::NotConnected`] if no WebSocket transport is configured,
    /// or a transport error if the connection or subscription fails.
    pub fn subscribe_trades(&mut self, symbol: &Symbol) -> Result<()> {
        self.subscribe(symbol, "trade")
    }

    /// Subscribe to the order-book (diff-depth) stream for `symbol`.
    ///
    /// # Errors
    /// See [`subscribe_trades`](Self::subscribe_trades).
    pub fn subscribe_book(&mut self, symbol: &Symbol) -> Result<()> {
        self.subscribe(symbol, "depth")
    }

    /// Subscribe to the 24-hour ticker stream for `symbol`.
    ///
    /// # Errors
    /// See [`subscribe_trades`](Self::subscribe_trades).
    pub fn subscribe_ticker(&mut self, symbol: &Symbol) -> Result<()> {
        self.subscribe(symbol, "ticker")
    }

    /// Subscribe to a pushed derivatives channel.
    ///
    /// Binance publishes funding and mark/index on the *same* stream --
    /// `<symbol>@markPrice` carries the rate, the mark and the index in one
    /// frame -- so both channels resolve to it and the parser emits whichever
    /// the caller subscribed to. Forced liquidations are their own stream.
    ///
    /// These streams exist only on the futures venue; the spot client refuses
    /// rather than subscribing to a channel that will never carry a frame.
    ///
    /// # Errors
    /// Returns an [`Error`] on a spot client, or if the subscription fails.
    pub fn subscribe_derivatives(
        &mut self,
        symbol: &Symbol,
        channel: DerivativesChannel,
    ) -> Result<()> {
        if !self.is_futures() {
            return Err(Error::unsupported_field(
                "Binance",
                "a derivatives channel on a spot client",
                "funding, mark/index and liquidations exist only on the futures venue",
            ));
        }
        let stream = match channel {
            DerivativesChannel::Funding | DerivativesChannel::MarkIndex => "markPrice",
            DerivativesChannel::Liquidations => "forceOrder",
        };
        self.derivatives_channels
            .push((Self::wire_symbol(symbol), channel));
        self.subscribe(symbol, stream)
    }

    /// The current open interest (`GET /fapi/v1/openInterest`).
    ///
    /// Polled, not pushed: Binance has no open-interest stream.
    ///
    /// # Errors
    /// Returns an [`Error`] on a spot client or if the request fails.
    pub fn open_interest(&self, symbol: &Symbol) -> Result<OpenInterest> {
        if !self.is_futures() {
            return Err(Error::unsupported_field(
                "Binance",
                "open interest on a spot client",
                "open interest is a futures figure",
            ));
        }
        let query = format!("symbol={}", Self::wire_symbol(symbol));
        let body = self.get("/fapi/v1/openInterest", &query)?;
        let value: serde_json::Value = deserialize(&body)?;
        Ok(OpenInterest {
            symbol: symbol.clone(),
            open_interest: parse_decimal(field_str(&value, "openInterest")?)?,
            timestamp: value
                .get("time")
                .and_then(serde_json::Value::as_i64)
                .unwrap_or(0),
        })
    }

    /// The current long/short account ratio
    /// (`GET /futures/data/globalLongShortAccountRatio`), most recent point.
    ///
    /// Polled, not pushed. Binance reports this as *account* proportions rather
    /// than sizes, which sum to one; they are carried through as given, since
    /// scaling them to a notional would invent a figure the venue did not
    /// publish.
    ///
    /// # Errors
    /// Returns an [`Error`] on a spot client, if the request fails, or if the
    /// venue returns no data point.
    pub fn long_short_ratio(&self, symbol: &Symbol) -> Result<LongShortRatio> {
        if !self.is_futures() {
            return Err(Error::unsupported_field(
                "Binance",
                "long/short positioning on a spot client",
                "positioning is a futures figure",
            ));
        }
        let query = format!("symbol={}&period=5m&limit=1", Self::wire_symbol(symbol));
        let body = self.get("/futures/data/globalLongShortAccountRatio", &query)?;
        let points: Vec<serde_json::Value> = deserialize(&body)?;
        let point = points
            .first()
            .ok_or_else(|| Error::NotFound("no long/short data point".to_string()))?;
        Ok(LongShortRatio {
            symbol: symbol.clone(),
            long_size: parse_decimal(field_str(point, "longAccount")?)?,
            short_size: parse_decimal(field_str(point, "shortAccount")?)?,
            timestamp: point
                .get("timestamp")
                .and_then(serde_json::Value::as_i64)
                .unwrap_or(0),
        })
    }

    /// Open the connection if needed, send a SUBSCRIBE for `<symbol>@<channel>`,
    /// and register the symbol for wire-name resolution.
    fn subscribe(&mut self, symbol: &Symbol, channel: &str) -> Result<()> {
        self.ensure_market_is_routed()?;
        let wire = Self::wire_symbol(symbol);
        if self.connection.is_none() {
            let ws = self.ws.as_ref().ok_or(Error::NotConnected)?;
            let connection = ws.connect(ws_base_url(self.market_type, self.testnet))?;
            self.connection = Some(connection);
        }
        self.sub_id += 1;
        let stream = format!("{}@{channel}", wire.to_lowercase());
        let message = format!(
            r#"{{"method":"SUBSCRIBE","params":["{stream}"],"id":{}}}"#,
            self.sub_id
        );
        self.connection
            .as_mut()
            .expect("connection just ensured")
            .send(&message)?;
        if !self.subscriptions.iter().any(|(w, _)| w == &wire) {
            self.subscriptions.push((wire, symbol.clone()));
        }
        if !self.sub_messages.contains(&message) {
            self.sub_messages.push(message);
        }
        Ok(())
    }

    /// Drain all stream events available since the last call. Non-blocking:
    /// returns an empty vector when nothing is pending or no stream is open.
    /// Frames that fail to parse are skipped.
    pub fn poll_events(&mut self) -> Vec<Event> {
        let subscriptions: HashMap<String, Symbol> = self.subscriptions.iter().cloned().collect();
        let resolve = |wire: &str| {
            subscriptions
                .get(wire)
                .cloned()
                .unwrap_or_else(|| Symbol::new(wire, ""))
        };
        let channels = self.derivatives_channels.clone();
        let mut events = Vec::new();
        if let Some(connection) = self.connection.as_mut() {
            while let Ok(Some(frame)) = connection.recv() {
                if let Ok(Some(event)) = parse_ws_message(&frame, &resolve) {
                    events.push(event);
                }
                // Derivatives frames are parsed separately because one
                // `markPrice` frame can answer two subscriptions: it carries the
                // funding rate and the mark/index pair together.
                events.extend(parse_derivatives_message(&frame, &resolve, &channels));
            }
        }
        // Drain the private user-data stream (order/balance updates), if open.
        if let Some(connection) = self.user_data_connection.as_mut() {
            while let Ok(Some(frame)) = connection.recv() {
                if let Ok(Some(event)) = parse_ws_message(&frame, &resolve) {
                    events.push(event);
                }
            }
        }
        // A dropped private stream is re-subscribed with a fresh listen key
        // (a stale replay would fail, since the key is single-use).
        self.reconnect_user_data_if_dropped(&mut events);
        let url = ws_base_url(self.market_type, self.testnet);
        crate::wsutil::reconnect_if_dropped(
            self.ws.as_deref(),
            url,
            &mut self.connection,
            &self.sub_messages,
            &mut events,
        );
        events
    }

    /// Re-subscribe the private user-data stream if it has dropped, emitting
    /// [`Event::Disconnected`] then [`Event::Reconnected`] around a fresh
    /// [`subscribe_user_data`](Self::subscribe_user_data).
    fn reconnect_user_data_if_dropped(&mut self, events: &mut Vec<Event>) {
        if !self.user_data_active {
            return;
        }
        let dropped = self
            .user_data_connection
            .as_ref()
            .is_some_and(|c| !c.is_connected());
        if !dropped {
            return;
        }
        events.push(Event::Disconnected);
        self.user_data_connection = None;
        if self.subscribe_user_data().is_ok() {
            events.push(Event::Reconnected);
        }
    }

    /// Place an order. The order is validated locally first, then sent signed.
    ///
    /// # Errors
    /// Returns an [`Error`] if the order is invalid, credentials are missing, or
    /// the venue rejects it.
    pub fn place_order(&self, request: &OrderRequest) -> Result<Order> {
        request.validate()?;
        // When exchangeInfo has been loaded, reject filter violations before the
        // round trip.
        if let Some(instrument) = self.instruments.get(&request.symbol) {
            instrument
                .filters
                .validate(request.quantity, request.price)?;
        }
        let type_str = type_for(request)?;
        let mut params = format!(
            "symbol={}&side={}&type={type_str}&quantity={}",
            Self::wire_symbol(&request.symbol),
            side_str(request.side),
            format_decimal(request.quantity),
        );
        if let Some(price) = request.price {
            params.push_str("&price=");
            params.push_str(&format_decimal(price));
        }
        if let Some(stop) = request.stop_price {
            params.push_str("&stopPrice=");
            params.push_str(&format_decimal(stop));
        }
        if matches!(type_str, "LIMIT" | "STOP_LOSS_LIMIT" | "TAKE_PROFIT_LIMIT") {
            params.push_str("&timeInForce=");
            params.push_str(tif_str(request.time_in_force));
        }
        if let Some(id) = &request.client_order_id {
            params.push_str("&newClientOrderId=");
            params.push_str(id);
        }
        params.push_str(&self.position_params(request)?);
        if let Some(mode) = stp_str(request.stp) {
            params.push_str("&selfTradePreventionMode=");
            params.push_str(mode);
        }
        let body = self.signed_request(HttpMethod::Post, self.order_path(), &params)?;
        parse_order(&request.symbol, &body)
    }

    /// Cancel an open order by venue id.
    ///
    /// # Errors
    /// Returns an [`Error`] if credentials are missing or the venue rejects it.
    pub fn cancel_order(&self, symbol: &Symbol, order_id: &str) -> Result<()> {
        let params = format!("symbol={}&orderId={order_id}", Self::wire_symbol(symbol));
        self.signed_request(HttpMethod::Delete, self.order_path(), &params)?;
        Ok(())
    }

    /// Query a single order by venue id.
    ///
    /// # Errors
    /// Returns an [`Error`] if credentials are missing or the order is unknown.
    pub fn query_order(&self, symbol: &Symbol, order_id: &str) -> Result<Order> {
        let params = format!("symbol={}&orderId={order_id}", Self::wire_symbol(symbol));
        let body = self.signed_request(HttpMethod::Get, self.order_path(), &params)?;
        parse_order(symbol, &body)
    }

    /// Account balances (assets with a non-zero free or locked amount are
    /// included as the venue reports them).
    ///
    /// # Errors
    /// Returns an [`Error`] if credentials are missing or the request fails.
    pub fn balances(&self) -> Result<Vec<Balance>> {
        if self.is_futures() {
            let body = self.signed_request(HttpMethod::Get, "/fapi/v2/balance", "")?;
            let raw: Vec<RawFuturesBalance> = deserialize(&body)?;
            return raw
                .iter()
                .map(|b| {
                    let total = parse_decimal(&b.balance)?;
                    let free = parse_decimal(&b.available_balance)?;
                    Ok(Balance {
                        asset: b.asset.clone(),
                        free,
                        locked: total - free,
                    })
                })
                .collect();
        }
        let body = self.signed_request(HttpMethod::Get, "/api/v3/account", "")?;
        let raw: RawAccount = deserialize(&body)?;
        raw.balances
            .iter()
            .map(|b| {
                Ok(Balance {
                    asset: b.asset.clone(),
                    free: parse_decimal(&b.free)?,
                    locked: parse_decimal(&b.locked)?,
                })
            })
            .collect()
    }

    /// All open orders, optionally filtered to one `symbol`. When unfiltered, the
    /// venue reports each order's wire symbol, which is mapped back to a canonical
    /// [`Symbol`] via the known quote-asset suffixes.
    ///
    /// # Errors
    /// Returns an [`Error`] if credentials are missing or the request fails.
    pub fn open_orders(&self, symbol: Option<&Symbol>) -> Result<Vec<Order>> {
        let params = match symbol {
            Some(s) => format!("symbol={}", Self::wire_symbol(s)),
            None => String::new(),
        };
        let body = self.signed_request(HttpMethod::Get, self.open_orders_path(), &params)?;
        let raws: Vec<RawOrder> = deserialize(&body)?;
        raws.iter()
            .map(|raw| {
                let sym = symbol
                    .cloned()
                    .unwrap_or_else(|| split_wire_symbol(&raw.symbol));
                order_from_raw(sym, raw)
            })
            .collect()
    }

    /// Issue a GET and return the body, mapping non-2xx responses onto the error
    /// taxonomy.
    fn get(&self, path: &str, query: &str) -> Result<String> {
        self.ensure_market_is_routed()?;
        let url = if query.is_empty() {
            format!("{}{path}", self.rest_base)
        } else {
            format!("{}{path}?{query}", self.rest_base)
        };
        let response = self.http.execute(&HttpRequest::get(url))?;
        if response.is_success() {
            Ok(response.body)
        } else {
            Err(map_error(&response))
        }
    }

    /// The timestamp a signed request must carry: this machine's clock plus the
    /// offset learned from the venue.
    ///
    /// Binance rejects a signed request whose `timestamp` falls outside
    /// `recvWindow` of *its* clock, so a machine a few seconds off has every
    /// order refused with a message about the receive window rather than about
    /// the clock. Until [`sync_time`](Self::sync_time) is called the offset is
    /// zero and this is the local time, which is the previous behaviour.
    fn signed_now_ms(&self) -> i64 {
        self.clock.server_time_ms((self.now_ms)())
    }

    /// Learn the offset between this machine's clock and the venue's.
    ///
    /// Explicit rather than automatic, for the same reason as
    /// [`load_instruments`](Self::load_instruments): it costs a request, and a
    /// client should not make one the caller did not ask for. Call it once after
    /// connecting, and again if the process runs long enough for drift to
    /// matter.
    ///
    /// Returns the new offset in milliseconds (`server - local`).
    ///
    /// # Errors
    /// Returns an [`Error`] if the request fails or the response cannot be parsed.
    pub fn sync_time(&mut self) -> Result<i64> {
        let path = if self.is_futures() {
            "/fapi/v1/time"
        } else {
            "/api/v3/time"
        };
        let local_before = (self.now_ms)();
        let body = self.get(path, "")?;
        let raw: RawServerTime = deserialize(&body)?;
        self.clock.sync(local_before, raw.server_time);
        Ok(self.clock.offset_ms())
    }

    /// Sign `params` (HMAC-SHA256 over the query with `recvWindow` + `timestamp`)
    /// and issue the request with the API-key header.
    fn signed_request(&self, method: HttpMethod, path: &str, params: &str) -> Result<String> {
        self.ensure_market_is_routed()?;
        let creds = self.credentials.as_ref().ok_or(Error::InvalidCredentials(
            "signed endpoint requires credentials",
        ))?;
        let timestamp = self.signed_now_ms();
        let payload = if params.is_empty() {
            format!("recvWindow={}&timestamp={timestamp}", self.recv_window_ms)
        } else {
            format!(
                "{params}&recvWindow={}&timestamp={timestamp}",
                self.recv_window_ms
            )
        };
        let signature = hmac_sha256_hex(creds.api_secret.as_bytes(), payload.as_bytes());
        let url = format!("{}{path}?{payload}&signature={signature}", self.rest_base);
        let request =
            HttpRequest::new(method, url).with_header("X-MBX-APIKEY", creds.api_key.clone());
        let response = self.http.execute(&request)?;
        if response.is_success() {
            Ok(response.body)
        } else {
            Err(map_error(&response))
        }
    }
}

// The trait surface delegates to the inherent methods (fully qualified to avoid
// resolving back to the trait method), giving a `Box<dyn Exchange>` for the factory.
impl MarketData for Binance {
    fn ticker(&mut self, symbol: &Symbol) -> Result<Ticker> {
        Binance::ticker(self, symbol)
    }
    fn klines(&mut self, symbol: &Symbol, interval: &str, limit: u32) -> Result<Vec<Candle>> {
        Binance::klines(self, symbol, interval, limit)
    }
    fn order_book(&mut self, symbol: &Symbol, depth: u32) -> Result<OrderBookSnapshot> {
        Binance::order_book(self, symbol, depth)
    }
    fn subscribe_trades(&mut self, symbol: &Symbol) -> Result<()> {
        Binance::subscribe_trades(self, symbol)
    }
    fn subscribe_book(&mut self, symbol: &Symbol) -> Result<()> {
        Binance::subscribe_book(self, symbol)
    }
    fn subscribe_ticker(&mut self, symbol: &Symbol) -> Result<()> {
        Binance::subscribe_ticker(self, symbol)
    }
    fn poll_events(&mut self) -> Vec<Event> {
        Binance::poll_events(self)
    }
}

impl Execution for Binance {
    fn place_order(&mut self, request: &OrderRequest) -> Result<Order> {
        Binance::place_order(self, request)
    }
    fn cancel_order(&mut self, symbol: &Symbol, order_id: &str) -> Result<()> {
        Binance::cancel_order(self, symbol, order_id)
    }
    fn query_order(&mut self, symbol: &Symbol, order_id: &str) -> Result<Order> {
        Binance::query_order(self, symbol, order_id)
    }
    fn open_orders(&mut self, symbol: Option<&Symbol>) -> Result<Vec<Order>> {
        Binance::open_orders(self, symbol)
    }
    fn balances(&mut self) -> Result<Vec<Balance>> {
        Binance::balances(self)
    }
}

impl Exchange for Binance {
    fn name(&self) -> &'static str {
        "binance"
    }
}

impl Binance {
    /// Open positions on the USDⓈ-M futures account (`/fapi/v2/positionRisk`).
    ///
    /// # Errors
    /// Returns an [`Error`] if credentials are missing or the request fails.
    pub fn positions(&self, symbol: Option<&Symbol>) -> Result<Vec<Position>> {
        let params =
            symbol.map_or_else(String::new, |s| format!("symbol={}", Self::wire_symbol(s)));
        let body = self.signed_request(HttpMethod::Get, "/fapi/v2/positionRisk", &params)?;
        parse_positions(&body)
    }

    /// Set the leverage for `symbol` (`/fapi/v1/leverage`).
    ///
    /// # Errors
    /// Returns an [`Error`] if the leverage is rejected or the request fails.
    pub fn set_leverage(&self, symbol: &Symbol, leverage: u32) -> Result<()> {
        let params = format!("symbol={}&leverage={leverage}", Self::wire_symbol(symbol));
        self.signed_request(HttpMethod::Post, "/fapi/v1/leverage", &params)?;
        Ok(())
    }

    /// Set the margin mode for `symbol` (`/fapi/v1/marginType`).
    ///
    /// # Errors
    /// Returns an [`Error`] if the change is rejected or the request fails.
    pub fn set_margin_mode(&self, symbol: &Symbol, mode: MarginMode) -> Result<()> {
        let margin = match mode {
            MarginMode::Isolated => "ISOLATED",
            MarginMode::Cross => "CROSSED",
        };
        let params = format!("symbol={}&marginType={margin}", Self::wire_symbol(symbol));
        self.signed_request(HttpMethod::Post, "/fapi/v1/marginType", &params)?;
        Ok(())
    }

    /// Flatten the open position in `symbol` with a reduce-only market order.
    ///
    /// # Errors
    /// Returns [`Error::NotFound`] if there is no open position, or another
    /// [`Error`] if the request fails.
    pub fn close_position(&self, symbol: &Symbol) -> Result<Order> {
        let position = self
            .positions(Some(symbol))?
            .into_iter()
            .find(|p| &p.symbol == symbol)
            .ok_or_else(|| Error::NotFound(format!("no open position for {symbol}")))?;
        let request = match position.side {
            PositionSide::Long => OrderRequest::market_sell(symbol.clone(), position.quantity),
            PositionSide::Short => OrderRequest::market_buy(symbol.clone(), position.quantity),
        }
        .reduce_only();
        self.place_order(&request)
    }

    /// Amend a resting order's price and/or quantity. Binance futures amends in
    /// place (`PUT /fapi/v1/order`); spot has no in-place amend, so it is emulated
    /// as an atomic cancel-replace (`POST /api/v3/order/cancelReplace`). Either
    /// path first reads the existing order to preserve its side and type.
    ///
    /// # Errors
    /// Returns an [`Error`] if the order is unknown or the amend is rejected.
    pub fn amend_order(
        &self,
        symbol: &Symbol,
        order_id: &str,
        new_price: Option<Decimal>,
        new_quantity: Option<Decimal>,
    ) -> Result<Order> {
        let existing = self.query_order(symbol, order_id)?;
        let quantity = new_quantity.unwrap_or(existing.quantity);
        let price = new_price.or(existing.price);
        let wire = Self::wire_symbol(symbol);
        if self.is_futures() {
            let mut params = format!(
                "symbol={wire}&orderId={order_id}&side={}&quantity={}",
                side_str(existing.side),
                format_decimal(quantity),
            );
            if let Some(p) = price {
                params.push_str("&price=");
                params.push_str(&format_decimal(p));
            }
            let body = self.signed_request(HttpMethod::Put, self.order_path(), &params)?;
            return parse_order(symbol, &body);
        }
        let mut params = format!(
            "symbol={wire}&cancelReplaceMode=STOP_ON_FAILURE&cancelOrderId={order_id}\
             &side={}&type={}&quantity={}",
            side_str(existing.side),
            order_type_str(existing.order_type),
            format_decimal(quantity),
        );
        if let Some(p) = price {
            params.push_str("&price=");
            params.push_str(&format_decimal(p));
            if existing.order_type.requires_price() {
                params.push_str("&timeInForce=GTC");
            }
        }
        let body = self.signed_request(HttpMethod::Post, "/api/v3/order/cancelReplace", &params)?;
        let value: serde_json::Value = deserialize(&body)?;
        let new_order = value
            .get("newOrderResult")
            .ok_or_else(|| Error::Deserialization("missing newOrderResult".to_string()))?;
        let raw: RawOrder = serde_json::from_value(new_order.clone())
            .map_err(|e| Error::Deserialization(e.to_string()))?;
        order_from_raw(symbol.clone(), &raw)
    }

    /// Place several orders in one round-trip. Binance futures has a native batch
    /// endpoint (`POST /fapi/v1/batchOrders`); spot has none, so the orders are
    /// placed sequentially. Each order's own outcome is preserved.
    ///
    /// # Errors
    /// Returns an [`Error`] if the batch request itself fails.
    pub fn place_batch(&self, requests: &[OrderRequest]) -> Result<Vec<Result<Order>>> {
        if self.is_futures() {
            let items = requests
                .iter()
                .map(|request| batch_order_json(request, self.position_mode))
                .collect::<Result<Vec<_>>>()?
                .join(",");
            let params = format!("batchOrders={}", percent_encode(&format!("[{items}]")));
            let body = self.signed_request(HttpMethod::Post, "/fapi/v1/batchOrders", &params)?;
            let arr: Vec<serde_json::Value> = deserialize(&body)?;
            return Ok(arr.iter().map(batch_element_to_order).collect());
        }
        Ok(requests.iter().map(|r| self.place_order(r)).collect())
    }

    /// Cancel several orders on one `symbol` in a single round-trip. Binance
    /// futures has a native batch cancel (`DELETE /fapi/v1/batchOrders`); spot has
    /// none, so the ids are cancelled sequentially.
    ///
    /// # Errors
    /// Returns an [`Error`] if the request fails.
    pub fn cancel_batch(&self, symbol: &Symbol, order_ids: &[String]) -> Result<()> {
        if self.is_futures() {
            let list = order_ids
                .iter()
                .map(|id| format!("\"{id}\""))
                .collect::<Vec<_>>()
                .join(",");
            let params = format!(
                "symbol={}&orderIdList={}",
                Self::wire_symbol(symbol),
                percent_encode(&format!("[{list}]")),
            );
            self.signed_request(HttpMethod::Delete, "/fapi/v1/batchOrders", &params)?;
            return Ok(());
        }
        for id in order_ids {
            self.cancel_order(symbol, id)?;
        }
        Ok(())
    }

    /// Place a one-cancels-other bracket (`POST /api/v3/order/oco`), returning the
    /// two order legs. OCO is a spot order-list; Binance USDⓈ-M futures has no
    /// order-list, so this returns an [`Error::Exchange`] on a futures client.
    ///
    /// # Errors
    /// Returns an [`Error`] if the OCO is invalid, unsupported on this market, or rejected.
    pub fn place_oco(&self, request: &OcoRequest) -> Result<Vec<Order>> {
        request.validate()?;
        if self.is_futures() {
            return Err(Error::Exchange {
                code: "unsupported".to_string(),
                message: "Binance USD-M futures has no OCO order-list; use separate \
                          take-profit / stop orders"
                    .to_string(),
            });
        }
        let mut params = format!(
            "symbol={}&side={}&quantity={}&price={}&stopPrice={}",
            Self::wire_symbol(&request.symbol),
            side_str(request.side),
            format_decimal(request.quantity),
            format_decimal(request.price),
            format_decimal(request.stop_price),
        );
        if let Some(slp) = request.stop_limit_price {
            params.push_str("&stopLimitPrice=");
            params.push_str(&format_decimal(slp));
            params.push_str("&stopLimitTimeInForce=GTC");
        }
        if let Some(id) = &request.client_order_id {
            params.push_str("&listClientOrderId=");
            params.push_str(id);
        }
        let body = self.signed_request(HttpMethod::Post, "/api/v3/order/oco", &params)?;
        let value: serde_json::Value = deserialize(&body)?;
        let reports = value
            .get("orderReports")
            .and_then(serde_json::Value::as_array)
            .ok_or_else(|| Error::Deserialization("missing orderReports".to_string()))?;
        reports
            .iter()
            .map(|report| {
                let raw: RawOrder = serde_json::from_value(report.clone())
                    .map_err(|e| Error::Deserialization(e.to_string()))?;
                order_from_raw(request.symbol.clone(), &raw)
            })
            .collect()
    }

    /// Place an order over the Binance WebSocket API (`order.place`). Builds and
    /// signs the request params exactly like the REST path, wraps them in a
    /// `{id, method, params}` frame, sends it on the lazily-opened `ws-api`
    /// connection and parses the response.
    ///
    /// # Errors
    /// Returns [`Error::NotConnected`] if no WebSocket transport is configured, or
    /// another [`Error`] if the order is invalid or rejected.
    pub fn place_order_ws(&mut self, request: &OrderRequest) -> Result<Order> {
        request.validate()?;
        let type_str = type_for(request)?;
        let mut params = vec![
            ("symbol".to_string(), Self::wire_symbol(&request.symbol)),
            ("side".to_string(), side_str(request.side).to_string()),
            ("type".to_string(), type_str.to_string()),
            ("quantity".to_string(), format_decimal(request.quantity)),
        ];
        if let Some(price) = request.price {
            params.push(("price".to_string(), format_decimal(price)));
        }
        if let Some(stop) = request.stop_price {
            params.push(("stopPrice".to_string(), format_decimal(stop)));
        }
        if matches!(type_str, "LIMIT" | "STOP_LOSS_LIMIT" | "TAKE_PROFIT_LIMIT") {
            params.push((
                "timeInForce".to_string(),
                tif_str(request.time_in_force).to_string(),
            ));
        }
        if let Some(id) = &request.client_order_id {
            params.push(("newClientOrderId".to_string(), id.clone()));
        }
        if let Some(mode) = stp_str(request.stp) {
            params.push(("selfTradePreventionMode".to_string(), mode.to_string()));
        }
        // The ws-api connection goes to ws-fapi on a futures client, so the
        // position fields are named here exactly as on the REST path -- and
        // resolved by the same function, so the two cannot drift again.
        for (key, value) in self.position_fields(request)? {
            params.push((key.to_string(), value));
        }
        let result = self.ws_request("order.place", params)?;
        let raw: RawOrder =
            serde_json::from_value(result).map_err(|e| Error::Deserialization(e.to_string()))?;
        order_from_raw(request.symbol.clone(), &raw)
    }

    /// Cancel an order over the Binance WebSocket API (`order.cancel`).
    ///
    /// # Errors
    /// Returns [`Error::NotConnected`] if no WebSocket transport is configured, or
    /// another [`Error`] if the order is unknown or the request fails.
    pub fn cancel_order_ws(&mut self, symbol: &Symbol, order_id: &str) -> Result<()> {
        let params = vec![
            ("symbol".to_string(), Self::wire_symbol(symbol)),
            ("orderId".to_string(), order_id.to_string()),
        ];
        self.ws_request("order.cancel", params)?;
        Ok(())
    }

    /// Open the private user-data stream. Creates a listen key over REST
    /// (`POST /api/v3/userDataStream` for spot, `POST /fapi/v1/listenKey` for
    /// futures — both keyed but unsigned), then opens `wss://.../ws/<listenKey>`.
    /// Afterwards [`poll_events`](Self::poll_events) also surfaces the account's
    /// own [`Event::OrderUpdate`] and [`Event::BalanceUpdate`].
    ///
    /// The listen key expires after 60 minutes without a keepalive `PUT`; call
    /// [`keepalive_user_data`](Self::keepalive_user_data) periodically to refresh
    /// it. A dropped stream is re-subscribed automatically on the next
    /// [`poll_events`](Self::poll_events).
    ///
    /// # Errors
    /// Returns [`Error::InvalidCredentials`] without an API key, [`Error::NotConnected`]
    /// without a WebSocket transport, or another [`Error`] if the request fails.
    pub fn subscribe_user_data(&mut self) -> Result<()> {
        self.ensure_market_is_routed()?;
        let creds = self.credentials.as_ref().ok_or(Error::InvalidCredentials(
            "user-data stream requires credentials",
        ))?;
        let request = HttpRequest::new(
            HttpMethod::Post,
            format!("{}{}", self.rest_base, self.listen_key_path()),
        )
        .with_header("X-MBX-APIKEY", creds.api_key.clone());
        let response = self.http.execute(&request)?;
        if !response.is_success() {
            return Err(map_error(&response));
        }
        let value: serde_json::Value = serde_json::from_str(&response.body)
            .map_err(|e| Error::Deserialization(e.to_string()))?;
        let listen_key = value
            .get("listenKey")
            .and_then(serde_json::Value::as_str)
            .ok_or_else(|| Error::Deserialization("missing listenKey".to_string()))?
            .to_string();
        let ws = self.ws.as_ref().ok_or(Error::NotConnected)?;
        let stream_url = format!(
            "{}/{listen_key}",
            ws_base_url(self.market_type, self.testnet)
        );
        self.user_data_connection = Some(ws.connect(&stream_url)?);
        self.user_data_listen_key = Some(listen_key);
        self.user_data_active = true;
        Ok(())
    }

    /// The REST path that mints / refreshes a listen key for this market type.
    fn listen_key_path(&self) -> &'static str {
        if self.is_futures() {
            "/fapi/v1/listenKey"
        } else {
            "/api/v3/userDataStream"
        }
    }

    /// Refresh the listen key so the private stream is not dropped after 60
    /// minutes of inactivity (`PUT` the listen-key endpoint). A no-op before
    /// [`subscribe_user_data`](Self::subscribe_user_data).
    ///
    /// # Errors
    /// Returns [`Error::InvalidCredentials`] without an API key, or another
    /// [`Error`] if the refresh request fails.
    pub fn keepalive_user_data(&mut self) -> Result<()> {
        self.ensure_market_is_routed()?;
        let Some(listen_key) = self.user_data_listen_key.clone() else {
            return Ok(());
        };
        let creds = self.credentials.as_ref().ok_or(Error::InvalidCredentials(
            "user-data stream requires credentials",
        ))?;
        // Spot refreshes a specific key by query param; futures refreshes the
        // account's single key with no param.
        let url = if self.is_futures() {
            format!("{}{}", self.rest_base, self.listen_key_path())
        } else {
            format!(
                "{}{}?listenKey={listen_key}",
                self.rest_base,
                self.listen_key_path()
            )
        };
        let request = HttpRequest::new(HttpMethod::Put, url)
            .with_header("X-MBX-APIKEY", creds.api_key.clone());
        let response = self.http.execute(&request)?;
        if response.is_success() {
            Ok(())
        } else {
            Err(map_error(&response))
        }
    }

    /// Sign `params`, wrap them in a `ws-api` request frame, send it on the
    /// dedicated connection and return the response `result`.
    fn ws_request(
        &mut self,
        method: &str,
        mut params: Vec<(String, String)>,
    ) -> Result<serde_json::Value> {
        self.ensure_market_is_routed()?;
        let creds = self.credentials.as_ref().ok_or(Error::InvalidCredentials(
            "signed endpoint requires credentials",
        ))?;
        let id = self.signed_now_ms();
        params.push(("apiKey".to_string(), creds.api_key.clone()));
        params.push(("timestamp".to_string(), id.to_string()));
        // Binance signs the request over the alphabetically-sorted params.
        params.sort_by(|a, b| a.0.cmp(&b.0));
        let query = params
            .iter()
            .map(|(k, v)| format!("{k}={v}"))
            .collect::<Vec<_>>()
            .join("&");
        let signature = hmac_sha256_hex(creds.api_secret.as_bytes(), query.as_bytes());
        params.push(("signature".to_string(), signature));
        let mut obj = serde_json::Map::new();
        for (k, v) in params {
            obj.insert(k, serde_json::Value::String(v));
        }
        let frame = serde_json::json!({ "id": id, "method": method, "params": obj }).to_string();
        // Open the ws-api connection on first use.
        if self.ws_api_connection.is_none() {
            let ws = self.ws.as_ref().ok_or(Error::NotConnected)?;
            let url = ws_api_url(self.market_type, self.testnet);
            self.ws_api_connection = Some(ws.connect(url)?);
        }
        let connection = self
            .ws_api_connection
            .as_mut()
            .expect("ws-api connection just ensured");
        connection.send(&frame)?;
        let Some(response) = connection.recv()? else {
            return Err(Error::NotConnected);
        };
        let value: serde_json::Value =
            serde_json::from_str(&response).map_err(|e| Error::Deserialization(e.to_string()))?;
        let status = value
            .get("status")
            .and_then(serde_json::Value::as_i64)
            .unwrap_or(0);
        if status == 200 {
            Ok(value
                .get("result")
                .cloned()
                .unwrap_or(serde_json::Value::Null))
        } else {
            let error = value.get("error");
            let code = error
                .and_then(|e| e.get("code"))
                .and_then(serde_json::Value::as_i64)
                .unwrap_or(status);
            let message = error
                .and_then(|e| e.get("msg"))
                .and_then(serde_json::Value::as_str)
                .unwrap_or("")
                .to_string();
            Err(Error::OrderRejected {
                code: code.to_string(),
                message,
            })
        }
    }
}

impl DerivativesStream for Binance {
    fn subscribe_derivatives(
        &mut self,
        symbol: &Symbol,
        channel: DerivativesChannel,
    ) -> Result<()> {
        Binance::subscribe_derivatives(self, symbol, channel)
    }
    fn open_interest(&mut self, symbol: &Symbol) -> Result<OpenInterest> {
        Binance::open_interest(self, symbol)
    }
    fn long_short_ratio(&mut self, symbol: &Symbol) -> Result<LongShortRatio> {
        Binance::long_short_ratio(self, symbol)
    }
}

impl WsExecution for Binance {
    fn place_order_ws(&mut self, request: &OrderRequest) -> Result<Order> {
        Binance::place_order_ws(self, request)
    }
    fn cancel_order_ws(&mut self, symbol: &Symbol, order_id: &str) -> Result<()> {
        Binance::cancel_order_ws(self, symbol, order_id)
    }
}

impl WsUserData for Binance {
    fn subscribe_user_data(&mut self) -> Result<()> {
        Binance::subscribe_user_data(self)
    }
    fn keepalive_user_data(&mut self) -> Result<()> {
        Binance::keepalive_user_data(self)
    }
}

impl Derivatives for Binance {
    fn positions(&mut self, symbol: Option<&Symbol>) -> Result<Vec<Position>> {
        Binance::positions(self, symbol)
    }
    fn set_leverage(&mut self, symbol: &Symbol, leverage: u32) -> Result<()> {
        Binance::set_leverage(self, symbol, leverage)
    }
    fn set_margin_mode(&mut self, symbol: &Symbol, mode: MarginMode) -> Result<()> {
        Binance::set_margin_mode(self, symbol, mode)
    }
    fn close_position(&mut self, symbol: &Symbol) -> Result<Order> {
        Binance::close_position(self, symbol)
    }
}

impl AdvancedOrders for Binance {
    fn amend_order(
        &mut self,
        symbol: &Symbol,
        order_id: &str,
        new_price: Option<Decimal>,
        new_quantity: Option<Decimal>,
    ) -> Result<Order> {
        Binance::amend_order(self, symbol, order_id, new_price, new_quantity)
    }
    fn place_batch(&mut self, requests: &[OrderRequest]) -> Result<Vec<Result<Order>>> {
        Binance::place_batch(self, requests)
    }
    fn cancel_batch(&mut self, symbol: &Symbol, order_ids: &[String]) -> Result<()> {
        Binance::cancel_batch(self, symbol, order_ids)
    }
    fn place_oco(&mut self, request: &OcoRequest) -> Result<Vec<Order>> {
        Binance::place_oco(self, request)
    }
}

/// Percent-encode per RFC 3986 (unreserved characters pass through), used for the
/// JSON `batchOrders`/`orderIdList` values in the futures batch endpoints.
fn percent_encode(s: &str) -> String {
    const HEX: &[u8; 16] = b"0123456789ABCDEF";
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(char::from(b));
            }
            _ => {
                out.push('%');
                out.push(char::from(HEX[(b >> 4) as usize]));
                out.push(char::from(HEX[(b & 0x0f) as usize]));
            }
        }
    }
    out
}

/// One element of a futures `batchOrders` JSON array.
fn batch_order_json(request: &OrderRequest, position_mode: PositionMode) -> Result<String> {
    let type_str = type_for(request)?;
    let mut obj = serde_json::json!({
        "symbol": Binance::wire_symbol(&request.symbol),
        "side": side_str(request.side),
        "type": type_str,
        "quantity": format_decimal(request.quantity),
    });
    if let Some(price) = request.price {
        obj["price"] = serde_json::json!(format_decimal(price));
    }
    // `LIMIT_MAKER` takes no time-in-force; `type_for` has already refused a
    // post-only order that asked for one.
    if request.order_type.requires_price() && type_str != "LIMIT_MAKER" {
        obj["timeInForce"] = serde_json::json!(tif_str(request.time_in_force));
    }
    if let Some(mode) = stp_str(request.stp) {
        obj["selfTradePreventionMode"] = serde_json::json!(mode);
    }
    if let Some(stop) = request.stop_price {
        obj["stopPrice"] = serde_json::json!(format_decimal(stop));
    }
    if let Some(id) = &request.client_order_id {
        obj["newClientOrderId"] = serde_json::json!(id);
    }
    // Only ever called on the futures batch endpoint, so the hedge rule applies
    // exactly as it does on the single-order path: name the side instead of
    // sending `reduceOnly`.
    if position_mode == PositionMode::Hedge {
        obj["positionSide"] = serde_json::json!(match PositionSide::for_order(
            request.side,
            request.reduce_only
        ) {
            PositionSide::Long => "LONG",
            PositionSide::Short => "SHORT",
        });
    } else if request.reduce_only {
        obj["reduceOnly"] = serde_json::json!("true");
    }
    Ok(obj.to_string())
}

/// A batch-order response element is either a placed order or a `{code, msg}`
/// rejection; map it onto that order's own [`Result`].
fn batch_element_to_order(value: &serde_json::Value) -> Result<Order> {
    if let Some(code) = value.get("code").and_then(serde_json::Value::as_i64) {
        let message = value
            .get("msg")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("")
            .to_string();
        return Err(Error::OrderRejected {
            code: code.to_string(),
            message,
        });
    }
    let raw: RawOrder =
        serde_json::from_value(value.clone()).map_err(|e| Error::Deserialization(e.to_string()))?;
    let symbol = split_wire_symbol(&raw.symbol);
    order_from_raw(symbol, &raw)
}

fn parse_positions(body: &str) -> Result<Vec<Position>> {
    let raw: Vec<RawPosition> = deserialize(body)?;
    let mut positions = Vec::new();
    for entry in raw {
        let amount = parse_decimal(&entry.position_amt)?;
        if amount.is_zero() {
            continue;
        }
        let side = if amount.is_sign_negative() {
            PositionSide::Short
        } else {
            PositionSide::Long
        };
        positions.push(Position {
            symbol: split_wire_symbol(&entry.symbol),
            side,
            quantity: amount.abs(),
            entry_price: parse_decimal(&entry.entry_price)?,
            mark_price: parse_decimal(&entry.mark_price)?,
            leverage: parse_decimal(&entry.leverage)?,
            unrealized_pnl: parse_decimal(&entry.unrealized)?,
            margin_mode: if entry.margin_type.eq_ignore_ascii_case("isolated") {
                MarginMode::Isolated
            } else {
                MarginMode::Cross
            },
        });
    }
    Ok(positions)
}

fn side_str(side: OrderSide) -> &'static str {
    match side {
        OrderSide::Buy => "BUY",
        OrderSide::Sell => "SELL",
    }
}

fn order_type_str(order_type: OrderType) -> &'static str {
    match order_type {
        OrderType::Market => "MARKET",
        OrderType::Limit => "LIMIT",
        OrderType::StopMarket => "STOP_LOSS",
        OrderType::StopLimit => "STOP_LOSS_LIMIT",
    }
}

/// The Binance order `type` for a request. `LIMIT_MAKER` is how Binance spells
/// post-only, and it accepts no `timeInForce` at all -- so a post-only order
/// carrying an IOC or FOK is refused rather than sent as the `LIMIT_MAKER` whose
/// time-in-force silently went missing.
fn type_for(request: &OrderRequest) -> Result<&'static str> {
    // Only the limit-shaped types take a `timeInForce`; `MARKET` rejects the
    // parameter (-1106). A market order is immediate anyway, so GTC (the
    // default) and IOC describe what it already does -- but FOK is a different
    // instruction, and letting it through would leave a partial fill standing
    // where the caller asked for all-or-nothing.
    if !request.order_type.requires_price() && request.time_in_force == TimeInForce::Fok {
        return Err(Error::unsupported_field(
            "Binance",
            "a FOK time-in-force on a market order",
            "Binance accepts timeInForce only on the limit order types",
        ));
    }
    if request.post_only && request.order_type == OrderType::Limit {
        if request.time_in_force != TimeInForce::Gtc {
            return Err(Error::unsupported_field(
                "Binance",
                "post_only together with a non-GTC time-in-force",
                "`LIMIT_MAKER` is Binance's post-only type and accepts no timeInForce",
            ));
        }
        return Ok("LIMIT_MAKER");
    }
    Ok(order_type_str(request.order_type))
}

fn tif_str(tif: TimeInForce) -> &'static str {
    match tif {
        TimeInForce::Gtc => "GTC",
        TimeInForce::Ioc => "IOC",
        TimeInForce::Fok => "FOK",
    }
}

/// The Binance `selfTradePreventionMode` value, or `None` for no STP.
fn stp_str(stp: SelfTradePrevention) -> Option<&'static str> {
    match stp {
        SelfTradePrevention::None => None,
        SelfTradePrevention::ExpireMaker => Some("EXPIRE_MAKER"),
        SelfTradePrevention::ExpireTaker => Some("EXPIRE_TAKER"),
        SelfTradePrevention::ExpireBoth => Some("EXPIRE_BOTH"),
    }
}

fn parse_side(raw: &str) -> Result<OrderSide> {
    match raw {
        "BUY" => Ok(OrderSide::Buy),
        "SELL" => Ok(OrderSide::Sell),
        other => Err(Error::Deserialization(format!("unknown side {other:?}"))),
    }
}

fn parse_order_type(raw: &str) -> Result<OrderType> {
    match raw {
        "MARKET" => Ok(OrderType::Market),
        "LIMIT" | "LIMIT_MAKER" => Ok(OrderType::Limit),
        "STOP_LOSS" | "TAKE_PROFIT" => Ok(OrderType::StopMarket),
        "STOP_LOSS_LIMIT" | "TAKE_PROFIT_LIMIT" => Ok(OrderType::StopLimit),
        other => Err(Error::Deserialization(format!(
            "unknown order type {other:?}"
        ))),
    }
}

fn parse_status(raw: &str) -> Result<OrderStatus> {
    match raw {
        "NEW" => Ok(OrderStatus::New),
        "PARTIALLY_FILLED" => Ok(OrderStatus::PartiallyFilled),
        "FILLED" => Ok(OrderStatus::Filled),
        "CANCELED" | "PENDING_CANCEL" => Ok(OrderStatus::Canceled),
        "REJECTED" => Ok(OrderStatus::Rejected),
        "EXPIRED" | "EXPIRED_IN_MATCH" => Ok(OrderStatus::Expired),
        other => Err(Error::Deserialization(format!("unknown status {other:?}"))),
    }
}

fn parse_order(symbol: &Symbol, body: &str) -> Result<Order> {
    let raw: RawOrder = deserialize(body)?;
    order_from_raw(symbol.clone(), &raw)
}

fn order_from_raw(symbol: Symbol, raw: &RawOrder) -> Result<Order> {
    let executed = parse_decimal(&raw.executed_qty)?;
    // Futures reports the fill price directly as `avgPrice`; spot reports the
    // cumulative quote quantity, from which the average is derived.
    let avg = parse_decimal(&raw.avg_price).unwrap_or(Decimal::ZERO);
    let average_price = if avg > Decimal::ZERO {
        Some(avg)
    } else if executed > Decimal::ZERO && !raw.cummulative_quote_qty.is_empty() {
        Some(parse_decimal(&raw.cummulative_quote_qty)? / executed)
    } else {
        None
    };
    let parsed_price = parse_decimal(&raw.price)?;
    let price = (parsed_price > Decimal::ZERO).then_some(parsed_price);
    Ok(Order {
        id: raw.order_id.to_string(),
        client_order_id: (!raw.client_order_id.is_empty()).then(|| raw.client_order_id.clone()),
        symbol,
        side: parse_side(&raw.side)?,
        order_type: parse_order_type(&raw.order_type)?,
        status: parse_status(&raw.status)?,
        quantity: parse_decimal(&raw.orig_qty)?,
        filled_quantity: executed,
        price,
        average_price,
    })
}

/// Quote assets used to split a concatenated wire symbol (`BTCUSDT` -> `BTC/USDT`)
/// when the venue reports only the wire form. Longer quotes are tried first.
const KNOWN_QUOTES: &[&str] = &[
    "FDUSD", "USDT", "USDC", "TUSD", "BUSD", "DAI", "EUR", "TRY", "BTC", "ETH", "BNB", "USD",
];

/// Map a concatenated Binance wire symbol back to a canonical [`Symbol`] using
/// the known quote-asset suffixes. Falls back to the whole string as the base.
fn split_wire_symbol(wire: &str) -> Symbol {
    for quote in KNOWN_QUOTES {
        if let Some(base) = wire.strip_suffix(quote) {
            if !base.is_empty() {
                return Symbol::new(base, *quote);
            }
        }
    }
    Symbol::new(wire, "")
}

fn field_str<'a>(value: &'a serde_json::Value, key: &str) -> Result<&'a str> {
    value
        .get(key)
        .and_then(serde_json::Value::as_str)
        .ok_or_else(|| Error::Deserialization(format!("missing string field {key:?}")))
}

fn parse_ws_levels(value: Option<&serde_json::Value>) -> Result<Vec<BookLevel>> {
    let array = value
        .and_then(serde_json::Value::as_array)
        .ok_or_else(|| Error::Deserialization("missing depth levels".to_string()))?;
    array
        .iter()
        .map(|level| {
            let pair = level
                .as_array()
                .ok_or_else(|| Error::Deserialization("depth level not an array".to_string()))?;
            let price = parse_decimal(
                pair.first()
                    .and_then(serde_json::Value::as_str)
                    .ok_or_else(|| Error::Deserialization("depth price missing".to_string()))?,
            )?;
            let quantity =
                parse_decimal(pair.get(1).and_then(serde_json::Value::as_str).ok_or_else(
                    || Error::Deserialization("depth quantity missing".to_string()),
                )?)?;
            Ok(BookLevel { price, quantity })
        })
        .collect()
}

/// Parse one Binance WebSocket frame into the derivatives events the caller
/// subscribed to.
///
/// Returns a `Vec` rather than an `Option` because `markPrice` is one frame
/// answering two possible subscriptions: it carries the funding rate, the mark
/// price and the index price together. A client subscribed to both channels gets
/// both prints from it; one subscribed to neither gets nothing, since emitting a
/// print nobody asked for would put a figure into the stream that the caller has
/// no reason to expect.
fn parse_derivatives_message(
    text: &str,
    resolve: &impl Fn(&str) -> Symbol,
    channels: &[(String, DerivativesChannel)],
) -> Vec<Event> {
    let Ok(value) = serde_json::from_str::<serde_json::Value>(text) else {
        return Vec::new();
    };
    let data = value.get("data").unwrap_or(&value);
    let Some(event_type) = data.get("e").and_then(serde_json::Value::as_str) else {
        return Vec::new();
    };
    let subscribed = |wire: &str, channel: DerivativesChannel| {
        channels.iter().any(|(w, c)| w == wire && *c == channel)
    };
    let mut out = Vec::new();
    match event_type {
        "markPriceUpdate" => {
            let Ok(wire) = field_str(data, "s") else {
                return out;
            };
            let symbol = resolve(wire);
            let timestamp = data
                .get("E")
                .and_then(serde_json::Value::as_i64)
                .unwrap_or(0);
            let mark = field_str(data, "p")
                .ok()
                .and_then(|p| parse_decimal(p).ok());
            let Some(mark_price) = mark else {
                return out;
            };
            if subscribed(wire, DerivativesChannel::Funding) {
                if let Some(rate) = field_str(data, "r")
                    .ok()
                    .and_then(|r| parse_decimal(r).ok())
                {
                    out.push(Event::Derivatives(DerivativesFeed::Funding(FundingRate {
                        symbol: symbol.clone(),
                        rate,
                        mark_price,
                        timestamp,
                    })));
                }
            }
            if subscribed(wire, DerivativesChannel::MarkIndex) {
                if let Some(index_price) = field_str(data, "i")
                    .ok()
                    .and_then(|i| parse_decimal(i).ok())
                {
                    out.push(Event::Derivatives(DerivativesFeed::MarkIndex(MarkIndex {
                        symbol,
                        mark_price,
                        index_price,
                        timestamp,
                    })));
                }
            }
        }
        "forceOrder" => {
            // The liquidation payload is nested under `o`.
            let Some(order) = data.get("o") else {
                return out;
            };
            let Ok(wire) = field_str(order, "s") else {
                return out;
            };
            if !subscribed(wire, DerivativesChannel::Liquidations) {
                return out;
            }
            // `S` is the side of the forced order hitting the book: a liquidated
            // long is sold, a liquidated short is bought.
            let side = match order.get("S").and_then(serde_json::Value::as_str) {
                Some("SELL") => OrderSide::Sell,
                Some("BUY") => OrderSide::Buy,
                _ => return out,
            };
            let (Ok(price), Ok(quantity)) = (
                field_str(order, "p").and_then(parse_decimal),
                field_str(order, "q").and_then(parse_decimal),
            ) else {
                return out;
            };
            out.push(Event::Derivatives(DerivativesFeed::Liquidation(
                Liquidation {
                    symbol: resolve(wire),
                    side,
                    price,
                    quantity,
                    timestamp: order
                        .get("T")
                        .and_then(serde_json::Value::as_i64)
                        .unwrap_or(0),
                },
            )));
        }
        _ => {}
    }
    out
}

/// Parse one Binance WebSocket frame into an [`Event`], resolving the wire
/// symbol with `resolve`. Non-data frames (subscription acks) and unhandled
/// event types return `Ok(None)`.
fn parse_ws_message(text: &str, resolve: &impl Fn(&str) -> Symbol) -> Result<Option<Event>> {
    let value: serde_json::Value =
        serde_json::from_str(text).map_err(|e| Error::Deserialization(e.to_string()))?;
    // A combined stream wraps the payload as {"stream":..,"data":..}.
    let data = value.get("data").unwrap_or(&value);
    let Some(event_type) = data.get("e").and_then(serde_json::Value::as_str) else {
        return Ok(None);
    };
    match event_type {
        "trade" => {
            // `m` = "is the buyer the market maker?"; if so the taker (aggressor)
            // is the seller.
            let is_maker_buyer = data.get("m").and_then(serde_json::Value::as_bool) == Some(true);
            Ok(Some(Event::Trade(TradePrint {
                symbol: resolve(field_str(data, "s")?),
                price: parse_decimal(field_str(data, "p")?)?,
                quantity: parse_decimal(field_str(data, "q")?)?,
                aggressor: if is_maker_buyer {
                    OrderSide::Sell
                } else {
                    OrderSide::Buy
                },
                timestamp: data
                    .get("T")
                    .and_then(serde_json::Value::as_i64)
                    .unwrap_or(0),
            })))
        }
        "depthUpdate" => Ok(Some(Event::BookDelta(BookDelta {
            symbol: resolve(field_str(data, "s")?),
            first_update_id: data
                .get("U")
                .and_then(serde_json::Value::as_u64)
                .unwrap_or(0),
            final_update_id: data
                .get("u")
                .and_then(serde_json::Value::as_u64)
                .unwrap_or(0),
            bids: parse_ws_levels(data.get("b"))?,
            asks: parse_ws_levels(data.get("a"))?,
            timestamp: data
                .get("E")
                .and_then(serde_json::Value::as_i64)
                .unwrap_or(0),
        }))),
        "24hrTicker" => Ok(Some(Event::Ticker(Ticker {
            symbol: resolve(field_str(data, "s")?),
            last: parse_decimal(field_str(data, "c")?)?,
            bid: parse_decimal(field_str(data, "b")?)?,
            ask: parse_decimal(field_str(data, "a")?)?,
            volume: parse_decimal(field_str(data, "v")?)?,
            timestamp: data
                .get("E")
                .and_then(serde_json::Value::as_i64)
                .unwrap_or(0),
        }))),
        // Private user-data frames. The wire symbol is split directly (the
        // user-data stream carries no public subscription to resolve against).
        "executionReport" => {
            let symbol = split_wire_symbol(field_str(data, "s")?);
            Ok(Some(Event::OrderUpdate(order_from_user_stream(
                symbol, data, false,
            )?)))
        }
        "outboundAccountPosition" => Ok(Some(Event::BalanceUpdate(parse_stream_balances(
            data, "f", "l",
        )?))),
        "ORDER_TRADE_UPDATE" => {
            let order = data
                .get("o")
                .ok_or_else(|| Error::Deserialization("missing order payload 'o'".to_string()))?;
            let symbol = split_wire_symbol(field_str(order, "s")?);
            Ok(Some(Event::OrderUpdate(order_from_user_stream(
                symbol, order, true,
            )?)))
        }
        "ACCOUNT_UPDATE" => {
            let account = data
                .get("a")
                .ok_or_else(|| Error::Deserialization("missing account payload 'a'".to_string()))?;
            // Futures reports a wallet balance `wb`; there is no separate locked
            // amount, so the free balance carries the wallet balance.
            Ok(Some(Event::BalanceUpdate(parse_stream_balances(
                account, "wb", "",
            )?)))
        }
        _ => Ok(None),
    }
}

/// Build an [`Order`] from a spot `executionReport` or a futures
/// `ORDER_TRADE_UPDATE` order payload. The field names are shared; futures
/// reports the average fill price directly as `ap`, while spot derives it from
/// the cumulative quote `Z` over the cumulative filled quantity `z`.
fn order_from_user_stream(
    symbol: Symbol,
    order: &serde_json::Value,
    futures: bool,
) -> Result<Order> {
    let executed = parse_decimal(field_str(order, "z")?)?;
    let average_price = if futures {
        let ap = parse_decimal(field_str(order, "ap")?).unwrap_or(Decimal::ZERO);
        (ap > Decimal::ZERO).then_some(ap)
    } else {
        let cum_quote = order
            .get("Z")
            .and_then(serde_json::Value::as_str)
            .map_or(Ok(Decimal::ZERO), parse_decimal)?;
        (executed > Decimal::ZERO && cum_quote > Decimal::ZERO).then(|| cum_quote / executed)
    };
    let parsed_price = parse_decimal(field_str(order, "p")?)?;
    let price = (parsed_price > Decimal::ZERO).then_some(parsed_price);
    let order_id = order
        .get("i")
        .and_then(serde_json::Value::as_i64)
        .ok_or_else(|| Error::Deserialization("missing order id 'i'".to_string()))?;
    let client_id = order
        .get("c")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("");
    Ok(Order {
        id: order_id.to_string(),
        client_order_id: (!client_id.is_empty()).then(|| client_id.to_string()),
        symbol,
        side: parse_side(field_str(order, "S")?)?,
        order_type: parse_order_type(field_str(order, "o")?)?,
        status: parse_status(field_str(order, "X")?)?,
        quantity: parse_decimal(field_str(order, "q")?)?,
        filled_quantity: executed,
        price,
        average_price,
    })
}

/// Parse a user-data balance array `B` of `{a, <free_key>, <locked_key>}` into
/// [`Balance`]s. An empty `locked_key` treats the locked amount as zero (futures
/// reports only a wallet balance).
fn parse_stream_balances(
    payload: &serde_json::Value,
    free_key: &str,
    locked_key: &str,
) -> Result<Vec<Balance>> {
    let array = payload
        .get("B")
        .and_then(serde_json::Value::as_array)
        .ok_or_else(|| Error::Deserialization("missing balances 'B'".to_string()))?;
    array
        .iter()
        .map(|balance| {
            let locked = if locked_key.is_empty() {
                Decimal::ZERO
            } else {
                parse_decimal(field_str(balance, locked_key)?)?
            };
            Ok(Balance {
                asset: field_str(balance, "a")?.to_string(),
                free: parse_decimal(field_str(balance, free_key)?)?,
                locked,
            })
        })
        .collect()
}

/// The REST base URL for a market type and network.
fn rest_base_url(market_type: MarketType, testnet: bool) -> &'static str {
    match (market_type, testnet) {
        (MarketType::UsdMFutures, false) => "https://fapi.binance.com",
        (MarketType::UsdMFutures, true) => "https://testnet.binancefuture.com",
        (_, true) => "https://testnet.binance.vision",
        (_, false) => "https://api.binance.com",
    }
}

/// The WebSocket base URL for a market type and network.
fn ws_base_url(market_type: MarketType, testnet: bool) -> &'static str {
    match (market_type, testnet) {
        (MarketType::UsdMFutures, false) => "wss://fstream.binance.com/ws",
        (MarketType::UsdMFutures, true) => "wss://stream.binancefuture.com/ws",
        (_, true) => "wss://testnet.binance.vision/ws",
        (_, false) => "wss://stream.binance.com:9443/ws",
    }
}

/// The WebSocket order-API (`ws-api`) URL for a market type and network.
fn ws_api_url(market_type: MarketType, testnet: bool) -> &'static str {
    match (market_type, testnet) {
        (MarketType::UsdMFutures, false) => "wss://ws-fapi.binance.com/ws-fapi/v1",
        (MarketType::UsdMFutures, true) => "wss://testnet.binancefuture.com/ws-fapi/v1",
        (_, true) => "wss://ws-api.testnet.binance.vision/ws-api/v3",
        (_, false) => "wss://ws-api.binance.com:443/ws-api/v3",
    }
}

#[derive(Deserialize)]
struct RawTicker {
    #[serde(rename = "lastPrice")]
    last_price: String,
    #[serde(rename = "bidPrice")]
    bid_price: String,
    #[serde(rename = "askPrice")]
    ask_price: String,
    volume: String,
    /// Close time of the rolling window, which is the venue's own "as of".
    #[serde(rename = "closeTime", default)]
    close_time: i64,
}

#[derive(Deserialize)]
struct RawDepth {
    #[serde(rename = "lastUpdateId")]
    last_update_id: u64,
    bids: Vec<[String; 2]>,
    asks: Vec<[String; 2]>,
    /// Futures depth carries the venue's transaction time; spot depth carries
    /// no timestamp at all, so it stays `0` rather than being invented here.
    #[serde(rename = "T", default)]
    transaction_time: i64,
}

#[derive(Deserialize)]
struct BinanceError {
    code: i64,
    msg: String,
}

#[derive(Deserialize)]
struct RawOrder {
    #[serde(default)]
    symbol: String,
    #[serde(rename = "orderId")]
    order_id: u64,
    #[serde(rename = "clientOrderId", default)]
    client_order_id: String,
    side: String,
    #[serde(rename = "type")]
    order_type: String,
    status: String,
    #[serde(rename = "origQty")]
    orig_qty: String,
    #[serde(rename = "executedQty")]
    executed_qty: String,
    #[serde(rename = "cummulativeQuoteQty", default)]
    cummulative_quote_qty: String,
    #[serde(rename = "avgPrice", default)]
    avg_price: String,
    price: String,
}

#[derive(Deserialize)]
struct RawAccount {
    balances: Vec<RawBalance>,
}

#[derive(Deserialize)]
struct RawBalance {
    asset: String,
    free: String,
    locked: String,
}

#[derive(Deserialize)]
struct RawFuturesTicker {
    #[serde(rename = "lastPrice")]
    last_price: String,
    volume: String,
    #[serde(rename = "closeTime", default)]
    close_time: i64,
}

#[derive(Deserialize)]
struct RawBookTicker {
    #[serde(rename = "bidPrice")]
    bid_price: String,
    #[serde(rename = "askPrice")]
    ask_price: String,
}

#[derive(Deserialize)]
struct RawFuturesBalance {
    asset: String,
    balance: String,
    #[serde(rename = "availableBalance")]
    available_balance: String,
}

#[derive(Deserialize)]
struct RawPosition {
    symbol: String,
    #[serde(rename = "positionAmt")]
    position_amt: String,
    #[serde(rename = "entryPrice")]
    entry_price: String,
    #[serde(rename = "markPrice")]
    mark_price: String,
    #[serde(rename = "unRealizedProfit")]
    unrealized: String,
    leverage: String,
    #[serde(rename = "marginType")]
    margin_type: String,
}

/// `GET /api/v3/time` (spot) / `/fapi/v1/time` (futures).
/// Verified against the live endpoint: `{"serverTime":1788295956083}`.
#[derive(Deserialize)]
struct RawServerTime {
    #[serde(rename = "serverTime")]
    server_time: i64,
}

#[derive(Deserialize)]
struct RawExchangeInfo {
    symbols: Vec<RawSymbol>,
}

#[derive(Deserialize)]
struct RawSymbol {
    #[serde(rename = "baseAsset")]
    base_asset: String,
    #[serde(rename = "quoteAsset")]
    quote_asset: String,
    #[serde(rename = "baseAssetPrecision", default)]
    base_asset_precision: u32,
    #[serde(rename = "quoteAssetPrecision", default)]
    quote_asset_precision: u32,
    #[serde(default)]
    filters: Vec<serde_json::Value>,
}

fn find_filter<'a>(filters: &'a [serde_json::Value], kind: &str) -> Option<&'a serde_json::Value> {
    filters
        .iter()
        .find(|f| f.get("filterType").and_then(serde_json::Value::as_str) == Some(kind))
}

fn filter_decimal(filter: Option<&serde_json::Value>, key: &str) -> Decimal {
    filter
        .and_then(|f| f.get(key))
        .and_then(serde_json::Value::as_str)
        .and_then(|s| parse_decimal(s).ok())
        .unwrap_or(Decimal::ZERO)
}

fn parse_instrument(raw: &RawSymbol) -> Instrument {
    let lot = find_filter(&raw.filters, "LOT_SIZE");
    let price = find_filter(&raw.filters, "PRICE_FILTER");
    let notional =
        find_filter(&raw.filters, "NOTIONAL").or_else(|| find_filter(&raw.filters, "MIN_NOTIONAL"));
    Instrument {
        symbol: Symbol::new(&raw.base_asset, &raw.quote_asset),
        base_precision: raw.base_asset_precision,
        quote_precision: raw.quote_asset_precision,
        filters: InstrumentFilters {
            min_quantity: filter_decimal(lot, "minQty"),
            max_quantity: filter_decimal(lot, "maxQty"),
            step_size: filter_decimal(lot, "stepSize"),
            min_price: filter_decimal(price, "minPrice"),
            max_price: filter_decimal(price, "maxPrice"),
            tick_size: filter_decimal(price, "tickSize"),
            min_notional: filter_decimal(notional, "minNotional"),
        },
    }
}

fn deserialize<T: for<'de> Deserialize<'de>>(body: &str) -> Result<T> {
    serde_json::from_str(body).map_err(|e| Error::Deserialization(e.to_string()))
}

fn parse_levels(levels: &[[String; 2]]) -> Result<Vec<BookLevel>> {
    levels
        .iter()
        .map(|[price, qty]| {
            Ok(BookLevel {
                price: parse_decimal(price)?,
                quantity: parse_decimal(qty)?,
            })
        })
        .collect()
}

fn parse_kline_row(row: &[serde_json::Value]) -> Result<Candle> {
    // Binance kline: [openTime, open, high, low, close, volume, closeTime, ...].
    if row.len() < 6 {
        return Err(Error::Deserialization("kline row too short".to_string()));
    }
    let open_time = row[0]
        .as_i64()
        .ok_or_else(|| Error::Deserialization("kline open time not an integer".to_string()))?;
    let open = kline_f64(&row[1])?;
    let high = kline_f64(&row[2])?;
    let low = kline_f64(&row[3])?;
    let close = kline_f64(&row[4])?;
    let volume = kline_f64(&row[5])?;
    Candle::new(open, high, low, close, volume, open_time)
        .map_err(|e| Error::Deserialization(e.to_string()))
}

fn kline_f64(value: &serde_json::Value) -> Result<f64> {
    value
        .as_str()
        .ok_or_else(|| Error::Deserialization("kline field not a string".to_string()))?
        .parse::<f64>()
        .map_err(|e| Error::Deserialization(format!("kline field not a number: {e}")))
}

/// Map a non-success Binance response onto the unified error taxonomy.
fn map_error(response: &HttpResponse) -> Error {
    let Ok(err) = serde_json::from_str::<BinanceError>(&response.body) else {
        return Error::Exchange {
            code: response.status.to_string(),
            message: response.body.clone(),
        };
    };
    match err.code {
        -1121 => Error::InvalidSymbol(err.msg),
        -2010 | -2018 | -2019 => Error::InsufficientBalance,
        -1003 => Error::RateLimited {
            retry_after: response.retry_after(),
        },
        -1022 | -2014 | -2015 => Error::Auth(err.msg),
        _ => Error::Exchange {
            code: err.code.to_string(),
            message: err.msg,
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::transport::{MockHttpTransport, MockWsTransport};
    use rust_decimal_macros::dec;
    use std::sync::Arc;

    /// A `WsTransport` that forwards to a shared `MockWsTransport`, so a test
    /// keeps a handle after the client takes ownership.
    struct ArcWs(Arc<MockWsTransport>);
    impl WsTransport for ArcWs {
        fn connect(&self, url: &str) -> Result<Box<dyn WsConnection>> {
            self.0.connect(url)
        }
    }

    fn symbol() -> Symbol {
        Symbol::new("BTC", "USDT")
    }

    /// A Binance client over a mock transport, returning the mock so the test can
    /// queue responses and inspect requests.
    fn client(market_type: MarketType, testnet: bool) -> (Binance, Arc<MockHttpTransport>) {
        let mock = Arc::new(MockHttpTransport::new());
        let opts = if testnet {
            ExchangeOptions::testnet(market_type)
        } else {
            ExchangeOptions::mainnet(market_type)
        };
        let binance = Binance::with_http(Box::new(ArcTransport(Arc::clone(&mock))), &opts);
        (binance, mock)
    }

    /// A transport that forwards to a shared `MockHttpTransport` so the test keeps
    /// a handle after the client takes ownership.
    struct ArcTransport(Arc<MockHttpTransport>);
    impl HttpTransport for ArcTransport {
        fn execute(&self, request: &HttpRequest) -> Result<HttpResponse> {
            self.0.execute(request)
        }
    }

    #[test]
    fn wire_symbol_concatenates() {
        assert_eq!(Binance::wire_symbol(&symbol()), "BTCUSDT");
    }

    #[test]
    fn rest_base_urls_by_market_and_network() {
        assert_eq!(
            rest_base_url(MarketType::Spot, false),
            "https://api.binance.com"
        );
        assert_eq!(
            rest_base_url(MarketType::Spot, true),
            "https://testnet.binance.vision"
        );
        assert_eq!(
            rest_base_url(MarketType::UsdMFutures, false),
            "https://fapi.binance.com"
        );
        assert_eq!(
            rest_base_url(MarketType::UsdMFutures, true),
            "https://testnet.binancefuture.com"
        );
    }

    #[test]
    fn ticker_parses_and_targets_the_right_url() {
        let (binance, mock) = client(MarketType::Spot, false);
        assert_eq!(binance.market_type(), MarketType::Spot);
        mock.push_json(
            200,
            r#"{"lastPrice":"20000.50","bidPrice":"20000.00","askPrice":"20001.00","volume":"1234.5"}"#,
        );
        let ticker = binance.ticker(&symbol()).unwrap();
        assert_eq!(ticker.last, dec!(20000.50));
        assert_eq!(ticker.bid, dec!(20000.00));
        assert_eq!(ticker.ask, dec!(20001.00));
        assert_eq!(ticker.volume, dec!(1234.5));

        let req = &mock.recorded_requests()[0];
        assert_eq!(
            req.url,
            "https://api.binance.com/api/v3/ticker/24hr?symbol=BTCUSDT"
        );
    }

    #[test]
    // The kline fields parse from exact decimal strings, so an exact f64 compare
    // is correct here.
    #[allow(clippy::float_cmp)]
    fn klines_parse_into_candles() {
        let (binance, mock) = client(MarketType::Spot, false);
        mock.push_json(
            200,
            r#"[[1499040000000,"100.0","110.0","95.0","105.0","12.5",1499040059999,"0",1,"0","0","0"]]"#,
        );
        let candles = binance.klines(&symbol(), "1h", 1).unwrap();
        assert_eq!(candles.len(), 1);
        let c = candles[0];
        assert_eq!(c.open, 100.0);
        assert_eq!(c.high, 110.0);
        assert_eq!(c.low, 95.0);
        assert_eq!(c.close, 105.0);
        assert_eq!(c.volume, 12.5);
        assert_eq!(c.timestamp, 1_499_040_000_000);
    }

    #[test]
    fn order_book_parses_levels() {
        let (binance, mock) = client(MarketType::Spot, true);
        mock.push_json(
            200,
            r#"{"lastUpdateId":42,"bids":[["100.0","1.5"],["99.0","2.0"]],"asks":[["101.0","1.0"]]}"#,
        );
        let book = binance.order_book(&symbol(), 5).unwrap();
        assert_eq!(book.last_update_id, 42);
        assert_eq!(book.bids.len(), 2);
        assert_eq!(book.bids[0], BookLevel::new(dec!(100.0), dec!(1.5)));
        assert_eq!(book.asks[0], BookLevel::new(dec!(101.0), dec!(1.0)));
        // Testnet base.
        let req = &mock.recorded_requests()[0];
        assert!(req
            .url
            .starts_with("https://testnet.binance.vision/api/v3/depth"));
    }

    #[test]
    fn invalid_symbol_error_is_mapped() {
        let (binance, mock) = client(MarketType::Spot, false);
        mock.push_json(400, r#"{"code":-1121,"msg":"Invalid symbol."}"#);
        assert!(matches!(
            binance.ticker(&symbol()).unwrap_err(),
            Error::InvalidSymbol(_)
        ));
    }

    #[test]
    fn error_taxonomy_mapping() {
        let cases = [
            (r#"{"code":-2010,"msg":"x"}"#, "balance"),
            (r#"{"code":-1003,"msg":"x"}"#, "rate"),
            (r#"{"code":-2015,"msg":"x"}"#, "auth"),
            (r#"{"code":-9999,"msg":"weird"}"#, "exchange"),
        ];
        for (body, kind) in cases {
            let (binance, mock) = client(MarketType::Spot, false);
            mock.push_json(400, body);
            let err = binance.ticker(&symbol()).unwrap_err();
            match kind {
                "balance" => assert!(matches!(err, Error::InsufficientBalance)),
                "rate" => assert!(matches!(err, Error::RateLimited { .. })),
                "auth" => assert!(matches!(err, Error::Auth(_))),
                _ => assert!(matches!(err, Error::Exchange { .. })),
            }
        }
    }

    #[test]
    fn non_json_error_body_falls_back_to_exchange() {
        let (binance, mock) = client(MarketType::Spot, false);
        mock.push_json(502, "<html>bad gateway</html>");
        assert!(matches!(
            binance.ticker(&symbol()).unwrap_err(),
            Error::Exchange { .. }
        ));
    }

    #[test]
    fn short_kline_row_is_rejected() {
        let (binance, mock) = client(MarketType::Spot, false);
        mock.push_json(200, r#"[[1499040000000,"100.0"]]"#);
        assert!(matches!(
            binance.klines(&symbol(), "1h", 1).unwrap_err(),
            Error::Deserialization(_)
        ));
    }

    const ORDER_JSON: &str = r#"{"symbol":"BTCUSDT","orderId":28,"clientOrderId":"abc",
        "price":"100.00000000","origQty":"1.00000000","executedQty":"0.00000000",
        "cummulativeQuoteQty":"0.00000000","status":"NEW","type":"LIMIT","side":"BUY"}"#;

    /// An authenticated client over a mock transport with a fixed clock.
    fn signed_client(now_ms: i64) -> (Binance, Arc<MockHttpTransport>) {
        let mock = Arc::new(MockHttpTransport::new());
        let opts = ExchangeOptions::mainnet(MarketType::Spot);
        let binance = Binance::with_credentials(
            Box::new(ArcTransport(Arc::clone(&mock))),
            &opts,
            Credentials::new("APIKEY", "SECRET"),
        )
        .with_clock(Box::new(move || now_ms));
        (binance, mock)
    }

    /// An authenticated USDⓈ-M futures client over a mock transport.
    fn signed_futures_client(now_ms: i64) -> (Binance, Arc<MockHttpTransport>) {
        let mock = Arc::new(MockHttpTransport::new());
        let opts = ExchangeOptions::mainnet(MarketType::UsdMFutures);
        let binance = Binance::with_credentials(
            Box::new(ArcTransport(Arc::clone(&mock))),
            &opts,
            Credentials::new("APIKEY", "SECRET"),
        )
        .with_clock(Box::new(move || now_ms));
        (binance, mock)
    }

    /// An authenticated USDⓈ-M futures client whose account is in hedge mode.
    fn hedged_futures_client(now_ms: i64) -> (Binance, Arc<MockHttpTransport>) {
        let mock = Arc::new(MockHttpTransport::new());
        let mut opts = ExchangeOptions::mainnet(MarketType::UsdMFutures);
        opts.position_mode = PositionMode::Hedge;
        let binance = Binance::with_credentials(
            Box::new(ArcTransport(Arc::clone(&mock))),
            &opts,
            Credentials::new("APIKEY", "SECRET"),
        )
        .with_clock(Box::new(move || now_ms));
        (binance, mock)
    }

    #[test]
    fn the_websocket_frame_carries_the_stp_policy() {
        // The ws-api takes the REST parameter names verbatim, and this one was
        // simply not being pushed.
        let ws = Arc::new(MockWsTransport::new());
        let http = Arc::new(MockHttpTransport::new());
        let mut client = Binance::with_credentials(
            Box::new(ArcTransport(http)),
            &ExchangeOptions::mainnet(MarketType::Spot),
            Credentials::new("APIKEY", "SECRET"),
        )
        .with_ws(Box::new(ArcWs(Arc::clone(&ws))))
        .with_clock(Box::new(|| 1000));
        ws.push_connection(vec![Ok(Some(
            r#"{"id":"1","status":200,"result":{"symbol":"BTCUSDT","orderId":7,
            "clientOrderId":"","status":"NEW","type":"LIMIT","side":"BUY",
            "origQty":"1","executedQty":"0","price":"100"}}"#
                .to_string(),
        ))]);
        client
            .place_order_ws(
                &OrderRequest::limit_buy(symbol(), dec!(1), dec!(100))
                    .with_stp(SelfTradePrevention::ExpireTaker),
            )
            .unwrap();
        assert!(ws.sent()[0].contains("selfTradePreventionMode"));
        assert!(ws.sent()[0].contains("EXPIRE_TAKER"));
    }

    #[test]
    fn the_trigger_price_reaches_all_three_order_paths() {
        // Binance is the one venue that carries a trigger rather than refusing
        // it, and it has three ways to send an order. The REST path already had
        // this; the batch entry and the ws-api frame were dropping `stopPrice`.
        let stop = OrderRequest {
            order_type: OrderType::StopMarket,
            stop_price: Some(dec!(19000)),
            ..OrderRequest::market_sell(symbol(), dec!(1))
        };

        let (rest, mock) = signed_futures_client(1000);
        mock.push_json(200, ORDER_JSON);
        rest.place_order(&stop).unwrap();
        assert!(mock.recorded_requests()[0].url.contains("stopPrice=19000"));

        let batch = batch_order_json(&stop, PositionMode::OneWay).unwrap();
        assert!(batch.contains(r#""stopPrice":"19000""#));

        let ws = Arc::new(MockWsTransport::new());
        let http = Arc::new(MockHttpTransport::new());
        let mut ws_client = Binance::with_credentials(
            Box::new(ArcTransport(http)),
            &ExchangeOptions::mainnet(MarketType::UsdMFutures),
            Credentials::new("APIKEY", "SECRET"),
        )
        .with_ws(Box::new(ArcWs(Arc::clone(&ws))))
        .with_clock(Box::new(|| 1000));
        ws.push_connection(vec![Ok(Some(
            r#"{"id":"1","status":200,"result":{"symbol":"BTCUSDT","orderId":7,
            "clientOrderId":"","status":"NEW","type":"STOP_LOSS","side":"SELL",
            "origQty":"1","executedQty":"0","price":"0"}}"#
                .to_string(),
        ))]);
        ws_client.place_order_ws(&stop).unwrap();
        assert!(ws.sent()[0].contains("stopPrice"));
    }

    #[test]
    fn hedge_mode_names_the_side_and_drops_reduce_only() {
        // A hedged account holds both sides at once. Without `positionSide`
        // Binance rejects the order with -4061; with `reduceOnly` alongside it,
        // with -1106. Opening buys the long side, closing sells it.
        let (hedged, mock) = hedged_futures_client(1000);
        for _ in 0..2 {
            mock.push_json(200, ORDER_JSON);
        }
        hedged
            .place_order(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)))
            .unwrap();
        hedged
            .place_order(&OrderRequest::limit_sell(symbol(), dec!(1), dec!(100)).reduce_only())
            .unwrap();

        let reqs = mock.recorded_requests();
        assert!(reqs[0].url.contains("positionSide=LONG"));
        assert!(reqs[1].url.contains("positionSide=LONG")); // a sell closes the long
        assert!(!reqs[1].url.contains("reduceOnly"));
    }

    #[test]
    fn one_way_futures_and_spot_are_unchanged() {
        // The hedge branch is the only new one: one-way futures and spot still
        // send `reduceOnly` and no `positionSide`.
        let (futures, mock) = signed_futures_client(1000);
        mock.push_json(200, ORDER_JSON);
        futures
            .place_order(&OrderRequest::limit_sell(symbol(), dec!(1), dec!(100)).reduce_only())
            .unwrap();
        let reqs = mock.recorded_requests();
        assert!(reqs[0].url.contains("reduceOnly=true"));
        assert!(!reqs[0].url.contains("positionSide"));
    }

    #[test]
    fn hedge_mode_reaches_the_batch_and_websocket_paths() {
        // Three futures order paths, not one: REST, the native batch endpoint
        // and the ws-fapi order API.
        let json = batch_order_json(
            &OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)),
            PositionMode::Hedge,
        )
        .unwrap();
        assert!(json.contains(r#""positionSide":"LONG""#));
        assert!(!json.contains("reduceOnly"));

        let one_way = batch_order_json(
            &OrderRequest::limit_sell(symbol(), dec!(1), dec!(100)).reduce_only(),
            PositionMode::OneWay,
        )
        .unwrap();
        assert!(one_way.contains(r#""reduceOnly":"true""#));
        assert!(!one_way.contains("positionSide"));
    }

    /// Spot holds balances, not positions, and Binance rejects `reduceOnly`
    /// there outright (-1104). The client used to append it anyway.
    #[test]
    fn a_spot_order_refuses_reduce_only() {
        let (binance, mock) = signed_client(1000);
        let request = OrderRequest::limit_sell(symbol(), dec!(1), dec!(100)).reduce_only();
        let err = binance.place_order(&request).unwrap_err();
        assert!(matches!(err, Error::Exchange { ref code, .. } if code == "unsupported"));
        assert_eq!(mock.recorded_requests(), Vec::new());
    }

    /// One `markPrice` frame answers two possible subscriptions, and answers
    /// only the ones actually made. A client subscribed to funding gets the
    /// rate; one subscribed to mark/index gets the pair; one subscribed to both
    /// gets both; one subscribed to neither gets nothing, because a print nobody
    /// asked for is a figure appearing in a stream for no reason the caller can
    /// see.
    #[test]
    fn one_mark_price_frame_answers_only_the_channels_subscribed() {
        const FRAME: &str = r#"{"e":"markPriceUpdate","E":1700000000000,"s":"BTCUSDT","p":"20000.5","i":"19998.25","r":"0.0001"}"#;
        let resolve = |_: &str| symbol();

        let none = parse_derivatives_message(FRAME, &resolve, &[]);
        assert_eq!(none, Vec::new());

        let funding_only = parse_derivatives_message(
            FRAME,
            &resolve,
            &[("BTCUSDT".to_string(), DerivativesChannel::Funding)],
        );
        assert_eq!(funding_only.len(), 1);
        let Event::Derivatives(DerivativesFeed::Funding(funding)) = &funding_only[0] else {
            panic!("expected a funding print");
        };
        assert_eq!(funding.rate, dec!(0.0001));
        assert_eq!(funding.mark_price, dec!(20000.5));
        assert_eq!(funding.timestamp, 1_700_000_000_000);

        let mark_only = parse_derivatives_message(
            FRAME,
            &resolve,
            &[("BTCUSDT".to_string(), DerivativesChannel::MarkIndex)],
        );
        assert_eq!(mark_only.len(), 1);
        let Event::Derivatives(DerivativesFeed::MarkIndex(mark)) = &mark_only[0] else {
            panic!("expected a mark/index print");
        };
        assert_eq!(mark.mark_price, dec!(20000.5));
        assert_eq!(mark.index_price, dec!(19998.25));

        let both = parse_derivatives_message(
            FRAME,
            &resolve,
            &[
                ("BTCUSDT".to_string(), DerivativesChannel::Funding),
                ("BTCUSDT".to_string(), DerivativesChannel::MarkIndex),
            ],
        );
        assert_eq!(both.len(), 2);
    }

    /// A forced order is a liquidation, and its side is the side hitting the
    /// book: a liquidated long is *sold*. Reading it the other way inverts every
    /// liquidation-flow figure computed from the stream.
    #[test]
    fn a_forced_order_is_a_liquidation_on_the_side_hitting_the_book() {
        const FRAME: &str = r#"{"e":"forceOrder","E":1700000000000,"o":{"s":"BTCUSDT","S":"SELL","p":"19000","q":"2.5","T":1700000000123}}"#;
        let resolve = |_: &str| symbol();
        let events = parse_derivatives_message(
            FRAME,
            &resolve,
            &[("BTCUSDT".to_string(), DerivativesChannel::Liquidations)],
        );
        assert_eq!(events.len(), 1);
        let Event::Derivatives(DerivativesFeed::Liquidation(liq)) = &events[0] else {
            panic!("expected a liquidation print");
        };
        assert_eq!(liq.side, OrderSide::Sell);
        assert_eq!(liq.price, dec!(19000));
        assert_eq!(liq.quantity, dec!(2.5));
        assert_eq!(liq.timestamp, 1_700_000_000_123);

        // Not subscribed: nothing.
        assert_eq!(parse_derivatives_message(FRAME, &resolve, &[]), Vec::new());
    }

    /// A frame that is not a derivatives print, or is malformed, yields nothing
    /// rather than a partly-filled figure.
    #[test]
    fn a_frame_that_is_not_a_derivatives_print_yields_nothing() {
        let resolve = |_: &str| symbol();
        let subscribed = [
            ("BTCUSDT".to_string(), DerivativesChannel::Funding),
            ("BTCUSDT".to_string(), DerivativesChannel::MarkIndex),
            ("BTCUSDT".to_string(), DerivativesChannel::Liquidations),
        ];
        for frame in [
            r#"{"e":"trade","s":"BTCUSDT","p":"1","q":"1","m":false,"T":1}"#,
            r#"{"result":null,"id":1}"#,
            "not json at all",
            // markPrice with no mark price to speak of
            r#"{"e":"markPriceUpdate","s":"BTCUSDT","r":"0.0001"}"#,
            // forceOrder with no nested payload
            r#"{"e":"forceOrder","E":1}"#,
            // forceOrder with a side that is neither
            r#"{"e":"forceOrder","o":{"s":"BTCUSDT","S":"HOLD","p":"1","q":"1"}}"#,
        ] {
            assert_eq!(
                parse_derivatives_message(frame, &resolve, &subscribed),
                Vec::new()
            );
        }
    }

    /// The derivatives channels exist only on the futures venue. A spot client
    /// refuses rather than subscribing to a stream that will never carry a frame
    /// and leaving the caller waiting on it.
    #[test]
    fn a_spot_client_refuses_the_derivatives_channels() {
        let (mut spot, _mock) = signed_client(1000);
        let err = DerivativesStream::subscribe_derivatives(
            &mut spot,
            &symbol(),
            DerivativesChannel::Funding,
        )
        .unwrap_err();
        assert!(matches!(err, Error::Exchange { ref code, .. } if code == "unsupported"));

        let err = DerivativesStream::open_interest(&mut spot, &symbol()).unwrap_err();
        assert!(matches!(err, Error::Exchange { ref code, .. } if code == "unsupported"));

        let err = DerivativesStream::long_short_ratio(&mut spot, &symbol()).unwrap_err();
        assert!(matches!(err, Error::Exchange { ref code, .. } if code == "unsupported"));
    }

    /// Funding and mark/index share one stream, so both subscriptions send the
    /// same `markPrice` message; liquidations are their own.
    #[test]
    fn the_subscription_names_the_stream_binance_publishes() {
        let (mut futures, _mock) = signed_futures_client(1000);
        let ws = Arc::new(MockWsTransport::new());
        futures = futures.with_ws(Box::new(ArcWs(Arc::clone(&ws))));

        DerivativesStream::subscribe_derivatives(
            &mut futures,
            &symbol(),
            DerivativesChannel::Funding,
        )
        .unwrap();
        DerivativesStream::subscribe_derivatives(
            &mut futures,
            &symbol(),
            DerivativesChannel::Liquidations,
        )
        .unwrap();

        let sent = ws.sent();
        assert!(sent[0].contains("btcusdt@markPrice"));
        assert!(sent[1].contains("btcusdt@forceOrder"));
    }

    /// Open interest and long/short positioning are read, not streamed.
    #[test]
    fn the_polled_figures_are_read_over_rest() {
        let (futures, mock) = signed_futures_client(1000);
        mock.push_json(
            200,
            r#"{"symbol":"BTCUSDT","openInterest":"12345.67","time":1700000000000}"#,
        );
        let oi = Binance::open_interest(&futures, &symbol()).unwrap();
        assert_eq!(oi.open_interest, dec!(12345.67));
        assert_eq!(oi.timestamp, 1_700_000_000_000);
        assert!(mock.recorded_requests()[0]
            .url
            .contains("/fapi/v1/openInterest"));

        let (futures, mock) = signed_futures_client(1000);
        mock.push_json(
            200,
            r#"[{"symbol":"BTCUSDT","longShortRatio":"1.5","longAccount":"0.6","shortAccount":"0.4","timestamp":1700000000000}]"#,
        );
        let ratio = Binance::long_short_ratio(&futures, &symbol()).unwrap();
        assert_eq!(ratio.long_size, dec!(0.6));
        assert_eq!(ratio.short_size, dec!(0.4));
        assert!(mock.recorded_requests()[0]
            .url
            .contains("globalLongShortAccountRatio"));

        // An empty series is reported, not read as a zero.
        let (futures, mock) = signed_futures_client(1000);
        mock.push_json(200, "[]");
        assert!(Binance::long_short_ratio(&futures, &symbol()).is_err());
    }

    #[test]
    fn stp_mode_appends_param() {
        let (binance, mock) = signed_client(1000);
        mock.push_json(200, ORDER_JSON);
        binance
            .place_order(
                &OrderRequest::limit_buy(symbol(), dec!(1), dec!(100))
                    .with_stp(SelfTradePrevention::ExpireMaker),
            )
            .unwrap();
        assert!(mock.recorded_requests()[0]
            .url
            .contains("selfTradePreventionMode=EXPIRE_MAKER"));
    }

    #[test]
    fn stp_none_omits_param() {
        let (binance, mock) = signed_client(1000);
        mock.push_json(200, ORDER_JSON);
        binance
            .place_order(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)))
            .unwrap();
        assert!(!mock.recorded_requests()[0]
            .url
            .contains("selfTradePreventionMode"));
    }

    #[test]
    fn amend_spot_uses_cancel_replace() {
        let (binance, mock) = signed_client(1000);
        mock.push_json(200, ORDER_JSON); // query_order
        mock.push_json(
            200,
            r#"{"cancelResult":"SUCCESS","newOrderResult":{"symbol":"BTCUSDT","orderId":456,
            "clientOrderId":"","side":"BUY","type":"LIMIT","status":"NEW","origQty":"2",
            "executedQty":"0","price":"101"}}"#,
        );
        let order = binance
            .amend_order(&symbol(), "123", Some(dec!(101)), Some(dec!(2)))
            .unwrap();
        assert_eq!(order.id, "456");
        assert_eq!(order.quantity, dec!(2));
        let reqs = mock.recorded_requests();
        assert!(reqs[1].url.contains("/api/v3/order/cancelReplace"));
        assert!(reqs[1].url.contains("cancelOrderId=123"));
        assert!(reqs[1].url.contains("quantity=2"));
        assert!(reqs[1].url.contains("price=101"));
        assert_eq!(reqs[1].method, HttpMethod::Post);
    }

    #[test]
    fn amend_futures_puts_in_place() {
        let (binance, mock) = signed_futures_client(1000);
        mock.push_json(200, ORDER_JSON); // query_order
        mock.push_json(
            200,
            r#"{"symbol":"BTCUSDT","orderId":123,"clientOrderId":"","side":"BUY","type":"LIMIT",
            "status":"NEW","origQty":"1","executedQty":"0","price":"105","avgPrice":"0"}"#,
        );
        let order = binance
            .amend_order(&symbol(), "123", Some(dec!(105)), None)
            .unwrap();
        assert_eq!(order.price, Some(dec!(105)));
        let reqs = mock.recorded_requests();
        assert_eq!(reqs[1].method, HttpMethod::Put);
        assert!(reqs[1].url.contains("/fapi/v1/order"));
        assert!(reqs[1].url.contains("price=105"));
        assert!(reqs[1].url.contains("orderId=123"));
    }

    #[test]
    fn place_batch_spot_is_sequential() {
        let (binance, mock) = signed_client(1000);
        mock.push_json(200, ORDER_JSON);
        mock.push_json(200, ORDER_JSON);
        let results = binance
            .place_batch(&[
                OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)),
                OrderRequest::limit_buy(symbol(), dec!(1), dec!(101)),
            ])
            .unwrap();
        assert_eq!(results.len(), 2);
        assert!(results.iter().all(std::result::Result::is_ok));
        assert_eq!(mock.recorded_requests().len(), 2);
    }

    #[test]
    fn place_batch_futures_is_one_call_with_per_order_results() {
        let (binance, mock) = signed_futures_client(1000);
        mock.push_json(
            200,
            r#"[{"symbol":"BTCUSDT","orderId":1,"clientOrderId":"","side":"BUY","type":"LIMIT",
            "status":"NEW","origQty":"1","executedQty":"0","price":"100","avgPrice":"0"},
            {"code":-2019,"msg":"Margin is insufficient."}]"#,
        );
        let results = binance
            .place_batch(&[
                OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)),
                OrderRequest::limit_buy(symbol(), dec!(1), dec!(101)),
            ])
            .unwrap();
        assert_eq!(results.len(), 2);
        assert!(results[0].is_ok());
        assert!(matches!(
            results[1].as_ref().unwrap_err(),
            Error::OrderRejected { .. }
        ));
        let reqs = mock.recorded_requests();
        assert_eq!(reqs.len(), 1);
        assert!(reqs[0].url.contains("/fapi/v1/batchOrders"));
        assert!(reqs[0].url.contains("batchOrders=%5B")); // url-encoded '['
    }

    #[test]
    fn cancel_batch_spot_is_sequential() {
        let (binance, mock) = signed_client(1000);
        mock.push_json(200, "{}");
        mock.push_json(200, "{}");
        binance
            .cancel_batch(&symbol(), &["1".to_string(), "2".to_string()])
            .unwrap();
        assert_eq!(mock.recorded_requests().len(), 2);
    }

    #[test]
    fn cancel_batch_futures_is_one_call() {
        let (binance, mock) = signed_futures_client(1000);
        mock.push_json(200, "[{}]");
        binance
            .cancel_batch(&symbol(), &["1".to_string(), "2".to_string()])
            .unwrap();
        let reqs = mock.recorded_requests();
        assert_eq!(reqs.len(), 1);
        assert_eq!(reqs[0].method, HttpMethod::Delete);
        assert!(reqs[0].url.contains("/fapi/v1/batchOrders"));
        assert!(reqs[0].url.contains("orderIdList=%5B")); // url-encoded '['
    }

    #[test]
    fn place_oco_spot_returns_both_legs() {
        let (binance, mock) = signed_client(1000);
        mock.push_json(
            200,
            r#"{"orderListId":99,"orderReports":[
            {"symbol":"BTCUSDT","orderId":1,"clientOrderId":"","side":"SELL","type":"LIMIT_MAKER",
            "status":"NEW","origQty":"1","executedQty":"0","price":"110"},
            {"symbol":"BTCUSDT","orderId":2,"clientOrderId":"","side":"SELL","type":"STOP_LOSS_LIMIT",
            "status":"NEW","origQty":"1","executedQty":"0","price":"90"}]}"#,
        );
        let legs = binance
            .place_oco(&OcoRequest::new(
                symbol(),
                OrderSide::Sell,
                dec!(1),
                dec!(110),
                dec!(95),
            ))
            .unwrap();
        assert_eq!(legs.len(), 2);
        assert_eq!(legs[0].id, "1");
        assert_eq!(legs[1].id, "2");
        let req = &mock.recorded_requests()[0];
        assert!(req.url.contains("/api/v3/order/oco"));
        assert!(req.url.contains("stopPrice=95"));
    }

    #[test]
    fn place_oco_futures_is_unsupported() {
        let (binance, _mock) = signed_futures_client(1000);
        assert!(matches!(
            binance
                .place_oco(&OcoRequest::new(
                    symbol(),
                    OrderSide::Sell,
                    dec!(1),
                    dec!(110),
                    dec!(95)
                ))
                .unwrap_err(),
            Error::Exchange { .. }
        ));
    }

    /// An authenticated client with both a mock HTTP and a mock WS transport.
    fn ws_signed_client(now_ms: i64) -> (Binance, Arc<MockWsTransport>) {
        let http = Arc::new(MockHttpTransport::new());
        let ws = Arc::new(MockWsTransport::new());
        let opts = ExchangeOptions::mainnet(MarketType::Spot);
        let binance = Binance::with_credentials(
            Box::new(ArcTransport(http)),
            &opts,
            Credentials::new("APIKEY", "SECRET"),
        )
        .with_ws(Box::new(ArcWs(Arc::clone(&ws))))
        .with_clock(Box::new(move || now_ms));
        (binance, ws)
    }

    #[test]
    fn place_order_ws_signs_and_parses() {
        let (mut binance, ws) = ws_signed_client(1000);
        ws.push_connection(vec![Ok(Some(
            r#"{"id":1000,"status":200,"result":{"symbol":"BTCUSDT","orderId":55,
            "clientOrderId":"","side":"BUY","type":"LIMIT","status":"NEW","origQty":"1",
            "executedQty":"0","price":"100"}}"#
                .to_string(),
        ))]);
        let order = WsExecution::place_order_ws(
            &mut binance,
            &OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)),
        )
        .unwrap();
        assert_eq!(order.id, "55");
        assert_eq!(order.status, OrderStatus::New);
        assert_eq!(
            ws.connected_urls()[0],
            "wss://ws-api.binance.com:443/ws-api/v3"
        );
        let sent = &ws.sent()[0];
        assert!(sent.contains(r#""method":"order.place""#));
        assert!(sent.contains(r#""apiKey":"APIKEY""#));
        assert!(sent.contains(r#""signature""#));
        assert!(sent.contains(r#""timestamp":"1000""#));
    }

    #[test]
    fn place_order_ws_surfaces_rejection() {
        let (mut binance, ws) = ws_signed_client(1000);
        ws.push_connection(vec![Ok(Some(
            r#"{"id":1000,"status":400,"error":{"code":-2010,"msg":"insufficient balance"}}"#
                .to_string(),
        ))]);
        assert!(matches!(
            binance
                .place_order_ws(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)))
                .unwrap_err(),
            Error::OrderRejected { .. }
        ));
    }

    #[test]
    fn cancel_order_ws_sends_cancel_method() {
        let (mut binance, ws) = ws_signed_client(1000);
        ws.push_connection(vec![Ok(Some(
            r#"{"id":1000,"status":200,"result":{"symbol":"BTCUSDT","orderId":55}}"#.to_string(),
        ))]);
        WsExecution::cancel_order_ws(&mut binance, &symbol(), "55").unwrap();
        let sent = &ws.sent()[0];
        assert!(sent.contains(r#""method":"order.cancel""#));
        assert!(sent.contains(r#""orderId":"55""#));
    }

    #[test]
    fn ws_order_requires_a_ws_transport() {
        let (mut binance, _mock) = signed_client(1000);
        assert!(matches!(
            binance
                .place_order_ws(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)))
                .unwrap_err(),
            Error::NotConnected
        ));
    }

    /// A credentialed client wired to both a shared HTTP mock (for the listen-key
    /// POST) and a shared WS mock (for the private stream frames).
    fn user_data_client(
        market_type: MarketType,
    ) -> (Binance, Arc<MockHttpTransport>, Arc<MockWsTransport>) {
        let http = Arc::new(MockHttpTransport::new());
        let ws = Arc::new(MockWsTransport::new());
        let opts = ExchangeOptions::mainnet(market_type);
        let binance = Binance::with_credentials(
            Box::new(ArcTransport(Arc::clone(&http))),
            &opts,
            Credentials::new("APIKEY", "SECRET"),
        )
        .with_ws(Box::new(ArcWs(Arc::clone(&ws))));
        (binance, http, ws)
    }

    #[test]
    fn subscribe_user_data_spot_streams_orders_and_balances() {
        let (mut binance, http, ws) = user_data_client(MarketType::Spot);
        http.push_json(200, r#"{"listenKey":"listen-abc"}"#);
        ws.push_connection(vec![
            Ok(Some(
                r#"{"e":"executionReport","s":"BTCUSDT","i":123,"c":"myid","S":"BUY","o":"LIMIT",
                "X":"FILLED","q":"1.5","z":"1.5","p":"100","Z":"150"}"#
                    .to_string(),
            )),
            Ok(Some(
                r#"{"e":"outboundAccountPosition","B":[{"a":"USDT","f":"1000","l":"50"},
                {"a":"BTC","f":"2","l":"0"}]}"#
                    .to_string(),
            )),
        ]);
        binance.subscribe_user_data().unwrap();

        let reqs = http.recorded_requests();
        assert_eq!(reqs.len(), 1);
        assert_eq!(reqs[0].method, HttpMethod::Post);
        assert!(reqs[0].url.contains("/api/v3/userDataStream"));
        assert_eq!(
            ws.connected_urls()[0],
            "wss://stream.binance.com:9443/ws/listen-abc"
        );

        let events = binance.poll_events();
        assert_eq!(events.len(), 2);
        let Event::OrderUpdate(order) = &events[0] else {
            panic!("first event must be an order update");
        };
        assert_eq!(order.id, "123");
        assert_eq!(order.client_order_id.as_deref(), Some("myid"));
        assert_eq!(order.symbol, symbol());
        assert_eq!(order.side, OrderSide::Buy);
        assert_eq!(order.status, OrderStatus::Filled);
        assert_eq!(order.filled_quantity, dec!(1.5));
        assert_eq!(order.average_price, Some(dec!(100)));
        let Event::BalanceUpdate(balances) = &events[1] else {
            panic!("second event must be a balance update");
        };
        assert_eq!(balances.len(), 2);
        assert_eq!(balances[0].asset, "USDT");
        assert_eq!(balances[0].free, dec!(1000));
        assert_eq!(balances[0].locked, dec!(50));
    }

    #[test]
    fn subscribe_user_data_futures_parses_order_and_account_updates() {
        let (mut binance, http, ws) = user_data_client(MarketType::UsdMFutures);
        http.push_json(200, r#"{"listenKey":"fk"}"#);
        ws.push_connection(vec![
            Ok(Some(
                r#"{"e":"ORDER_TRADE_UPDATE","o":{"s":"BTCUSDT","i":456,"c":"","S":"SELL",
                "o":"LIMIT","X":"PARTIALLY_FILLED","q":"3","z":"1","p":"105","ap":"104.5"}}"#
                    .to_string(),
            )),
            Ok(Some(
                r#"{"e":"ACCOUNT_UPDATE","a":{"B":[{"a":"USDT","wb":"5000","cw":"5000"}]}}"#
                    .to_string(),
            )),
        ]);
        binance.subscribe_user_data().unwrap();

        let reqs = http.recorded_requests();
        assert!(reqs[0].url.contains("/fapi/v1/listenKey"));
        assert_eq!(ws.connected_urls()[0], "wss://fstream.binance.com/ws/fk");

        let events = binance.poll_events();
        assert_eq!(events.len(), 2);
        let Event::OrderUpdate(order) = &events[0] else {
            panic!("first event must be an order update");
        };
        assert_eq!(order.id, "456");
        assert_eq!(order.side, OrderSide::Sell);
        assert_eq!(order.status, OrderStatus::PartiallyFilled);
        assert_eq!(order.filled_quantity, dec!(1));
        assert_eq!(order.average_price, Some(dec!(104.5)));
        let Event::BalanceUpdate(balances) = &events[1] else {
            panic!("second event must be a balance update");
        };
        assert_eq!(balances.len(), 1);
        assert_eq!(balances[0].asset, "USDT");
        assert_eq!(balances[0].free, dec!(5000));
        assert_eq!(balances[0].locked, Decimal::ZERO);
    }

    #[test]
    fn subscribe_user_data_requires_credentials() {
        let (mut binance, _http) = client(MarketType::Spot, false);
        assert!(matches!(
            binance.subscribe_user_data().unwrap_err(),
            Error::InvalidCredentials(_)
        ));
    }

    #[test]
    fn keepalive_user_data_refreshes_the_listen_key() {
        let (mut binance, http, ws) = user_data_client(MarketType::Spot);
        http.push_json(200, r#"{"listenKey":"listen-abc"}"#);
        ws.push_connection(vec![]);
        binance.subscribe_user_data().unwrap();
        http.push_json(200, "{}"); // the keepalive PUT
        binance.keepalive_user_data().unwrap();
        let reqs = http.recorded_requests();
        let put = &reqs[1];
        assert_eq!(put.method, HttpMethod::Put);
        assert!(put
            .url
            .contains("/api/v3/userDataStream?listenKey=listen-abc"));
    }

    #[test]
    fn keepalive_user_data_is_a_noop_before_subscribe() {
        let (mut binance, http, _ws) = user_data_client(MarketType::Spot);
        binance.keepalive_user_data().unwrap();
        assert_eq!(http.recorded_requests(), Vec::new());
    }

    #[test]
    fn dropped_user_data_stream_reconnects_with_a_fresh_listen_key() {
        let (mut binance, http, ws) = user_data_client(MarketType::Spot);
        http.push_json(200, r#"{"listenKey":"key-1"}"#);
        // First private connection closes on the first recv; the reconnect target
        // is a fresh open connection.
        ws.push_connection(vec![Ok(None)]);
        ws.push_connection(vec![]);
        binance.subscribe_user_data().unwrap();
        // The reconnect re-mints a listen key over REST.
        http.push_json(200, r#"{"listenKey":"key-2"}"#);

        let events = binance.poll_events();
        assert!(events.contains(&Event::Disconnected));
        assert!(events.contains(&Event::Reconnected));
        // Two REST listen-key POSTs (initial + reconnect) and a second WS connection.
        assert_eq!(http.recorded_requests().len(), 2);
        assert_eq!(ws.connected_urls().len(), 2);
        assert!(ws.connected_urls()[1].ends_with("/ws/key-2"));
    }

    #[test]
    fn futures_ticker_combines_stats_and_book() {
        let (binance, mock) = signed_futures_client(1000);
        mock.push_json(
            200,
            r#"{"symbol":"BTCUSDT","lastPrice":"20000.0","volume":"1234.0"}"#,
        );
        mock.push_json(
            200,
            r#"{"symbol":"BTCUSDT","bidPrice":"19999.0","askPrice":"20001.0"}"#,
        );
        let ticker = binance.ticker(&symbol()).unwrap();
        assert_eq!(ticker.last, dec!(20000));
        assert_eq!(ticker.bid, dec!(19999));
        assert_eq!(ticker.ask, dec!(20001));
        assert_eq!(ticker.volume, dec!(1234));
        let reqs = mock.recorded_requests();
        assert!(reqs[0].url.contains("fapi.binance.com/fapi/v1/ticker/24hr"));
        assert!(reqs[1].url.contains("/fapi/v1/ticker/bookTicker"));
    }

    #[test]
    fn futures_balances_use_fapi_v2_balance() {
        let (binance, mock) = signed_futures_client(1000);
        mock.push_json(
            200,
            r#"[{"asset":"USDT","balance":"1000.0","availableBalance":"800.0"}]"#,
        );
        let balances = binance.balances().unwrap();
        assert_eq!(balances[0].asset, "USDT");
        assert_eq!(balances[0].free, dec!(800));
        assert_eq!(balances[0].locked, dec!(200));
        assert!(mock.recorded_requests()[0].url.contains("/fapi/v2/balance"));
    }

    #[test]
    fn futures_place_order_uses_fapi_order_path() {
        let (binance, mock) = signed_futures_client(1000);
        mock.push_json(200, ORDER_JSON);
        binance
            .place_order(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(20000)))
            .unwrap();
        assert!(mock.recorded_requests()[0].url.contains("/fapi/v1/order"));
    }

    #[test]
    fn derivatives_positions_parse_and_skip_flat() {
        let (mut binance, mock) = signed_futures_client(1000);
        mock.push_json(
            200,
            r#"[
              {"symbol":"BTCUSDT","positionAmt":"0.5","entryPrice":"20000.0","markPrice":"20100.0","unRealizedProfit":"50.0","leverage":"10","marginType":"isolated"},
              {"symbol":"ETHUSDT","positionAmt":"0.0","entryPrice":"0.0","markPrice":"0.0","unRealizedProfit":"0.0","leverage":"5","marginType":"cross"},
              {"symbol":"XRPUSDT","positionAmt":"-100.0","entryPrice":"0.5","markPrice":"0.48","unRealizedProfit":"2.0","leverage":"20","marginType":"cross"}
            ]"#,
        );
        let positions = Derivatives::positions(&mut binance, None).unwrap();
        assert_eq!(positions.len(), 2); // the flat ETH position is skipped
        assert_eq!(positions[0].symbol, Symbol::new("BTC", "USDT"));
        assert_eq!(positions[0].side, PositionSide::Long);
        assert_eq!(positions[0].quantity, dec!(0.5));
        assert_eq!(positions[0].leverage, dec!(10));
        assert_eq!(positions[0].margin_mode, MarginMode::Isolated);
        assert_eq!(positions[1].side, PositionSide::Short);
        assert_eq!(positions[1].quantity, dec!(100));
        assert!(mock.recorded_requests()[0]
            .url
            .contains("/fapi/v2/positionRisk"));
    }

    #[test]
    fn derivatives_set_leverage_and_margin_mode() {
        let (mut binance, mock) = signed_futures_client(1000);
        mock.push_json(200, r#"{"leverage":10,"symbol":"BTCUSDT"}"#);
        Derivatives::set_leverage(&mut binance, &symbol(), 10).unwrap();
        mock.push_json(200, r#"{"code":200,"msg":"success"}"#);
        Derivatives::set_margin_mode(&mut binance, &symbol(), MarginMode::Isolated).unwrap();
        let reqs = mock.recorded_requests();
        assert!(reqs[0].url.contains("/fapi/v1/leverage"));
        assert!(reqs[0].url.contains("leverage=10"));
        assert!(reqs[1].url.contains("/fapi/v1/marginType"));
        assert!(reqs[1].url.contains("marginType=ISOLATED"));
    }

    #[test]
    fn derivatives_close_position_places_reduce_only_market() {
        let (mut binance, mock) = signed_futures_client(1000);
        mock.push_json(
            200,
            r#"[{"symbol":"BTCUSDT","positionAmt":"0.5","entryPrice":"20000.0","markPrice":"20100.0","unRealizedProfit":"50.0","leverage":"10","marginType":"isolated"}]"#,
        );
        mock.push_json(200, ORDER_JSON);
        Derivatives::close_position(&mut binance, &symbol()).unwrap();
        let reqs = mock.recorded_requests();
        assert!(reqs[1].url.contains("/fapi/v1/order"));
        assert!(reqs[1].url.contains("side=SELL"));
        assert!(reqs[1].url.contains("reduceOnly=true"));
    }

    #[test]
    fn place_order_signs_request_and_parses_response() {
        let (binance, mock) = signed_client(1000);
        mock.push_json(200, ORDER_JSON);
        let order = binance
            .place_order(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)))
            .unwrap();
        assert_eq!(order.id, "28");
        assert_eq!(order.client_order_id.as_deref(), Some("abc"));
        assert_eq!(order.status, OrderStatus::New);
        assert_eq!(order.quantity, dec!(1));
        assert_eq!(order.price, Some(dec!(100)));
        assert_eq!(order.average_price, None);

        let req = &mock.recorded_requests()[0];
        assert_eq!(req.method, HttpMethod::Post);
        let payload = "symbol=BTCUSDT&side=BUY&type=LIMIT&quantity=1&price=100\
                       &timeInForce=GTC&recvWindow=5000&timestamp=1000";
        let sig = crate::signing::hmac_sha256_hex(b"SECRET", payload.as_bytes());
        assert!(req.url.contains(payload), "payload mismatch: {}", req.url);
        assert!(req.url.ends_with(&format!("signature={sig}")));
        assert!(req
            .headers
            .iter()
            .any(|(k, v)| k == "X-MBX-APIKEY" && v == "APIKEY"));
    }

    #[test]
    fn post_only_limit_becomes_limit_maker_without_tif() {
        let (binance, mock) = signed_client(1000);
        mock.push_json(200, ORDER_JSON);
        binance
            .place_order(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)).post_only())
            .unwrap();
        let req = &mock.recorded_requests()[0];
        assert!(req.url.contains("type=LIMIT_MAKER"));
        assert!(!req.url.contains("timeInForce"));
    }

    #[test]
    fn signed_endpoint_without_credentials_errors() {
        let (binance, _) = client(MarketType::Spot, false);
        let err = binance
            .place_order(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)))
            .unwrap_err();
        assert!(matches!(err, Error::InvalidCredentials(_)));
    }

    #[test]
    fn cancel_order_is_a_signed_delete() {
        let (binance, mock) = signed_client(1000);
        mock.push_json(
            200,
            r#"{"symbol":"BTCUSDT","orderId":28,"status":"CANCELED"}"#,
        );
        binance.cancel_order(&symbol(), "28").unwrap();
        let req = &mock.recorded_requests()[0];
        assert_eq!(req.method, HttpMethod::Delete);
        assert!(req.url.contains("orderId=28"));
        assert!(req.url.contains("signature="));
    }

    #[test]
    fn query_order_computes_average_fill_price() {
        let (binance, mock) = signed_client(1000);
        mock.push_json(
            200,
            r#"{"symbol":"BTCUSDT","orderId":28,"clientOrderId":"","price":"0.00000000",
            "origQty":"2.0","executedQty":"2.0","cummulativeQuoteQty":"200.0",
            "status":"FILLED","type":"MARKET","side":"SELL"}"#,
        );
        let order = binance.query_order(&symbol(), "28").unwrap();
        assert_eq!(order.status, OrderStatus::Filled);
        assert_eq!(order.side, OrderSide::Sell);
        assert_eq!(order.order_type, OrderType::Market);
        assert_eq!(order.average_price, Some(dec!(100))); // 200 / 2
        assert_eq!(order.price, None); // 0 -> None
        assert_eq!(order.client_order_id, None); // empty -> None
        assert_eq!(order.filled_quantity, dec!(2));
    }

    #[test]
    fn balances_parse() {
        let (binance, mock) = signed_client(1000);
        mock.push_json(
            200,
            r#"{"balances":[{"asset":"USDT","free":"100.5","locked":"25.5"},
            {"asset":"BTC","free":"0.1","locked":"0"}]}"#,
        );
        let bals = binance.balances().unwrap();
        assert_eq!(bals.len(), 2);
        assert_eq!(bals[0].asset, "USDT");
        assert_eq!(bals[0].total(), dec!(126));
        assert_eq!(bals[1].asset, "BTC");
    }

    #[test]
    fn system_clock_is_sane() {
        // Covers the production timestamp source: a plausible 2023+ epoch ms.
        assert!(system_now_ms() > 1_600_000_000_000);
    }

    fn resolve(_wire: &str) -> Symbol {
        symbol()
    }

    #[test]
    fn ws_trade_frame_maps_aggressor() {
        // m=false -> buyer is taker -> Buy aggressor.
        let buy = parse_ws_message(
            r#"{"e":"trade","s":"BTCUSDT","p":"100.5","q":"0.25","m":false,"T":1700000000000}"#,
            &resolve,
        )
        .unwrap()
        .unwrap();
        assert_eq!(
            buy,
            Event::Trade(TradePrint {
                symbol: symbol(),
                price: dec!(100.5),
                quantity: dec!(0.25),
                aggressor: OrderSide::Buy,
                timestamp: 1_700_000_000_000,
            })
        );
        // m=true -> seller is taker -> Sell aggressor.
        let sell = parse_ws_message(
            r#"{"e":"trade","s":"BTCUSDT","p":"100","q":"1","m":true,"T":1}"#,
            &resolve,
        )
        .unwrap()
        .unwrap();
        let Event::Trade(print) = sell else {
            panic!("expected trade")
        };
        assert_eq!(print.aggressor, OrderSide::Sell);
    }

    #[test]
    fn ws_combined_stream_wrapper_is_unwrapped() {
        let event = parse_ws_message(
            r#"{"stream":"btcusdt@trade","data":{"e":"trade","s":"BTCUSDT","p":"1","q":"1","m":false,"T":1}}"#,
            &resolve,
        )
        .unwrap()
        .unwrap();
        assert!(matches!(event, Event::Trade(_)));
    }

    #[test]
    fn ws_depth_update_maps_to_book_delta() {
        let event = parse_ws_message(
            r#"{"e":"depthUpdate","s":"BTCUSDT","U":10,"u":12,"b":[["100","1"],["99","0"]],"a":[["101","2"]]}"#,
            &resolve,
        )
        .unwrap()
        .unwrap();
        let Event::BookDelta(delta) = event else {
            panic!("expected book delta")
        };
        assert_eq!(delta.first_update_id, 10);
        assert_eq!(delta.final_update_id, 12);
        assert_eq!(
            delta.bids,
            vec![
                BookLevel::new(dec!(100), dec!(1)),
                BookLevel::new(dec!(99), dec!(0))
            ]
        );
        assert_eq!(delta.asks, vec![BookLevel::new(dec!(101), dec!(2))]);
    }

    #[test]
    fn ws_ticker_frame_maps_to_ticker() {
        let event = parse_ws_message(
            r#"{"e":"24hrTicker","s":"BTCUSDT","c":"100","b":"99","a":"101","v":"1234"}"#,
            &resolve,
        )
        .unwrap()
        .unwrap();
        assert_eq!(
            event,
            Event::Ticker(Ticker {
                symbol: symbol(),
                last: dec!(100),
                bid: dec!(99),
                ask: dec!(101),
                volume: dec!(1234),
                timestamp: 0,
            })
        );
    }

    #[test]
    fn ws_non_event_frames_are_ignored() {
        // Subscription ack.
        assert!(parse_ws_message(r#"{"result":null,"id":1}"#, &resolve)
            .unwrap()
            .is_none());
        // Unhandled event type.
        assert!(parse_ws_message(r#"{"e":"kline","s":"BTCUSDT"}"#, &resolve)
            .unwrap()
            .is_none());
    }

    #[test]
    fn ws_malformed_frame_errors() {
        assert!(matches!(
            parse_ws_message("not json", &resolve).unwrap_err(),
            Error::Deserialization(_)
        ));
        // A trade frame missing a required field.
        assert!(parse_ws_message(r#"{"e":"trade","s":"BTCUSDT"}"#, &resolve).is_err());
    }

    fn streaming_client(ws: &Arc<MockWsTransport>) -> Binance {
        let http = Arc::new(MockHttpTransport::new());
        let opts = ExchangeOptions::mainnet(MarketType::Spot);
        Binance::with_http(Box::new(ArcTransport(http)), &opts)
            .with_ws(Box::new(ArcWs(Arc::clone(ws))))
    }

    #[test]
    fn subscribe_sends_frame_and_poll_returns_events() {
        let ws = Arc::new(MockWsTransport::new());
        ws.push_connection(vec![
            Ok(Some(
                r#"{"e":"trade","s":"BTCUSDT","p":"100","q":"1","m":false,"T":1}"#.to_string(),
            )),
            Ok(Some(
                r#"{"e":"trade","s":"BTCUSDT","p":"101","q":"2","m":true,"T":2}"#.to_string(),
            )),
        ]);
        let mut binance = streaming_client(&ws);
        binance.subscribe_trades(&symbol()).unwrap();

        assert_eq!(
            ws.connected_urls(),
            vec!["wss://stream.binance.com:9443/ws".to_string()]
        );
        let sent = ws.sent();
        assert!(sent[0].contains(r#""method":"SUBSCRIBE""#));
        assert!(sent[0].contains("btcusdt@trade"));

        let events = binance.poll_events();
        assert_eq!(events.len(), 2);
        assert!(matches!(events[0], Event::Trade(_)));
        // Draining again yields nothing.
        assert_eq!(binance.poll_events(), Vec::new());
    }

    #[test]
    fn book_and_ticker_subscriptions_reuse_one_connection() {
        let ws = Arc::new(MockWsTransport::new());
        ws.push_connection(vec![]);
        let mut binance = streaming_client(&ws);
        binance.subscribe_book(&symbol()).unwrap();
        binance.subscribe_ticker(&symbol()).unwrap();

        // One connection, two SUBSCRIBE frames on the right channels.
        assert_eq!(ws.connected_urls().len(), 1);
        let sent = ws.sent();
        assert!(sent[0].contains("btcusdt@depth"));
        assert!(sent[1].contains("btcusdt@ticker"));
    }

    #[test]
    fn peer_close_triggers_reconnect_and_resubscribe() {
        let ws = Arc::new(MockWsTransport::new());
        // First stream: one trade, then a clean peer close.
        ws.push_connection(vec![
            Ok(Some(
                r#"{"e":"trade","s":"BTCUSDT","p":"100","q":"1","m":false,"T":1}"#.to_string(),
            )),
            Ok(None),
        ]);
        // Reconnect target: another trade.
        ws.push_connection(vec![Ok(Some(
            r#"{"e":"trade","s":"BTCUSDT","p":"101","q":"2","m":true,"T":2}"#.to_string(),
        ))]);

        let mut binance = streaming_client(&ws);
        binance.subscribe_trades(&symbol()).unwrap();

        // First poll drains the trade, sees the close, reconnects and resubscribes.
        let first = binance.poll_events();
        assert!(matches!(first[0], Event::Trade(_)));
        assert!(first.contains(&Event::Disconnected));
        assert!(first.contains(&Event::Reconnected));

        // The reconnect opened a second connection and replayed the SUBSCRIBE.
        assert_eq!(ws.connected_urls().len(), 2);
        let sent = ws.sent();
        assert_eq!(sent.len(), 2);
        assert!(sent[1].contains("btcusdt@trade"));

        // The fresh connection delivers its trade on the next poll.
        let second = binance.poll_events();
        assert!(matches!(second[0], Event::Trade(_)));
    }

    #[test]
    fn subscribe_without_ws_transport_errors() {
        let http = Arc::new(MockHttpTransport::new());
        let opts = ExchangeOptions::mainnet(MarketType::Spot);
        let mut binance = Binance::with_http(Box::new(ArcTransport(http)), &opts);
        assert!(matches!(
            binance.subscribe_trades(&symbol()).unwrap_err(),
            Error::NotConnected
        ));
    }

    #[test]
    fn poll_without_connection_is_empty() {
        let http = Arc::new(MockHttpTransport::new());
        let opts = ExchangeOptions::mainnet(MarketType::Spot);
        let mut binance = Binance::with_http(Box::new(ArcTransport(http)), &opts);
        assert_eq!(binance.poll_events(), Vec::new());
    }

    #[test]
    fn split_wire_symbol_uses_known_quotes() {
        assert_eq!(split_wire_symbol("BTCUSDT"), Symbol::new("BTC", "USDT"));
        assert_eq!(split_wire_symbol("ETHFDUSD"), Symbol::new("ETH", "FDUSD"));
        assert_eq!(split_wire_symbol("ETHBTC"), Symbol::new("ETH", "BTC"));
        // Unknown quote -> whole string as the base.
        assert_eq!(split_wire_symbol("WEIRD"), Symbol::new("WEIRD", ""));
    }

    #[test]
    fn open_orders_filtered_and_unfiltered() {
        let (binance, mock) = signed_client(1000);
        // Filtered: the symbol is known from the caller.
        mock.push_json(
            200,
            r#"[{"symbol":"BTCUSDT","orderId":1,"clientOrderId":"a","price":"100.0",
            "origQty":"1.0","executedQty":"0.0","cummulativeQuoteQty":"0.0",
            "status":"NEW","type":"LIMIT","side":"BUY"}]"#,
        );
        let orders = binance.open_orders(Some(&symbol())).unwrap();
        assert_eq!(orders.len(), 1);
        assert_eq!(orders[0].symbol, symbol());

        // Unfiltered: the symbol is resolved from the wire form.
        mock.push_json(
            200,
            r#"[{"symbol":"ETHUSDT","orderId":2,"clientOrderId":"","price":"0.0",
            "origQty":"2.0","executedQty":"0.0","cummulativeQuoteQty":"0.0",
            "status":"NEW","type":"MARKET","side":"SELL"}]"#,
        );
        let orders = binance.open_orders(None).unwrap();
        assert_eq!(orders[0].symbol, Symbol::new("ETH", "USDT"));
        let req = &mock.recorded_requests()[1];
        assert!(!req.url.contains("symbol="));
    }

    #[test]
    fn works_as_a_boxed_exchange() {
        let (binance, mock) = signed_client(1000);
        mock.push_json(200, ORDER_JSON);
        let mut exchange: Box<dyn Exchange> = Box::new(binance);
        assert_eq!(exchange.name(), "binance");
        let order = exchange
            .place_order(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)))
            .unwrap();
        assert_eq!(order.id, "28");
    }

    const EXCHANGE_INFO: &str = r#"{"symbols":[{"symbol":"BTCUSDT","baseAsset":"BTC",
        "quoteAsset":"USDT","baseAssetPrecision":8,"quoteAssetPrecision":8,"filters":[
        {"filterType":"LOT_SIZE","minQty":"0.001","maxQty":"1000","stepSize":"0.001"},
        {"filterType":"PRICE_FILTER","minPrice":"0.01","maxPrice":"1000000","tickSize":"0.01"},
        {"filterType":"NOTIONAL","minNotional":"10"}]}]}"#;

    #[test]
    fn load_instruments_populates_filters() {
        let (mut binance, mock) = signed_client(1000);
        mock.push_json(200, EXCHANGE_INFO);
        binance.load_instruments().unwrap();
        let inst = binance.instrument(&symbol()).unwrap();
        assert_eq!(inst.filters.step_size, dec!(0.001));
        assert_eq!(inst.filters.min_notional, dec!(10));
        assert_eq!(inst.filters.tick_size, dec!(0.01));
        assert_eq!(inst.base_precision, 8);
        // The request hit exchangeInfo with no query string.
        assert!(mock.recorded_requests()[0]
            .url
            .ends_with("/api/v3/exchangeInfo"));
    }

    #[test]
    fn place_order_rejects_filter_violation_when_loaded() {
        let (mut binance, mock) = signed_client(1000);
        mock.push_json(200, EXCHANGE_INFO);
        binance.load_instruments().unwrap();
        // quantity 0.0005 < min 0.001 -> rejected locally, no order sent.
        let err = binance
            .place_order(&OrderRequest::limit_buy(
                symbol(),
                dec!(0.0005),
                dec!(20000),
            ))
            .unwrap_err();
        assert!(matches!(err, Error::Filter(_)));
        assert_eq!(mock.recorded_requests().len(), 1); // only exchangeInfo
    }

    #[test]
    fn place_order_skips_filter_check_without_instruments() {
        let (binance, mock) = signed_client(1000);
        mock.push_json(200, ORDER_JSON);
        // No load_instruments: the order is sent (best effort).
        binance
            .place_order(&OrderRequest::limit_buy(
                symbol(),
                dec!(0.0005),
                dec!(20000),
            ))
            .unwrap();
        assert!(mock.recorded_requests()[0].url.contains("/api/v3/order"));
    }

    /// `Debug` reports connection state, never secret material. A client is
    /// formatted into logs and error messages, so anything it prints is
    /// somewhere a credential must not be.
    #[test]
    fn debug_reports_state_without_credentials() {
        let (client, _http) = signed_client(1_700_000_000_000);
        let rendered = format!("{client:?}");

        assert!(rendered.starts_with("Binance {"));
        assert!(rendered.contains("authenticated: true"));
        assert!(!rendered.contains("SECRET"));
        assert!(!rendered.contains("APIKEY"));

        // A listen key is credential material too: it grants read access
        // to the account's private stream.
        assert!(rendered.contains("user_data_listen_key: false"));
        assert!(!rendered.contains("listen-key-value"));
    }

    /// The clock offset must reach the signature, not just the struct.
    ///
    /// Binance refuses a signed request whose `timestamp` is outside
    /// `recvWindow` of its own clock, so a machine a few seconds off has every
    /// order rejected -- with a message about the receive window, not about the
    /// clock. This asserts the whole path: sync, then a signed request carrying
    /// the adjusted time.
    #[test]
    fn sync_time_shifts_signed_timestamps() {
        let (mut binance, http) = signed_client(1_000_000);

        // Shape verified against the live endpoint on 2026-09-01:
        // GET https://api.binance.com/api/v3/time -> {"serverTime":1788295956083}
        http.push_json(200, r#"{"serverTime":1004500}"#);
        let offset = binance.sync_time().expect("sync must succeed");
        assert_eq!(offset, 4_500, "server is 4.5 s ahead of this machine");

        http.push_json(200, r#"{"balances":[]}"#);
        binance.balances().expect("balances must succeed");

        let signed = &http.recorded_requests()[1];
        assert!(
            signed.url.contains("timestamp=1004500"),
            "the signed request must carry the venue's time, not ours: {}",
            signed.url
        );
        assert!(
            !signed.url.contains("timestamp=1000000"),
            "the local timestamp must not survive the offset: {}",
            signed.url
        );
    }

    /// Without a sync the behaviour is exactly what it was: local time.
    #[test]
    fn unsynced_clock_signs_with_local_time() {
        let (binance, http) = signed_client(1_000_000);
        http.push_json(200, r#"{"balances":[]}"#);
        binance.balances().expect("balances must succeed");
        assert!(http.recorded_requests()[0]
            .url
            .contains("timestamp=1000000"));
    }

    /// A rate-limited response carries the venue's advised wait.
    ///
    /// The limit itself is recognised from the body -- a code in the error
    /// envelope -- while the wait arrives in the `Retry-After` header, so the
    /// two are read in different places. Until they were joined, every
    /// `RateLimited` this client raised carried `retry_after: None`: a field
    /// the error type documents, and that nothing in the crate ever filled.
    #[test]
    fn rate_limit_carries_the_venues_advised_wait() {
        let (binance, mock) = client(MarketType::Spot, false);
        mock.push_response(
            crate::transport::HttpResponse::new(429, r#"{"code":-1003,"msg":"too many requests"}"#)
                .with_header("Retry-After", "2.5"),
        );
        let err = binance.ticker(&symbol()).unwrap_err();
        let wait = std::time::Duration::from_millis(2500);
        assert!(matches!(err, Error::RateLimited { retry_after: Some(d) } if d == wait));
    }
}