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
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
//! Gate.io (v4 API) — the sixth exchange.
//!
//! Gate signs with `SIGN = hex(HMAC-SHA512(secret, sig_string))`, where
//! `sig_string = METHOD\npath\nquery\nhex(SHA512(body))\ntimestamp` (unix
//! seconds), carried in `KEY`/`SIGN`/`Timestamp` headers. Symbols use an
//! underscore (`BTC_USDT`) and there is no response envelope — success is the raw
//! JSON, errors come back as an HTTP error status with `{label, message}`.
//!
//! When built with a futures [`MarketType`](crate::MarketType), market data,
//! `place_order`, `balances` and the [`Derivatives`] trait route to the
//! USDT-margined perpetual endpoints (`/api/v4/futures/usdt/*`), where orders
//! carry a signed integer contract `size`. `query_order`/`cancel_order`/
//! `open_orders` route to the futures order endpoints too, parsing the futures
//! order object (numeric id, signed `size`, `finish_as`) via
//! `futures_order_from_raw`.
//!
//! [`AdvancedOrders`]: STP via `stp_act` on order create, native in-place amend
//! (`PATCH /api/v4/spot/orders/{id}`) and native spot batch place/cancel
//! (`/api/v4/spot/batch_orders`, `/cancel_batch_orders`, per-order `succeeded`
//! flag). Gate has no OCO order-list, so `place_oco` is a documented gap.

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, LongShortRatio, MarkIndex, OpenInterest,
};
use crate::normalize::{format_decimal, parse_decimal};
use crate::options::{ExchangeOptions, MarginMode, MarketType, PositionMode, SelfTradePrevention};
use crate::positions::{Position, PositionSide};
use crate::signing::{hmac_sha512_hex, sha512_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::prelude::ToPrimitive;
use rust_decimal::Decimal;
use serde::Deserialize;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
use wickra_core::Candle;

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 Gate.io client over injected transports.
pub struct Gate {
    http: Box<dyn HttpTransport>,
    ws: Option<Box<dyn WsTransport>>,
    rest_base: String,
    market_type: MarketType,
    /// One-way or hedge. Gate calls hedge "dual mode", and a dual-mode close is
    /// expressed with `auto_size` rather than with `reduce_only`.
    position_mode: PositionMode,
    credentials: Option<Credentials>,
    now_ms: Box<dyn Fn() -> i64 + Send + Sync>,
    /// 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,
    connection: Option<Box<dyn WsConnection>>,
    sub_messages: Vec<String>,
    subscriptions: Vec<(String, Symbol)>,
    /// The futures account's user id, fetched once for the private stream.
    ///
    /// Gate addresses its futures private channels to a user id where the spot
    /// ones need none, so it is looked up on first subscribe and kept.
    futures_user_id: RefCell<Option<String>>,
    /// Which derivatives channels are subscribed, per contract.
    ///
    /// `futures.tickers` carries the funding rate, the mark price and the
    /// index beside the quote, so one frame can answer three subscriptions.
    derivatives_channels: Vec<(String, DerivativesChannel)>,
    /// Leverage applied when switching to isolated margin. Gate couples the
    /// margin mode with its leverage endpoint (`leverage=0` = cross), so
    /// [`set_leverage`](Self::set_leverage) records the value here.
    leverage: u32,
    /// The private user-data connection, opened by
    /// [`subscribe_user_data`](Self::subscribe_user_data) and drained by
    /// [`poll_events`](Self::poll_events) alongside the public stream.
    private_connection: Option<Box<dyn WsConnection>>,
    /// Set once the private stream is subscribed, so [`poll_events`](Self::poll_events)
    /// re-subscribes it after a drop.
    user_data_active: bool,
    /// A dedicated logged-in connection to the WebSocket order API, opened lazily
    /// on the first [`place_order_ws`](Self::place_order_ws) /
    /// [`cancel_order_ws`](Self::cancel_order_ws) call.
    ws_api_connection: Option<Box<dyn WsConnection>>,
}

/// 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 Gate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Gate")
            .field("ws", &self.ws.is_some())
            .field("rest_base", &self.rest_base)
            .field("market_type", &self.market_type)
            .field("authenticated", &self.credentials.is_some())
            .field("clock_offset_ms", &self.clock.offset_ms())
            .field("connection", &self.connection.is_some())
            .field("sub_messages", &self.sub_messages.len())
            .field("subscriptions", &self.subscriptions.len())
            .field("leverage", &self.leverage)
            .field("private_connection", &self.private_connection.is_some())
            .field("user_data_active", &self.user_data_active)
            .field("ws_api_connection", &self.ws_api_connection.is_some())
            .finish_non_exhaustive()
    }
}

impl Gate {
    /// 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("Gate.io", 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: "https://api.gateio.ws".to_string(),
            market_type: options.market_type,
            position_mode: options.position_mode,
            credentials,
            now_ms: Box::new(system_now_ms),
            clock: ServerClock::new(),
            connection: None,
            sub_messages: Vec::new(),
            subscriptions: Vec::new(),
            futures_user_id: RefCell::new(None),
            derivatives_channels: Vec::new(),
            leverage: 1,
            private_connection: None,
            user_data_active: false,
            ws_api_connection: None,
        }
    }

    /// The timestamp a signed request must carry: this machine's clock plus the
    /// offset learned from the venue.
    ///
    /// A venue rejects a signed request whose timestamp falls outside its own
    /// receive window, so a machine a few seconds off has every order refused --
    /// with a message about the 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, from
    /// `GET /api/v4/spot/time`.
    ///
    /// Explicit rather than automatic: 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 local_before = (self.now_ms)();
        let value = self.get("/api/v4/spot/time", "")?;
        let server_ms = value
            .get("server_time")
            .and_then(serde_json::Value::as_i64)
            .ok_or_else(|| Error::Deserialization("spot/time: no server_time".into()))?;
        self.clock.sync(local_before, server_ms);
        Ok(self.clock.offset_ms())
    }

    /// Whether this client targets Gate USDT-margined perpetual futures
    /// (`/api/v4/futures/usdt/*`) rather than spot.
    fn is_futures(&self) -> bool {
        self.market_type.is_derivatives()
    }

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

    /// Build an authenticated Gate.io client.
    #[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 (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.
    #[must_use]
    pub fn with_ws(mut self, ws: Box<dyn WsTransport>) -> Self {
        self.ws = Some(ws);
        self
    }

    /// The Gate wire symbol for a canonical [`Symbol`] (`BTC/USDT` -> `BTC_USDT`).
    #[must_use]
    pub fn wire_symbol(symbol: &Symbol) -> String {
        format!("{}_{}", symbol.base(), symbol.quote())
    }

    /// A ticker for `symbol`.
    ///
    /// # Errors
    /// Returns an [`Error`] if the request fails or the symbol is unknown.
    pub fn ticker(&self, symbol: &Symbol) -> Result<Ticker> {
        if self.is_futures() {
            return self.futures_ticker(symbol);
        }
        let query = format!("currency_pair={}", Self::wire_symbol(symbol));
        let value = self.get("/api/v4/spot/tickers", &query)?;
        let list: Vec<RawTicker> = parse_json(value)?;
        let entry = list
            .into_iter()
            .next()
            .ok_or_else(|| Error::NotFound(format!("no ticker for {symbol}")))?;
        Ok(Ticker {
            symbol: symbol.clone(),
            last: parse_decimal(&entry.last)?,
            bid: parse_decimal(&entry.highest_bid)?,
            ask: parse_decimal(&entry.lowest_ask)?,
            volume: parse_decimal(&entry.base_volume)?,
            // Gate's spot ticker carries no timestamp; verified against the
            // live endpoint.
            timestamp: 0,
        })
    }

    /// A futures ticker. Gate's perpetual ticker carries `last`/`volume_24h_base`
    /// but no best bid/ask, so the top of the futures order book supplies those.
    fn futures_ticker(&self, symbol: &Symbol) -> Result<Ticker> {
        let contract = Self::wire_symbol(symbol);
        let value = self.get(
            "/api/v4/futures/usdt/tickers",
            &format!("contract={contract}"),
        )?;
        let list: Vec<RawFuturesTicker> = parse_json(value)?;
        let entry = list
            .into_iter()
            .next()
            .ok_or_else(|| Error::NotFound(format!("no ticker for {symbol}")))?;
        let book = self.order_book(symbol, 1)?;
        Ok(Ticker {
            symbol: symbol.clone(),
            last: parse_decimal(&entry.last)?,
            bid: book.bids.first().map_or(Decimal::ZERO, |l| l.price),
            ask: book.asks.first().map_or(Decimal::ZERO, |l| l.price),
            volume: parse_decimal(&entry.volume_24h_base)?,
            // Gate's futures ticker carries no timestamp either.
            timestamp: 0,
        })
    }

    /// Up to `limit` candles for `symbol` at `interval` (unified). Gate returns
    /// oldest-first, already chronological.
    ///
    /// # 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>> {
        if self.is_futures() {
            let query = format!(
                "contract={}&interval={}&limit={limit}",
                Self::wire_symbol(symbol),
                map_interval(interval),
            );
            let value = self.get("/api/v4/futures/usdt/candlesticks", &query)?;
            let rows: Vec<RawFuturesCandle> = parse_json(value)?;
            return rows.iter().map(parse_futures_candle).collect();
        }
        let query = format!(
            "currency_pair={}&interval={}&limit={limit}",
            Self::wire_symbol(symbol),
            map_interval(interval),
        );
        let value = self.get("/api/v4/spot/candlesticks", &query)?;
        let rows: Vec<Vec<String>> = parse_json(value)?;
        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> {
        if self.is_futures() {
            let query = format!("contract={}&limit={depth}", Self::wire_symbol(symbol));
            let value = self.get("/api/v4/futures/usdt/order_book", &query)?;
            let raw: RawFuturesDepth = parse_json(value)?;
            return Ok(OrderBookSnapshot {
                symbol: symbol.clone(),
                last_update_id: raw.id,
                bids: parse_futures_levels(&raw.bids)?,
                asks: parse_futures_levels(&raw.asks)?,
                timestamp: 0,
            });
        }
        let query = format!("currency_pair={}&limit={depth}", Self::wire_symbol(symbol));
        let value = self.get("/api/v4/spot/order_book", &query)?;
        let raw: RawDepth = parse_json(value)?;
        Ok(OrderBookSnapshot {
            symbol: symbol.clone(),
            last_update_id: raw.update,
            bids: parse_levels(&raw.bids)?,
            asks: parse_levels(&raw.asks)?,
            // `update` is the book's own last-change time in milliseconds,
            // which is also what the client uses as the sequence id.
            timestamp: i64::try_from(raw.update).unwrap_or(0),
        })
    }

    /// Subscribe to a pushed derivatives channel.
    ///
    /// Gate publishes the funding rate, the mark price and the index price
    /// inside the `futures.tickers` frame -- one reading at one moment -- so
    /// `Funding` and `MarkIndex` are the same subscription seen two ways.
    ///
    /// `Liquidations` is refused. Gate has a `futures.liquidates` channel, but
    /// it answers an anonymous subscribe with *"authentication required for
    /// Channel futures.liquidates"*: it reports the caller's own liquidations,
    /// not the venue's forced flow, so it is not the public feed this channel
    /// means.
    ///
    /// # Errors
    /// Returns an [`Error`] on a spot client, for `Liquidations`, 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(
                "Gate.io",
                "a derivatives channel on a spot client",
                "funding and mark/index exist only on the futures venue",
            ));
        }
        if channel == DerivativesChannel::Liquidations {
            return Err(Error::unsupported_field(
                "Gate.io",
                "a liquidations channel",
                "Gate's `futures.liquidates` needs authentication and reports the \
                 caller's own liquidations, not the venue's forced flow",
            ));
        }
        let wire = Self::wire_symbol(symbol);
        if !self
            .derivatives_channels
            .iter()
            .any(|(w, c)| w == &wire && *c == channel)
        {
            self.derivatives_channels.push((wire, channel));
        }
        self.subscribe(symbol, "spot.tickers")
    }

    /// The current open interest
    /// (`GET /futures/usdt/contract_stats`), most recent point.
    ///
    /// Polled, not pushed. The figure is in contracts, the unit this client's
    /// futures order path takes. The row's `time` is in *seconds*, where every
    /// other stamp in this crate is milliseconds.
    ///
    /// # Errors
    /// Returns an [`Error`] on a spot client, if the request fails, or if the
    /// venue returns no data point.
    pub fn open_interest(&self, symbol: &Symbol) -> Result<OpenInterest> {
        if !self.is_futures() {
            return Err(Error::unsupported_field(
                "Gate.io",
                "open interest on a spot client",
                "open interest is a futures figure",
            ));
        }
        let point = self.contract_stats(symbol)?;
        Ok(OpenInterest {
            symbol: symbol.clone(),
            open_interest: parse_decimal(
                &point
                    .get("open_interest")
                    .and_then(serde_json::Value::as_i64)
                    .ok_or_else(|| Error::Deserialization("no open_interest".to_string()))?
                    .to_string(),
            )?,
            timestamp: stats_millis(&point),
        })
    }

    /// The current long/short account ratio
    /// (`GET /futures/usdt/contract_stats`), most recent point.
    ///
    /// Polled, not pushed. Gate publishes `lsr_account`, the ratio of long
    /// accounts to short ones, where Binance publishes the two proportions.
    /// With two categories the conversion is exact and sums to one.
    ///
    /// # 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(
                "Gate.io",
                "long/short positioning on a spot client",
                "positioning is a futures figure",
            ));
        }
        let point = self.contract_stats(symbol)?;
        let ratio = point
            .get("lsr_account")
            .and_then(serde_json::Value::as_f64)
            .and_then(|r| parse_decimal(&r.to_string()).ok())
            .ok_or_else(|| Error::Deserialization("no lsr_account".to_string()))?;
        let total = Decimal::ONE + ratio;
        if total.is_zero() {
            return Err(Error::Deserialization(
                "a long/short ratio of -1 has no proportions".to_string(),
            ));
        }
        Ok(LongShortRatio {
            symbol: symbol.clone(),
            long_size: ratio / total,
            short_size: Decimal::ONE / total,
            timestamp: stats_millis(&point),
        })
    }

    /// The newest `contract_stats` row, which carries both polled figures.
    fn contract_stats(&self, symbol: &Symbol) -> Result<serde_json::Value> {
        let query = format!("contract={}&limit=1", Self::wire_symbol(symbol));
        let value = self.get("/futures/usdt/contract_stats", &query)?;
        value
            .as_array()
            .and_then(|rows| rows.first())
            .cloned()
            .ok_or_else(|| Error::NotFound("no contract-stats data point".to_string()))
    }

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

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

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

    fn subscribe(&mut self, symbol: &Symbol, channel: &str) -> Result<()> {
        self.ensure_market_is_routed()?;
        // Gate serves spot and futures from different hosts with differently
        // named channels, so both follow the market the client is on. The
        // channel arrives spelled `spot.<name>`; on a futures client the prefix
        // is swapped rather than the call sites being duplicated.
        let futures = self.is_futures();
        let channel = if futures {
            &channel.replace("spot.", "futures.")
        } else {
            channel
        };
        let wire = Self::wire_symbol(symbol);
        if self.connection.is_none() {
            let ws = self.ws.as_ref().ok_or(Error::NotConnected)?;
            let url = if futures {
                FUTURES_WS_URL
            } else {
                "wss://api.gateio.ws/ws/v4/"
            };
            let connection = ws.connect(url)?;
            self.connection = Some(connection);
        }
        let time = self.signed_now_ms() / 1000;
        // `futures.order_book_update` needs an interval and a depth beside the
        // contract; the other channels take the contract alone.
        let payload = if channel == "futures.order_book_update" {
            format!(r#""{wire}","100ms","20""#)
        } else {
            format!(r#""{wire}""#)
        };
        let message = format!(
            r#"{{"time":{time},"channel":"{channel}","event":"subscribe","payload":[{payload}]}}"#
        );
        self.connection
            .as_mut()
            .expect("connection just ensured")
            .send(&message)?;
        if !self.sub_messages.contains(&message) {
            self.sub_messages.push(message.clone());
        }
        if !self.subscriptions.iter().any(|(w, _)| w == &wire) {
            self.subscriptions.push((wire, symbol.clone()));
        }
        Ok(())
    }

    /// Drain all stream events available since the last call. Non-blocking.
    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 subscribed = |wire: &str, channel: DerivativesChannel| {
            channels.iter().any(|(w, c)| w == wire && *c == channel)
        };
        let mut events = Vec::new();
        if let Some(connection) = self.connection.as_mut() {
            while let Ok(Some(frame)) = connection.recv() {
                if let Ok(mut parsed) = parse_ws_message(&frame, &resolve, &subscribed) {
                    events.append(&mut parsed);
                }
            }
        }
        // Drain the private user-data stream (spot.orders/spot.balances), if open.
        if let Some(connection) = self.private_connection.as_mut() {
            while let Ok(Some(frame)) = connection.recv() {
                if let Ok(mut parsed) = parse_ws_message(&frame, &resolve, &subscribed) {
                    events.append(&mut parsed);
                }
            }
        }
        // A dropped private stream is re-subscribed with fresh signed frames (the
        // per-channel signature is time-bound, so a stale replay would be rejected).
        if self.user_data_active
            && self
                .private_connection
                .as_ref()
                .is_some_and(|c| !c.is_connected())
        {
            events.push(Event::Disconnected);
            self.private_connection = None;
            if self.subscribe_user_data().is_ok() {
                events.push(Event::Reconnected);
            }
        }
        let url = "wss://api.gateio.ws/ws/v4/";
        crate::wsutil::reconnect_if_dropped(
            self.ws.as_deref(),
            url,
            &mut self.connection,
            &self.sub_messages,
            &mut events,
        );
        events
    }

    /// Open the private user-data stream (`wss://api.gateio.ws/ws/v4/`). Sends
    /// signed `subscribe` frames for the `spot.orders` and `spot.balances`
    /// channels (each carries an `auth` object whose `SIGN` is HMAC-SHA512 over
    /// `channel=<channel>&event=subscribe&time=<time>`). Afterwards
    /// [`poll_events`](Self::poll_events) also surfaces the account's own
    /// [`Event::OrderUpdate`] and [`Event::BalanceUpdate`].
    ///
    /// A dropped private stream is re-subscribed automatically on the next
    /// [`poll_events`](Self::poll_events); call
    /// [`keepalive_user_data`](Self::keepalive_user_data) periodically to keep it
    /// from being dropped for inactivity.
    ///
    /// # Errors
    /// Returns [`Error::InvalidCredentials`] without credentials,
    /// [`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()?;
        // Spot and futures are separate accounts on separate hosts: a futures
        // order never appears in the spot account, so watching the wrong one is
        // waiting for a fill that cannot arrive.
        //
        // The futures channels are addressed to a **user id**, which the spot
        // ones are not, so it is fetched first -- once, and cached. Subscribing
        // without it is a subscription to nobody.
        let futures = self.is_futures();
        let user_id = if futures {
            Some(self.futures_user_id()?)
        } else {
            None
        };
        let creds = self.credentials.as_ref().ok_or(Error::InvalidCredentials(
            "user-data stream requires credentials",
        ))?;
        let time = self.signed_now_ms() / 1000;
        // The futures private channels live on the same socket as the public
        // futures ones -- Gate separates them by authentication, not by host.
        let url = if futures {
            FUTURES_WS_URL
        } else {
            "wss://api.gateio.ws/ws/v4/"
        };
        let ws = self.ws.as_ref().ok_or(Error::NotConnected)?;
        let mut connection = ws.connect(url)?;
        // `spot.orders` takes `!all` to cover every pair; `spot.balances` takes
        // no payload. The futures pair is addressed to the user id instead, and
        // `!all` again covers every contract.
        let futures_orders = user_id
            .as_ref()
            .map(|id| format!(r#"["{id}","!all"]"#))
            .unwrap_or_default();
        let futures_balances = user_id
            .as_ref()
            .map(|id| format!(r#"["{id}"]"#))
            .unwrap_or_default();
        let channels: [(&str, &str); 2] = if futures {
            [
                ("futures.orders", futures_orders.as_str()),
                ("futures.balances", futures_balances.as_str()),
            ]
        } else {
            [("spot.orders", r#"["!all"]"#), ("spot.balances", "[]")]
        };
        for (channel, payload) in channels {
            let sign_string = format!("channel={channel}&event=subscribe&time={time}");
            let sign = hmac_sha512_hex(creds.api_secret.as_bytes(), sign_string.as_bytes());
            let message = format!(
                r#"{{"time":{time},"channel":"{channel}","event":"subscribe","payload":{payload},"auth":{{"method":"api_key","KEY":"{}","SIGN":"{sign}"}}}}"#,
                creds.api_key
            );
            connection.send(&message)?;
        }
        self.private_connection = Some(connection);
        self.user_data_active = true;
        Ok(())
    }

    /// Send an application-level heartbeat (the `ping` text frame) on the private
    /// stream so it is not dropped for inactivity. A no-op before
    /// [`subscribe_user_data`](Self::subscribe_user_data).
    ///
    /// # Errors
    /// Returns an [`Error`] if the ping cannot be sent.
    pub fn keepalive_user_data(&mut self) -> Result<()> {
        if let Some(connection) = self.private_connection.as_mut() {
            connection.send("ping")?;
        }
        Ok(())
    }

    /// Place a spot order over the Gate WebSocket order API (`spot.order_place`).
    /// Logs into a dedicated connection on first use (`spot.login`, signature =
    /// HMAC-SHA512 over `api\nspot.login\n\n<timestamp>`), then exchanges the same
    /// order args as the REST path.
    ///
    /// # Errors
    /// Returns [`Error::Exchange`] on the **futures** client (this binding's WS
    /// order API covers spot), [`Error::NotConnected`] without a WebSocket
    /// transport, or another [`Error`] if the order is invalid or rejected.
    pub fn place_order_ws(&mut self, request: &OrderRequest) -> Result<Order> {
        if request.order_type.is_trigger() {
            return Err(Error::unsupported_trigger("Gate.io"));
        }
        self.ensure_reduce_only_is_reducible(request)?;
        request.validate()?;
        if self.is_futures() {
            return Err(Error::Exchange {
                code: "unsupported".to_string(),
                message: "Gate's WebSocket order API is wired for spot here; place \
                          futures orders over REST (/api/v4/futures/usdt/orders)"
                    .to_string(),
            });
        }
        let mut req_param = serde_json::json!({
            "currency_pair": Self::wire_symbol(&request.symbol),
            "type": order_type_str(request.order_type),
            "account": "spot",
            "side": side_str(request.side),
            "amount": format_decimal(request.quantity),
        });
        if let Some(price) = request.price {
            req_param["price"] = serde_json::json!(format_decimal(price));
        }
        if let Some(tif) = tif_str(request)? {
            req_param["time_in_force"] = serde_json::json!(tif);
        }
        if let Some(id) = &request.client_order_id {
            let text = if id.starts_with("t-") {
                id.clone()
            } else {
                format!("t-{id}")
            };
            req_param["text"] = serde_json::json!(text);
        }
        if let Some(act) = stp_act_str(request.stp) {
            req_param["stp_act"] = serde_json::json!(act);
        }
        let result = self.ws_api_request("spot.order_place", &req_param)?;
        let raw: RawOrder =
            serde_json::from_value(result).map_err(|e| Error::Deserialization(e.to_string()))?;
        order_from_raw(request.symbol.clone(), &raw)
    }

    /// Cancel a spot order over the Gate WebSocket order API (`spot.order_cancel`).
    ///
    /// # Errors
    /// Returns [`Error::Exchange`] on the futures client, [`Error::NotConnected`]
    /// without a WebSocket transport, or another [`Error`] if the request fails.
    pub fn cancel_order_ws(&mut self, symbol: &Symbol, order_id: &str) -> Result<()> {
        if self.is_futures() {
            return Err(Error::Exchange {
                code: "unsupported".to_string(),
                message: "Gate's WebSocket order API is wired for spot here; cancel \
                          futures orders over REST"
                    .to_string(),
            });
        }
        let req_param = serde_json::json!({
            "order_id": order_id,
            "currency_pair": Self::wire_symbol(symbol),
        });
        self.ws_api_request("spot.order_cancel", &req_param)?;
        Ok(())
    }

    /// Open and log into the WebSocket order connection if needed. The `spot.login`
    /// request signs `api\nspot.login\n\n<timestamp>`; later requests on the same
    /// connection inherit the session, so they are unsigned.
    fn ensure_ws_api(&mut self) -> Result<()> {
        self.ensure_market_is_routed()?;
        if self.ws_api_connection.is_some() {
            return Ok(());
        }
        let creds = self.credentials.as_ref().ok_or(Error::InvalidCredentials(
            "WebSocket order API requires credentials",
        ))?;
        let timestamp = self.signed_now_ms() / 1000;
        let signature = hmac_sha512_hex(
            creds.api_secret.as_bytes(),
            format!("api\nspot.login\n\n{timestamp}").as_bytes(),
        );
        let req_id = format!("wkex-login-{}", (self.now_ms)());
        let login = format!(
            r#"{{"time":{timestamp},"channel":"spot.login","event":"api","payload":{{"req_id":"{req_id}","api_key":"{}","signature":"{signature}","timestamp":"{timestamp}"}}}}"#,
            creds.api_key
        );
        let ws = self.ws.as_ref().ok_or(Error::NotConnected)?;
        let mut connection = ws.connect("wss://api.gateio.ws/ws/v4/")?;
        connection.send(&login)?;
        connection.recv()?; // consume the login acknowledgement
        self.ws_api_connection = Some(connection);
        Ok(())
    }

    /// Send an order-API request frame and return its `data.result`, mapping a
    /// non-`"200"` header status onto the error taxonomy.
    fn ws_api_request(
        &mut self,
        channel: &str,
        req_param: &serde_json::Value,
    ) -> Result<serde_json::Value> {
        self.ensure_ws_api()?;
        let time = self.signed_now_ms() / 1000;
        let req_id = format!("wkex-{}", (self.now_ms)());
        let frame = serde_json::json!({
            "time": time,
            "channel": channel,
            "event": "api",
            "payload": { "req_id": req_id, "req_param": req_param },
        })
        .to_string();
        let connection = self
            .ws_api_connection
            .as_mut()
            .expect("ws order 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("header")
            .and_then(|header| header.get("status"))
            .and_then(serde_json::Value::as_str)
            .unwrap_or("");
        if status == "200" {
            Ok(value
                .get("data")
                .and_then(|data| data.get("result"))
                .cloned()
                .unwrap_or(serde_json::Value::Null))
        } else {
            let errs = value.get("data").and_then(|data| data.get("errs"));
            let label = errs
                .and_then(|e| e.get("label"))
                .and_then(serde_json::Value::as_str)
                .unwrap_or("ws");
            let message = errs
                .and_then(|e| e.get("message"))
                .and_then(serde_json::Value::as_str)
                .unwrap_or("order rejected")
                .to_string();
            Err(Error::OrderRejected {
                code: label.to_string(),
                message,
            })
        }
    }

    /// Place an order.
    ///
    /// # Errors
    /// Returns an [`Error`] if the order is invalid, credentials are missing, or
    /// the venue rejects it.
    /// Refuse `reduce_only` where there is no position to reduce.
    ///
    /// A spot account holds balances, not positions, so a reduce-only order has
    /// nothing to close. Dropping the flag would place an opening order where a
    /// closing one was asked for -- the opposite trade -- so it is refused, the
    /// way Binance's spot path and Upbit already refuse it.
    fn ensure_reduce_only_is_reducible(&self, request: &OrderRequest) -> Result<()> {
        if request.reduce_only && !self.is_futures() {
            return Err(Error::unsupported_field(
                "Gate.io",
                "reduce_only on a spot order",
                "spot holds balances, not positions, and has none to reduce",
            ));
        }
        Ok(())
    }

    /// Place a trigger order through Gate's price-order endpoint.
    ///
    /// Gate calls these *price* orders and nests them: a `trigger` says when to
    /// act and a `put` says what to place. Spot and futures use different
    /// shapes for both halves.
    ///
    /// `rule` is the comparison, and Gate will not infer it: `2` is "at or
    /// below", which is what protects a long, and `1` is "at or above", which
    /// covers a short. The wrong rule arms the order on the side that never
    /// comes.
    ///
    /// **Gate's spot price order can only place a limit.** A stop-market is
    /// refused rather than sent with an invented limit price, since that price
    /// decides how much slippage the caller's stop may take. Futures has no such
    /// limit: a `price` of `0` there means "take the market".
    ///
    /// # Errors
    /// Returns an [`Error`] if the trigger price is missing, if a spot
    /// stop-market is asked for, or if the request fails.
    fn place_price_order(&self, request: &OrderRequest) -> Result<Order> {
        let stop = request
            .stop_price
            .ok_or(Error::InvalidOrder("a trigger order requires a stop price"))?;
        // Selling to protect a long fires on the way down; buying to cover a
        // short fires on the way up.
        let rule = match request.side {
            OrderSide::Sell => 2,
            OrderSide::Buy => 1,
        };
        let (path, body) = if self.is_futures() {
            let size = decimal_to_contracts(request.quantity)?;
            let size = match request.side {
                OrderSide::Buy => size,
                OrderSide::Sell => -size,
            };
            (
                "/api/v4/futures/usdt/price_orders",
                serde_json::json!({
                    "initial": {
                        "contract": Self::wire_symbol(&request.symbol),
                        "size": size,
                        // `0` is Gate's "take the market" on a futures price
                        // order; a limit is sent as itself.
                        "price": request.price.map_or_else(
                            || "0".to_string(),
                            format_decimal,
                        ),
                    },
                    "trigger": {
                        "strategy_type": 0,
                        // 0 is the last traded price; 1 the mark, 2 the index.
                        "price_type": 0,
                        "price": format_decimal(stop),
                        "rule": rule,
                    },
                }),
            )
        } else {
            let Some(price) = request.price else {
                return Err(Error::unsupported_field(
                    "Gate.io",
                    "a spot stop-market order",
                    "Gate's spot price order can only place a limit, and choosing \
                     one here would decide how much slippage the caller's stop may take",
                ));
            };
            (
                "/api/v4/spot/price_orders",
                serde_json::json!({
                    "market": Self::wire_symbol(&request.symbol),
                    "trigger": {
                        "price": format_decimal(stop),
                        "rule": if rule == 2 { "<=" } else { ">=" },
                        // Zero is Gate's "no expiry" on a spot price order.
                        "expiration": 0,
                    },
                    "put": {
                        "type": "limit",
                        "side": side_str(request.side),
                        "price": format_decimal(price),
                        "amount": format_decimal(request.quantity),
                        "account": "normal",
                        "time_in_force": "gtc",
                    },
                }),
            )
        };
        let value = self.signed_request(HttpMethod::Post, path, "", &body.to_string())?;
        Ok(Order {
            id: value
                .get("id")
                .map(|id| match id.as_str() {
                    Some(text) => text.to_string(),
                    None => id.to_string(),
                })
                .unwrap_or_default(),
            client_order_id: request.client_order_id.clone(),
            symbol: request.symbol.clone(),
            side: request.side,
            order_type: request.order_type,
            status: OrderStatus::New,
            quantity: request.quantity,
            filled_quantity: Decimal::ZERO,
            price: request.price,
            average_price: None,
        })
    }

    pub fn place_order(&self, request: &OrderRequest) -> Result<Order> {
        self.ensure_reduce_only_is_reducible(request)?;
        request.validate()?;
        // A trigger is a different endpoint here, with a different body shape.
        if request.order_type.is_trigger() {
            return self.place_price_order(request);
        }
        if self.is_futures() {
            return self.place_futures_order(request);
        }
        let mut body = serde_json::json!({
            "currency_pair": Self::wire_symbol(&request.symbol),
            "side": side_str(request.side),
            "type": order_type_str(request.order_type),
            "amount": format_decimal(request.quantity),
        });
        if let Some(price) = request.price {
            body["price"] = serde_json::json!(format_decimal(price));
        }
        if let Some(tif) = tif_str(request)? {
            body["time_in_force"] = serde_json::json!(tif);
        }
        if let Some(id) = &request.client_order_id {
            let text = if id.starts_with("t-") {
                id.clone()
            } else {
                format!("t-{id}")
            };
            body["text"] = serde_json::json!(text);
        }
        if let Some(act) = stp_act_str(request.stp) {
            body["stp_act"] = serde_json::json!(act);
        }
        let value = self.signed_request(
            HttpMethod::Post,
            "/api/v4/spot/orders",
            "",
            &body.to_string(),
        )?;
        let raw: RawOrder = parse_json(value)?;
        order_from_raw(request.symbol.clone(), &raw)
    }

    /// 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<()> {
        if self.is_futures() {
            let path = format!("/api/v4/futures/usdt/orders/{order_id}");
            self.signed_request(HttpMethod::Delete, &path, "", "")?;
            return Ok(());
        }
        let path = format!("/api/v4/spot/orders/{order_id}");
        let query = format!("currency_pair={}", Self::wire_symbol(symbol));
        self.signed_request(HttpMethod::Delete, &path, &query, "")?;
        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> {
        if self.is_futures() {
            let path = format!("/api/v4/futures/usdt/orders/{order_id}");
            let value = self.signed_request(HttpMethod::Get, &path, "", "")?;
            let raw: RawFuturesOrder = parse_json(value)?;
            return futures_order_from_raw(symbol.clone(), &raw);
        }
        let path = format!("/api/v4/spot/orders/{order_id}");
        let query = format!("currency_pair={}", Self::wire_symbol(symbol));
        let value = self.signed_request(HttpMethod::Get, &path, &query, "")?;
        let raw: RawOrder = parse_json(value)?;
        order_from_raw(symbol.clone(), &raw)
    }

    /// Open orders for one `symbol` (Gate requires a currency pair / contract here).
    ///
    /// # Errors
    /// Returns an [`Error`] if credentials are missing, no symbol is given, or the
    /// request fails.
    pub fn open_orders(&self, symbol: Option<&Symbol>) -> Result<Vec<Order>> {
        let sym = symbol.ok_or(Error::InvalidOrder("Gate open_orders requires a symbol"))?;
        if self.is_futures() {
            let query = format!("contract={}&status=open", Self::wire_symbol(sym));
            let value =
                self.signed_request(HttpMethod::Get, "/api/v4/futures/usdt/orders", &query, "")?;
            let list: Vec<RawFuturesOrder> = parse_json(value)?;
            return list
                .iter()
                .map(|raw| futures_order_from_raw(sym.clone(), raw))
                .collect();
        }
        let query = format!("currency_pair={}&status=open", Self::wire_symbol(sym));
        let value = self.signed_request(HttpMethod::Get, "/api/v4/spot/orders", &query, "")?;
        let list: Vec<RawOrder> = parse_json(value)?;
        list.iter()
            .map(|raw| order_from_raw(sym.clone(), raw))
            .collect()
    }

    /// The futures account's user id, fetched once and cached.
    ///
    /// Gate's futures private channels are addressed to a user id where the
    /// spot ones are not: `futures.orders` takes `[user_id, contract]`. The id
    /// comes back on the account call the balance path already uses.
    ///
    /// # Errors
    /// Returns an [`Error`] if credentials are missing or the request fails.
    fn futures_user_id(&self) -> Result<String> {
        if let Some(id) = self.futures_user_id.borrow().clone() {
            return Ok(id);
        }
        let value =
            self.signed_request(HttpMethod::Get, "/api/v4/futures/usdt/accounts", "", "")?;
        let id = value
            .get("user")
            .map(|user| {
                user.as_str()
                    .map_or_else(|| user.to_string(), str::to_string)
            })
            .ok_or_else(|| Error::Deserialization("futures account has no user id".to_string()))?;
        *self.futures_user_id.borrow_mut() = Some(id.clone());
        Ok(id)
    }

    /// Spot account balances.
    ///
    /// # Errors
    /// Returns an [`Error`] if credentials are missing or the request fails.
    pub fn balances(&self) -> Result<Vec<Balance>> {
        if self.is_futures() {
            let value =
                self.signed_request(HttpMethod::Get, "/api/v4/futures/usdt/accounts", "", "")?;
            let acct: RawFuturesAccount = parse_json(value)?;
            let total = dec_or_zero(&acct.total);
            let available = dec_or_zero(&acct.available);
            return Ok(vec![Balance {
                asset: acct.currency,
                free: available,
                locked: (total - available).max(Decimal::ZERO),
            }]);
        }
        let value = self.signed_request(HttpMethod::Get, "/api/v4/spot/accounts", "", "")?;
        let list: Vec<RawAccount> = parse_json(value)?;
        Ok(list
            .iter()
            .map(|a| Balance {
                asset: a.currency.clone(),
                free: dec_or_zero(&a.available),
                locked: dec_or_zero(&a.locked),
            })
            .collect())
    }

    /// Place a Gate USDT-margined futures order. Futures orders carry a **signed
    /// integer `size`** (contracts; positive = long/buy, negative = short/sell)
    /// and use `price="0"` with `tif="ioc"` for market orders.
    fn place_futures_order(&self, request: &OrderRequest) -> Result<Order> {
        let contract = Self::wire_symbol(&request.symbol);
        let magnitude = decimal_to_contracts(request.quantity)?;
        let size = match request.side {
            OrderSide::Buy => magnitude,
            OrderSide::Sell => -magnitude,
        };
        let mut body = if self.position_mode == PositionMode::Hedge && request.reduce_only {
            // In dual mode a close names the side it closes and carries no size
            // of its own: Gate reads `auto_size` and requires `size` to be 0.
            // `reduce_only` alone is the one-way spelling and does not say which
            // of the two open sides is meant.
            let auto_size = match PositionSide::for_order(request.side, true) {
                PositionSide::Long => "close_long",
                PositionSide::Short => "close_short",
            };
            serde_json::json!({
                "contract": contract,
                "size": 0,
                "auto_size": auto_size,
                "reduce_only": true,
            })
        } else {
            // Opening in dual mode needs nothing extra: the sign of `size`
            // already says which side grows.
            serde_json::json!({
                "contract": contract,
                "size": size,
                "reduce_only": request.reduce_only,
            })
        };
        match request.order_type {
            OrderType::Market | OrderType::StopMarket => {
                // A Gate futures market order is a zero-price IOC; the venue has
                // no other spelling for it, so a caller asking for FOK is asking
                // for an order this path cannot place.
                if request.time_in_force == TimeInForce::Fok {
                    return Err(Error::unsupported_field(
                        "Gate.io",
                        "a FOK time-in-force on a futures market order",
                        "the futures market order is a zero-price IOC",
                    ));
                }
                body["price"] = serde_json::json!("0");
                body["tif"] = serde_json::json!("ioc");
            }
            OrderType::Limit | OrderType::StopLimit => {
                let price = request
                    .price
                    .ok_or(Error::InvalidOrder("limit order requires a price"))?;
                body["price"] = serde_json::json!(format_decimal(price));
                if let Some(tif) = tif_str(request)? {
                    body["tif"] = serde_json::json!(tif);
                }
            }
        }
        if let Some(id) = &request.client_order_id {
            let text = if id.starts_with("t-") {
                id.clone()
            } else {
                format!("t-{id}")
            };
            body["text"] = serde_json::json!(text);
        }
        let value = self.signed_request(
            HttpMethod::Post,
            "/api/v4/futures/usdt/orders",
            "",
            &body.to_string(),
        )?;
        let raw: RawFuturesOrder = parse_json(value)?;
        futures_order_from_raw(request.symbol.clone(), &raw)
    }

    /// Open positions on the USDT-margined futures account
    /// (`/api/v4/futures/usdt/positions`).
    ///
    /// # Errors
    /// Returns an [`Error`] if credentials are missing or the request fails.
    pub fn positions(&self, symbol: Option<&Symbol>) -> Result<Vec<Position>> {
        let value =
            self.signed_request(HttpMethod::Get, "/api/v4/futures/usdt/positions", "", "")?;
        let list: Vec<RawFuturesPosition> = parse_json(value)?;
        let wanted = symbol.map(Self::wire_symbol);
        Ok(list
            .iter()
            .filter(|p| p.size != 0)
            .filter(|p| wanted.as_ref().is_none_or(|w| &p.contract == w))
            .map(parse_futures_position)
            .collect())
    }

    /// Set the leverage for `symbol` (isolated margin; `leverage=0` = cross).
    ///
    /// # Errors
    /// Returns an [`Error`] if the leverage is rejected or the request fails.
    pub fn set_leverage(&mut self, symbol: &Symbol, leverage: u32) -> Result<()> {
        self.leverage = leverage.max(1);
        self.apply_leverage(symbol, leverage)
    }

    /// Switch the margin mode for `symbol`. Gate couples this with the leverage
    /// endpoint: cross is `leverage=0`, isolated re-applies the recorded leverage.
    ///
    /// # Errors
    /// Returns an [`Error`] if the change is rejected or the request fails.
    pub fn set_margin_mode(&mut self, symbol: &Symbol, mode: MarginMode) -> Result<()> {
        let leverage = match mode {
            MarginMode::Cross => 0,
            MarginMode::Isolated => self.leverage.max(1),
        };
        self.apply_leverage(symbol, leverage)
    }

    fn apply_leverage(&self, symbol: &Symbol, leverage: u32) -> Result<()> {
        let path = format!(
            "/api/v4/futures/usdt/positions/{}/leverage",
            Self::wire_symbol(symbol)
        );
        let query = format!("leverage={leverage}");
        self.signed_request(HttpMethod::Post, &path, &query, "")?;
        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)
    }

    fn get(&self, path: &str, query: &str) -> Result<serde_json::Value> {
        self.ensure_market_is_routed()?;
        let url = format!("{}{path}?{query}", self.rest_base);
        let response = self.http.execute(&HttpRequest::get(url))?;
        parse_body(&response)
    }

    /// Sign with `KEY`/`SIGN`/`Timestamp`: `SIGN = hex(HMAC-SHA512(secret,
    /// METHOD\npath\nquery\nhex(SHA512(body))\ntimestamp))`.
    fn signed_request(
        &self,
        method: HttpMethod,
        path: &str,
        query: &str,
        body: &str,
    ) -> Result<serde_json::Value> {
        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() / 1000).to_string();
        let body_hash = sha512_hex(body.as_bytes());
        let sign_string = format!(
            "{}\n{path}\n{query}\n{body_hash}\n{timestamp}",
            method.as_str()
        );
        let signature = hmac_sha512_hex(creds.api_secret.as_bytes(), sign_string.as_bytes());
        let url = if query.is_empty() {
            format!("{}{path}", self.rest_base)
        } else {
            format!("{}{path}?{query}", self.rest_base)
        };
        let mut request = HttpRequest::new(method, url)
            .with_header("KEY", creds.api_key.clone())
            .with_header("SIGN", signature)
            .with_header("Timestamp", timestamp);
        if !body.is_empty() {
            request = request
                .with_header("Content-Type", "application/json")
                .with_body(body.to_string());
        }
        let response = self.http.execute(&request)?;
        parse_body(&response)
    }
}

/// Parse a Gate response: raw JSON on success, `{label, message}` on an HTTP error.
fn parse_body(response: &HttpResponse) -> Result<serde_json::Value> {
    if response.is_success() {
        serde_json::from_str(&response.body).map_err(|e| Error::Deserialization(e.to_string()))
    } else {
        let err: GateError = serde_json::from_str(&response.body).unwrap_or(GateError {
            label: response.status.to_string(),
            message: response.body.clone(),
        });
        Err(map_error(&err.label, &err.message).with_retry_after(response.retry_after()))
    }
}

fn parse_json<T: for<'de> Deserialize<'de>>(value: serde_json::Value) -> Result<T> {
    serde_json::from_value(value).map_err(|e| Error::Deserialization(e.to_string()))
}

fn map_interval(interval: &str) -> String {
    match interval {
        "1w" => "7d",
        other => other,
    }
    .to_string()
}

fn map_error(label: &str, message: &str) -> Error {
    match label {
        "TOO_MANY_REQUESTS" | "RATE_LIMIT" => Error::RateLimited { retry_after: None },
        "INVALID_KEY" | "INVALID_SIGNATURE" | "SIGN_MISMATCH" | "AUTHENTICATION_FAILED" => {
            Error::Auth(message.to_string())
        }
        "BALANCE_NOT_ENOUGH" | "INSUFFICIENT_AVAILABLE" => Error::InsufficientBalance,
        "ORDER_NOT_FOUND" => Error::NotFound(message.to_string()),
        "INVALID_CURRENCY_PAIR" => Error::InvalidSymbol(message.to_string()),
        other => Error::Exchange {
            code: other.to_string(),
            message: message.to_string(),
        },
    }
}

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

/// The Gate `stp_act` value for a self-trade-prevention policy, or `None` to omit.
/// Gate cancels the oldest (`co`), newest (`cn`) or both (`cb`) order.
fn stp_act_str(stp: SelfTradePrevention) -> Option<&'static str> {
    match stp {
        SelfTradePrevention::None => None,
        SelfTradePrevention::ExpireMaker => Some("co"),
        SelfTradePrevention::ExpireTaker => Some("cn"),
        SelfTradePrevention::ExpireBoth => Some("cb"),
    }
}

/// Gate spells time-in-force and post-only through one field (`time_in_force`
/// on spot, `tif` on futures), because `poc` *is* a post-only GTC. That makes
/// the two settings able to conflict, so a post-only IOC/FOK is refused rather
/// than silently resolved in one direction or the other.
///
/// `Gtc` is the request default and Gate's own default, so it is left off the
/// wire; `Ioc` and `Fok` are what a dropped field would change, and they are
/// always sent.
fn tif_str(request: &OrderRequest) -> Result<Option<&'static str>> {
    match (request.post_only, request.time_in_force) {
        (true, TimeInForce::Gtc) => Ok(Some("poc")),
        (true, _) => Err(Error::unsupported_field(
            "Gate.io",
            "post_only together with a non-GTC time-in-force",
            "`poc` is Gate's post-only and is itself a time-in-force",
        )),
        (false, TimeInForce::Gtc) => Ok(None),
        (false, TimeInForce::Ioc) => Ok(Some("ioc")),
        (false, TimeInForce::Fok) => Ok(Some("fok")),
    }
}

fn order_type_str(order_type: OrderType) -> &'static str {
    match order_type {
        OrderType::Market | OrderType::StopMarket => "market",
        OrderType::Limit | OrderType::StopLimit => "limit",
    }
}

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:?}"))),
    }
}

/// Split a Gate wire pair (`BTC_USDT`) into a canonical [`Symbol`].
fn symbol_from_wire(wire: &str) -> Symbol {
    match wire.split_once('_') {
        Some((base, quote)) if !base.is_empty() && !quote.is_empty() => Symbol::new(base, quote),
        _ => Symbol::new(wire, ""),
    }
}

fn parse_order_type(raw: &str) -> Result<OrderType> {
    match raw {
        "market" => Ok(OrderType::Market),
        "limit" => Ok(OrderType::Limit),
        other => Err(Error::Deserialization(format!(
            "unknown order type {other:?}"
        ))),
    }
}

fn dec_or_zero(raw: &str) -> Decimal {
    crate::normalize::parse_opt_decimal(Some(raw))
        .ok()
        .flatten()
        .unwrap_or(Decimal::ZERO)
}

fn nonzero_decimal(raw: &str) -> Option<Decimal> {
    crate::normalize::parse_opt_decimal(Some(raw))
        .ok()
        .flatten()
        .filter(|d| *d > Decimal::ZERO)
}

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: &[String]) -> Result<Candle> {
    // Gate candle: [ts, quoteVol, close, high, low, open, baseVol, closed].
    if row.len() < 7 {
        return Err(Error::Deserialization("kline row too short".to_string()));
    }
    let ts = row[0]
        .parse::<i64>()
        .map_err(|e| Error::Deserialization(format!("kline ts not an integer: {e}")))?;
    let f = |i: usize| -> Result<f64> {
        row[i]
            .parse::<f64>()
            .map_err(|e| Error::Deserialization(format!("kline field not a number: {e}")))
    };
    // open=row[5], high=row[3], low=row[4], close=row[2], volume=row[6].
    Candle::new(f(5)?, f(3)?, f(4)?, f(2)?, f(6)?, ts)
        .map_err(|e| Error::Deserialization(e.to_string()))
}

fn order_from_raw(symbol: Symbol, raw: &RawOrder) -> Result<Order> {
    // REST reports `filled_amount` directly; the `spot.orders` stream reports the
    // remaining `left`, so the filled quantity is `amount - left`.
    let filled = if raw.filled_amount.is_empty() && !raw.left.is_empty() {
        (dec_or_zero(&raw.amount) - dec_or_zero(&raw.left)).max(Decimal::ZERO)
    } else {
        dec_or_zero(&raw.filled_amount)
    };
    let status = match raw.status.as_str() {
        "cancelled" => OrderStatus::Canceled,
        "closed" => OrderStatus::Filled,
        "open" => {
            if filled > Decimal::ZERO {
                OrderStatus::PartiallyFilled
            } else {
                OrderStatus::New
            }
        }
        other => return Err(Error::Deserialization(format!("unknown status {other:?}"))),
    };
    Ok(Order {
        id: raw.id.clone(),
        client_order_id: (!raw.text.is_empty()).then(|| raw.text.clone()),
        symbol,
        side: parse_side(&raw.side)?,
        order_type: parse_order_type(&raw.order_type)?,
        status,
        quantity: parse_decimal(&raw.amount)?,
        filled_quantity: filled,
        price: nonzero_decimal(&raw.price),
        average_price: nonzero_decimal(&raw.avg_deal_price),
    })
}

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 opt_str<'a>(value: &'a serde_json::Value, key: &str) -> &'a str {
    value
        .get(key)
        .and_then(serde_json::Value::as_str)
        .unwrap_or("")
}

fn opt_u64(value: &serde_json::Value, key: &str) -> u64 {
    value
        .get(key)
        .and_then(|v| {
            v.as_u64()
                .or_else(|| v.as_str().and_then(|s| s.parse().ok()))
        })
        .unwrap_or(0)
}

fn opt_i64(value: &serde_json::Value, key: &str) -> i64 {
    value
        .get(key)
        .and_then(|v| {
            v.as_i64()
                .or_else(|| v.as_str().and_then(|s| s.parse().ok()))
        })
        .unwrap_or(0)
}

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()
}

/// A `contract_stats` row's stamp, in milliseconds.
///
/// Gate reports it in *seconds* here, where every other stamp in this crate is
/// milliseconds. Carrying it through unconverted would date every reading to
/// 1970.
fn stats_millis(point: &serde_json::Value) -> i64 {
    point
        .get("time")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(0)
        * 1000
}

/// Gate's futures WebSocket.
const FUTURES_WS_URL: &str = "wss://fx-ws.gateio.ws/v4/ws/usdt";

/// A signed contract size from a futures frame.
///
/// Gate's futures trades carry no side field: the size is signed, and negative
/// means the aggressor sold. Sizes are in contracts, which is the unit this
/// client's futures order path already takes -- `decimal_to_contracts` rounds a
/// quantity to whole contracts rather than converting from base units, so the
/// stream and the order path speak the same number.
fn futures_signed_size(value: &serde_json::Value, key: &str) -> Option<(Decimal, OrderSide)> {
    let raw = value.get(key)?;
    let text = raw
        .as_str()
        .map(ToString::to_string)
        .or_else(|| raw.as_i64().map(|n| n.to_string()))?;
    let size = parse_decimal(&text).ok()?;
    let side = if size.is_sign_negative() {
        OrderSide::Sell
    } else {
        OrderSide::Buy
    };
    Some((size.abs(), side))
}

/// `[{p, s}]` levels from a futures book frame. A size of zero removes the
/// level, which is what the delta type already means.
fn futures_levels(value: Option<&serde_json::Value>) -> Vec<BookLevel> {
    value
        .and_then(serde_json::Value::as_array)
        .map(|rows| {
            rows.iter()
                .filter_map(|row| {
                    let size = row.get("s")?;
                    let size = size
                        .as_str()
                        .map(ToString::to_string)
                        .or_else(|| size.as_i64().map(|n| n.to_string()))?;
                    Some(BookLevel {
                        price: parse_decimal(row.get("p")?.as_str()?).ok()?,
                        quantity: parse_decimal(&size).ok()?,
                    })
                })
                .collect()
        })
        .unwrap_or_default()
}

fn parse_ws_message(
    text: &str,
    resolve: &impl Fn(&str) -> Symbol,
    subscribed: &impl Fn(&str, DerivativesChannel) -> bool,
) -> Result<Vec<Event>> {
    let value: serde_json::Value =
        serde_json::from_str(text).map_err(|e| Error::Deserialization(e.to_string()))?;
    if value.get("event").and_then(serde_json::Value::as_str) != Some("update") {
        return Ok(Vec::new()); // subscribe ack / other events
    }
    let Some(channel) = value.get("channel").and_then(serde_json::Value::as_str) else {
        return Ok(Vec::new());
    };
    let null = serde_json::Value::Null;
    let result = value.get("result").unwrap_or(&null);

    match channel {
        // A futures trade frame is a list, and its size is signed rather than
        // carrying a side.
        "futures.trades" => Ok(result
            .as_array()
            .map(|trades| {
                trades
                    .iter()
                    .filter_map(|trade| {
                        let (quantity, aggressor) = futures_signed_size(trade, "size")?;
                        Some(Event::Trade(TradePrint {
                            symbol: resolve(trade.get("contract")?.as_str()?),
                            price: parse_decimal(trade.get("price")?.as_str()?).ok()?,
                            quantity,
                            aggressor,
                            timestamp: trade
                                .get("create_time_ms")
                                .and_then(serde_json::Value::as_i64)
                                .unwrap_or(0),
                        }))
                    })
                    .collect()
            })
            .unwrap_or_default()),
        "futures.order_book_update" => {
            let Some(contract) = result.get("s").and_then(serde_json::Value::as_str) else {
                return Ok(Vec::new());
            };
            Ok(vec![Event::BookDelta(BookDelta {
                symbol: resolve(contract),
                first_update_id: result
                    .get("U")
                    .and_then(serde_json::Value::as_u64)
                    .unwrap_or(0),
                final_update_id: result
                    .get("u")
                    .and_then(serde_json::Value::as_u64)
                    .unwrap_or(0),
                bids: futures_levels(result.get("b")),
                asks: futures_levels(result.get("a")),
                timestamp: result
                    .get("t")
                    .and_then(serde_json::Value::as_i64)
                    .unwrap_or(0),
            })])
        }
        // One frame, up to three answers: the futures ticker carries the
        // funding rate, the mark price and the index beside the quote, all read
        // at one moment. Only what was subscribed to is emitted.
        "futures.tickers" => {
            let empty = Vec::new();
            let mut out = Vec::new();
            for ticker in result.as_array().unwrap_or(&empty) {
                let Some(wire) = ticker.get("contract").and_then(serde_json::Value::as_str) else {
                    continue;
                };
                let symbol = resolve(wire);
                let timestamp = ticker
                    .get("t")
                    .and_then(serde_json::Value::as_i64)
                    .unwrap_or(0);
                let field = |key: &str| {
                    ticker
                        .get(key)
                        .and_then(serde_json::Value::as_str)
                        .and_then(|v| parse_decimal(v).ok())
                };
                if let Some(last) = field("last") {
                    out.push(Event::Ticker(Ticker {
                        symbol: symbol.clone(),
                        last,
                        // The futures ticker publishes no top of book; the book
                        // channel is where those live, and inventing them from
                        // the last price would be a fabrication.
                        bid: Decimal::ZERO,
                        ask: Decimal::ZERO,
                        volume: field("volume_24h_base").unwrap_or_default(),
                        timestamp,
                    }));
                }
                let mark = field("mark_price");
                if subscribed(wire, DerivativesChannel::Funding) {
                    if let (Some(rate), Some(mark_price)) = (field("funding_rate"), mark) {
                        out.push(Event::Derivatives(DerivativesFeed::Funding(FundingRate {
                            symbol: symbol.clone(),
                            rate,
                            mark_price,
                            timestamp,
                        })));
                    }
                }
                if subscribed(wire, DerivativesChannel::MarkIndex) {
                    if let (Some(mark_price), Some(index_price)) = (mark, field("index_price")) {
                        out.push(Event::Derivatives(DerivativesFeed::MarkIndex(MarkIndex {
                            symbol,
                            mark_price,
                            index_price,
                            timestamp,
                        })));
                    }
                }
            }
            Ok(out)
        }
        "spot.trades" => Ok(vec![Event::Trade(TradePrint {
            symbol: resolve(field_str(result, "currency_pair")?),
            price: parse_decimal(field_str(result, "price")?)?,
            quantity: parse_decimal(field_str(result, "amount")?)?,
            aggressor: parse_side(field_str(result, "side")?)?,
            timestamp: opt_i64(result, "create_time_ms"),
        })]),
        "spot.tickers" => Ok(vec![Event::Ticker(Ticker {
            symbol: resolve(field_str(result, "currency_pair")?),
            last: parse_decimal(field_str(result, "last")?)?,
            bid: dec_or_zero(opt_str(result, "highest_bid")),
            ask: dec_or_zero(opt_str(result, "lowest_ask")),
            volume: dec_or_zero(opt_str(result, "base_volume")),
            timestamp: 0,
        })]),
        "spot.order_book_update" => {
            let update_id = opt_u64(result, "u");
            Ok(vec![Event::BookDelta(BookDelta {
                symbol: resolve(opt_str(result, "s")),
                first_update_id: update_id,
                final_update_id: update_id,
                bids: parse_ws_levels(result.get("b"))?,
                asks: parse_ws_levels(result.get("a"))?,
                timestamp: opt_u64(result, "t").try_into().unwrap_or(0),
            })])
        }
        // Private order channel: `result` is an array of order objects, each
        // carrying its own `currency_pair`.
        "spot.orders" => result
            .as_array()
            .ok_or_else(|| Error::Deserialization("spot.orders result not an array".to_string()))?
            .iter()
            .map(|order| {
                // The private stream carries no public subscription, so the wire
                // `currency_pair` is split directly.
                let symbol = symbol_from_wire(field_str(order, "currency_pair")?);
                let raw: RawOrder = serde_json::from_value(order.clone())
                    .map_err(|e| Error::Deserialization(e.to_string()))?;
                Ok(Event::OrderUpdate(order_from_raw(symbol, &raw)?))
            })
            .collect(),
        // The futures private order channel. It says everything the spot one
        // says, and says all of it differently: the contract instead of the
        // pair, a *signed* size instead of a side, and a two-part outcome --
        // `status` only reaches `finished`, and `finish_as` says whether that
        // was a fill or a cancel. Reading `status` alone reports every
        // cancelled order as filled.
        "futures.orders" => result
            .as_array()
            .ok_or_else(|| {
                Error::Deserialization("futures.orders result not an array".to_string())
            })?
            .iter()
            .map(|order| Ok(Event::OrderUpdate(futures_order_from_frame(order)?)))
            .collect(),
        // The futures balance channel reports one account currency, and reports
        // it as a running total rather than as free/locked -- margin in use is
        // not broken out here, so `locked` is left at zero rather than guessed.
        "futures.balances" => {
            let balances = result
                .as_array()
                .ok_or_else(|| {
                    Error::Deserialization("futures.balances result not an array".to_string())
                })?
                .iter()
                .map(|entry| {
                    Ok(Balance {
                        asset: field_str(entry, "currency")?.to_string(),
                        free: number_or_string(entry, "balance"),
                        locked: Decimal::ZERO,
                    })
                })
                .collect::<Result<Vec<_>>>()?;
            Ok(vec![Event::BalanceUpdate(balances)])
        }
        // Private balance channel: `result` is an array of per-currency balances,
        // emitted together as one balance-update snapshot.
        "spot.balances" => {
            let balances = result
                .as_array()
                .ok_or_else(|| {
                    Error::Deserialization("spot.balances result not an array".to_string())
                })?
                .iter()
                .map(|entry| {
                    let total = dec_or_zero(opt_str(entry, "total"));
                    let available = dec_or_zero(opt_str(entry, "available"));
                    Ok(Balance {
                        asset: field_str(entry, "currency")?.to_string(),
                        free: available,
                        locked: (total - available).max(Decimal::ZERO),
                    })
                })
                .collect::<Result<Vec<_>>>()?;
            Ok(vec![Event::BalanceUpdate(balances)])
        }
        _ => Ok(Vec::new()),
    }
}

#[derive(Deserialize)]
struct GateError {
    #[serde(default)]
    label: String,
    #[serde(default)]
    message: String,
}

#[derive(Deserialize)]
struct RawTicker {
    last: String,
    highest_bid: String,
    lowest_ask: String,
    base_volume: String,
}

#[derive(Deserialize)]
struct RawDepth {
    #[serde(default)]
    update: u64,
    bids: Vec<[String; 2]>,
    asks: Vec<[String; 2]>,
}

/// Build an [`Order`] from a `futures.orders` frame.
///
/// Gate's futures order carries a **signed** size rather than a side -- negative
/// is a sell -- and reports what is left rather than what filled. The id is a
/// number here where the spot channel sends a string, and the client's own id
/// rides in `text`.
fn futures_order_from_frame(order: &serde_json::Value) -> Result<Order> {
    let size = order
        .get("size")
        .and_then(serde_json::Value::as_i64)
        .ok_or_else(|| Error::Deserialization("futures order has no size".to_string()))?;
    let side = if size < 0 {
        OrderSide::Sell
    } else {
        OrderSide::Buy
    };
    let quantity = Decimal::from(size.abs());
    let left = number_or_string(order, "left").abs();
    let price = nonzero_decimal(opt_str(order, "price"));
    let text = opt_str(order, "text");
    Ok(Order {
        id: order
            .get("id")
            .map(|id| id.as_str().map_or_else(|| id.to_string(), str::to_string))
            .ok_or_else(|| Error::Deserialization("futures order has no id".to_string()))?,
        // Gate prefixes a caller's own id with `t-`; an order the caller did not
        // name carries an id Gate made up, which is not the caller's to match on.
        client_order_id: text.starts_with("t-").then(|| text.to_string()),
        symbol: symbol_from_wire(field_str(order, "contract")?),
        side,
        // A futures order with no price is a market order; `price` is "0" there.
        order_type: if price.is_some() {
            OrderType::Limit
        } else {
            OrderType::Market
        },
        status: futures_order_status(
            opt_str(order, "status"),
            opt_str(order, "finish_as"),
            (quantity - left).max(Decimal::ZERO),
        ),
        quantity,
        filled_quantity: (quantity - left).max(Decimal::ZERO),
        price,
        average_price: nonzero_decimal(opt_str(order, "fill_price")),
    })
}

/// Map a `futures.orders` outcome to an [`OrderStatus`].
///
/// `status` is only ever `open` or `finished`, and `finish_as` says which kind
/// of finished -- `filled`, or one of several ways of ending early, all of
/// which leave the order not filled. A **partial** fill is neither: it is an
/// order still open that has filled some, which only the amount already filled
/// can say.
fn futures_order_status(status: &str, finish_as: &str, filled: Decimal) -> OrderStatus {
    match status {
        "finished" if finish_as == "filled" => OrderStatus::Filled,
        "finished" => OrderStatus::Canceled,
        _ if filled > Decimal::ZERO => OrderStatus::PartiallyFilled,
        _ => OrderStatus::New,
    }
}

/// Read a field Gate's futures channels may send as a number or as a string.
fn number_or_string(value: &serde_json::Value, key: &str) -> Decimal {
    value.get(key).map_or(Decimal::ZERO, |field| {
        field.as_str().map_or_else(
            || {
                field
                    .as_f64()
                    .and_then(|n| parse_decimal(&n.to_string()).ok())
                    .unwrap_or(Decimal::ZERO)
            },
            |text| parse_decimal(text).unwrap_or(Decimal::ZERO),
        )
    })
}

#[derive(Deserialize)]
struct RawOrder {
    id: String,
    #[serde(default)]
    text: String,
    side: String,
    #[serde(rename = "type")]
    order_type: String,
    status: String,
    amount: String,
    #[serde(rename = "filled_amount", default)]
    filled_amount: String,
    // The private `spot.orders` stream reports the remaining size as `left`
    // rather than the filled amount; the filled quantity is derived from it.
    #[serde(default)]
    left: String,
    #[serde(default)]
    price: String,
    #[serde(rename = "avg_deal_price", default)]
    avg_deal_price: String,
}

#[derive(Deserialize)]
struct RawAccount {
    currency: String,
    #[serde(default)]
    available: String,
    #[serde(default)]
    locked: String,
}

#[derive(Deserialize)]
struct RawFuturesTicker {
    last: String,
    #[serde(rename = "volume_24h_base", default)]
    volume_24h_base: String,
}

#[derive(Deserialize)]
struct RawFuturesCandle {
    t: i64,
    o: String,
    h: String,
    l: String,
    c: String,
    #[serde(default)]
    v: f64,
}

#[derive(Deserialize)]
struct RawFuturesLevel {
    p: String,
    s: i64,
}

#[derive(Deserialize)]
struct RawFuturesDepth {
    #[serde(default)]
    id: u64,
    bids: Vec<RawFuturesLevel>,
    asks: Vec<RawFuturesLevel>,
}

#[derive(Deserialize)]
struct RawFuturesOrder {
    id: i64,
    size: i64,
    #[serde(default)]
    left: i64,
    #[serde(default)]
    price: String,
    #[serde(rename = "fill_price", default)]
    fill_price: String,
    status: String,
    #[serde(rename = "finish_as", default)]
    finish_as: String,
    #[serde(default)]
    text: String,
}

#[derive(Deserialize)]
struct RawFuturesAccount {
    #[serde(default = "usdt_currency")]
    currency: String,
    #[serde(default)]
    total: String,
    #[serde(default)]
    available: String,
}

fn usdt_currency() -> String {
    "USDT".to_string()
}

#[derive(Deserialize)]
struct RawFuturesPosition {
    contract: String,
    size: i64,
    #[serde(default)]
    leverage: String,
    #[serde(rename = "cross_leverage_limit", default)]
    cross_leverage_limit: String,
    #[serde(rename = "entry_price", default)]
    entry_price: String,
    #[serde(rename = "mark_price", default)]
    mark_price: String,
    #[serde(rename = "unrealised_pnl", default)]
    unrealised_pnl: String,
}

/// Round a base quantity to a whole number of Gate futures contracts.
fn decimal_to_contracts(quantity: Decimal) -> Result<i64> {
    let contracts = quantity
        .round()
        .to_i64()
        .filter(|c| *c != 0)
        .ok_or(Error::InvalidOrder("futures size rounds to zero contracts"))?;
    Ok(contracts.abs())
}

fn parse_futures_candle(row: &RawFuturesCandle) -> Result<Candle> {
    let f = |s: &str| -> Result<f64> {
        s.parse::<f64>()
            .map_err(|e| Error::Deserialization(format!("candle field not a number: {e}")))
    };
    Candle::new(f(&row.o)?, f(&row.h)?, f(&row.l)?, f(&row.c)?, row.v, row.t)
        .map_err(|e| Error::Deserialization(e.to_string()))
}

fn parse_futures_levels(levels: &[RawFuturesLevel]) -> Result<Vec<BookLevel>> {
    levels
        .iter()
        .map(|level| {
            Ok(BookLevel {
                price: parse_decimal(&level.p)?,
                quantity: Decimal::from(level.s.abs()),
            })
        })
        .collect()
}

fn futures_order_from_raw(symbol: Symbol, raw: &RawFuturesOrder) -> Result<Order> {
    let side = if raw.size >= 0 {
        OrderSide::Buy
    } else {
        OrderSide::Sell
    };
    let quantity = Decimal::from(raw.size.abs());
    let filled = Decimal::from(raw.size.abs() - raw.left.abs());
    let order_type = if raw.price == "0" || raw.price.is_empty() {
        OrderType::Market
    } else {
        OrderType::Limit
    };
    let status = match raw.status.as_str() {
        "open" => {
            if filled > Decimal::ZERO {
                OrderStatus::PartiallyFilled
            } else {
                OrderStatus::New
            }
        }
        "finished" => {
            if raw.finish_as == "filled" {
                OrderStatus::Filled
            } else {
                OrderStatus::Canceled
            }
        }
        other => return Err(Error::Deserialization(format!("unknown status {other:?}"))),
    };
    Ok(Order {
        id: raw.id.to_string(),
        client_order_id: (!raw.text.is_empty()).then(|| raw.text.clone()),
        symbol,
        side,
        order_type,
        status,
        quantity,
        filled_quantity: filled,
        price: nonzero_decimal(&raw.price),
        average_price: nonzero_decimal(&raw.fill_price),
    })
}

fn parse_futures_position(raw: &RawFuturesPosition) -> Position {
    let side = if raw.size > 0 {
        PositionSide::Long
    } else {
        PositionSide::Short
    };
    // Gate reports `leverage == "0"` for cross positions and carries the effective
    // cap in `cross_leverage_limit`.
    let is_cross = raw.leverage.is_empty() || raw.leverage == "0";
    let leverage = if is_cross {
        dec_or_zero(&raw.cross_leverage_limit)
    } else {
        dec_or_zero(&raw.leverage)
    };
    Position {
        symbol: symbol_from_contract(&raw.contract),
        side,
        quantity: Decimal::from(raw.size.abs()),
        entry_price: dec_or_zero(&raw.entry_price),
        mark_price: dec_or_zero(&raw.mark_price),
        leverage,
        unrealized_pnl: dec_or_zero(&raw.unrealised_pnl),
        margin_mode: if is_cross {
            MarginMode::Cross
        } else {
            MarginMode::Isolated
        },
    }
}

/// Reconstruct a canonical [`Symbol`] from a Gate contract (`BTC_USDT`).
fn symbol_from_contract(contract: &str) -> Symbol {
    match contract.split_once('_') {
        Some((base, quote)) => Symbol::new(base, quote),
        None => Symbol::new(contract, ""),
    }
}

impl MarketData for Gate {
    fn ticker(&mut self, symbol: &Symbol) -> Result<Ticker> {
        Gate::ticker(self, symbol)
    }
    fn klines(&mut self, symbol: &Symbol, interval: &str, limit: u32) -> Result<Vec<Candle>> {
        Gate::klines(self, symbol, interval, limit)
    }
    fn order_book(&mut self, symbol: &Symbol, depth: u32) -> Result<OrderBookSnapshot> {
        Gate::order_book(self, symbol, depth)
    }
    fn subscribe_trades(&mut self, symbol: &Symbol) -> Result<()> {
        Gate::subscribe_trades(self, symbol)
    }
    fn subscribe_book(&mut self, symbol: &Symbol) -> Result<()> {
        Gate::subscribe_book(self, symbol)
    }
    fn subscribe_ticker(&mut self, symbol: &Symbol) -> Result<()> {
        Gate::subscribe_ticker(self, symbol)
    }
    fn poll_events(&mut self) -> Vec<Event> {
        Gate::poll_events(self)
    }
}

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

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

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

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

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

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

impl Gate {
    /// Amend a resting spot order's price and/or amount in place
    /// (`PATCH /api/v4/spot/orders/{id}`).
    ///
    /// # 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 mut body = serde_json::json!({});
        if let Some(q) = new_quantity {
            body["amount"] = serde_json::json!(format_decimal(q));
        }
        if let Some(p) = new_price {
            body["price"] = serde_json::json!(format_decimal(p));
        }
        let path = format!("/api/v4/spot/orders/{order_id}");
        let query = format!("currency_pair={}", Self::wire_symbol(symbol));
        let value = self.signed_request(HttpMethod::Patch, &path, &query, &body.to_string())?;
        let raw: RawOrder = parse_json(value)?;
        order_from_raw(symbol.clone(), &raw)
    }

    /// Place several spot orders in one request (`/api/v4/spot/batch_orders`).
    /// Each element carries a `succeeded` flag, so each request's own [`Result`]
    /// is preserved.
    ///
    /// # Errors
    /// Returns an [`Error`] if the batch request itself fails.
    pub fn place_batch(&self, requests: &[OrderRequest]) -> Result<Vec<Result<Order>>> {
        if requests.iter().any(|r| r.order_type.is_trigger()) {
            return Err(Error::unsupported_trigger("Gate.io"));
        }
        for request in requests {
            self.ensure_reduce_only_is_reducible(request)?;
        }
        // Resolved before the batch is built, so a request the venue cannot
        // express refuses the whole call rather than being sent weakened.
        let tifs = requests.iter().map(tif_str).collect::<Result<Vec<_>>>()?;
        let items: Vec<serde_json::Value> = requests
            .iter()
            .zip(&tifs)
            .map(|(r, tif)| {
                let mut o = serde_json::json!({
                    "currency_pair": Self::wire_symbol(&r.symbol),
                    "side": side_str(r.side),
                    "type": order_type_str(r.order_type),
                    "amount": format_decimal(r.quantity),
                });
                if let Some(price) = r.price {
                    o["price"] = serde_json::json!(format_decimal(price));
                }
                if let Some(tif) = tif {
                    o["time_in_force"] = serde_json::json!(*tif);
                }
                if let Some(id) = &r.client_order_id {
                    let text = if id.starts_with("t-") {
                        id.clone()
                    } else {
                        format!("t-{id}")
                    };
                    o["text"] = serde_json::json!(text);
                }
                if let Some(act) = stp_act_str(r.stp) {
                    o["stp_act"] = serde_json::json!(act);
                }
                o
            })
            .collect();
        let body = serde_json::Value::Array(items).to_string();
        let value =
            self.signed_request(HttpMethod::Post, "/api/v4/spot/batch_orders", "", &body)?;
        let elements: Vec<serde_json::Value> = parse_json(value)?;
        Ok(requests
            .iter()
            .zip(elements)
            .map(|(req, elem)| {
                let succeeded = elem
                    .get("succeeded")
                    .and_then(serde_json::Value::as_bool)
                    .unwrap_or(true);
                if !succeeded {
                    let message = elem
                        .get("message")
                        .or_else(|| elem.get("label"))
                        .and_then(serde_json::Value::as_str)
                        .unwrap_or("order rejected in batch")
                        .to_string();
                    return Err(Error::OrderRejected {
                        code: "batch".to_string(),
                        message,
                    });
                }
                let raw: RawOrder = serde_json::from_value(elem)
                    .map_err(|e| Error::Deserialization(e.to_string()))?;
                order_from_raw(req.symbol.clone(), &raw)
            })
            .collect())
    }

    /// Cancel several orders on one `symbol` in one request
    /// (`/api/v4/spot/cancel_batch_orders`).
    ///
    /// # Errors
    /// Returns an [`Error`] if the request fails.
    pub fn cancel_batch(&self, symbol: &Symbol, order_ids: &[String]) -> Result<()> {
        let pair = Self::wire_symbol(symbol);
        let items: Vec<serde_json::Value> = order_ids
            .iter()
            .map(|id| serde_json::json!({ "currency_pair": pair, "id": id }))
            .collect();
        let body = serde_json::Value::Array(items).to_string();
        self.signed_request(
            HttpMethod::Post,
            "/api/v4/spot/cancel_batch_orders",
            "",
            &body,
        )?;
        Ok(())
    }
}

impl AdvancedOrders for Gate {
    fn amend_order(
        &mut self,
        symbol: &Symbol,
        order_id: &str,
        new_price: Option<Decimal>,
        new_quantity: Option<Decimal>,
    ) -> Result<Order> {
        Gate::amend_order(self, symbol, order_id, new_price, new_quantity)
    }
    fn place_batch(&mut self, requests: &[OrderRequest]) -> Result<Vec<Result<Order>>> {
        Gate::place_batch(self, requests)
    }
    fn cancel_batch(&mut self, symbol: &Symbol, order_ids: &[String]) -> Result<()> {
        Gate::cancel_batch(self, symbol, order_ids)
    }
    /// Gate has no OCO order-list (it uses standalone price-triggered orders), so
    /// this returns an [`Error::Exchange`].
    fn place_oco(&mut self, _request: &OcoRequest) -> Result<Vec<Order>> {
        Err(Error::Exchange {
            code: "unsupported".to_string(),
            message: "Gate has no OCO order-list; use price-triggered orders".to_string(),
        })
    }
}

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

    struct ArcTransport(Arc<MockHttpTransport>);
    impl HttpTransport for ArcTransport {
        fn execute(&self, request: &HttpRequest) -> Result<HttpResponse> {
            self.0.execute(request)
        }
    }
    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")
    }

    fn client() -> (Gate, Arc<MockHttpTransport>) {
        let mock = Arc::new(MockHttpTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::Spot);
        (
            Gate::with_http(Box::new(ArcTransport(Arc::clone(&mock))), &opts),
            mock,
        )
    }

    fn futures_ws_client() -> (Gate, Arc<MockWsTransport>) {
        let http = Arc::new(MockHttpTransport::new());
        let ws = Arc::new(MockWsTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::UsdMFutures);
        let gate = Gate::with_http(Box::new(ArcTransport(http)), &opts)
            .with_ws(Box::new(ArcWs(Arc::clone(&ws))));
        (gate, ws)
    }

    /// The answers Gate gives on a bad day.
    #[test]
    fn gate_polled_reads_report_what_went_wrong() {
        let http = Arc::new(MockHttpTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::UsdMFutures);
        let gate = Gate::with_http(Box::new(ArcTransport(Arc::clone(&http))), &opts);

        http.push_json(200, "[]");
        assert!(matches!(
            Gate::open_interest(&gate, &symbol()),
            Err(Error::NotFound(_))
        ));

        http.push_json(200, r#"[{"time":1788464400}]"#);
        assert!(matches!(
            Gate::open_interest(&gate, &symbol()),
            Err(Error::Deserialization(_))
        ));

        http.push_json(200, r#"[{"time":1788464400,"open_interest":1}]"#);
        assert!(matches!(
            Gate::long_short_ratio(&gate, &symbol()),
            Err(Error::Deserialization(_))
        ));

        // A ratio of -1 has no proportions: 1 + r is zero, and the division
        // that follows would be by zero.
        http.push_json(200, r#"[{"time":1788464400,"lsr_account":-1.0}]"#);
        assert!(matches!(
            Gate::long_short_ratio(&gate, &symbol()),
            Err(Error::Deserialization(_))
        ));
    }

    /// Frames the futures parser cannot use are dropped.
    #[test]
    fn gate_drops_futures_frames_it_cannot_read() {
        let (mut gate, ws) = futures_ws_client();
        ws.push_connection(vec![
            // A book update with no contract.
            Ok(Some(
                r#"{"time":1,"channel":"futures.order_book_update","event":"update",
                "result":{"t":1,"U":1,"u":2,"a":[],"b":[]}}"#
                    .to_string(),
            )),
            // A trade with no price.
            Ok(Some(
                r#"{"time":1,"channel":"futures.trades","event":"update",
                "result":[{"size":1,"contract":"BTC_USDT"}]}"#
                    .to_string(),
            )),
            // A ticker with no last price.
            Ok(Some(
                r#"{"time":1,"channel":"futures.tickers","event":"update",
                "result":[{"contract":"BTC_USDT"}]}"#
                    .to_string(),
            )),
            // A level whose size is missing.
            Ok(Some(
                r#"{"time":1,"channel":"futures.order_book_update","event":"update",
                "result":{"t":1,"U":1,"u":2,"s":"BTC_USDT","a":[{"p":"1.0"}],"b":[]}}"#
                    .to_string(),
            )),
        ]);
        Gate::subscribe_book(&mut gate, &symbol()).unwrap();

        let events = Gate::poll_events(&mut gate);
        // Only the last frame produces anything, and its one unreadable level
        // is dropped rather than defaulted.
        assert_eq!(events.len(), 1, "{events:?}");
        let Event::BookDelta(delta) = &events[0] else {
            panic!("expected a delta");
        };
        assert!(delta.asks.is_empty() && delta.bids.is_empty());
    }

    /// One ticker frame answers both subscriptions.
    #[test]
    fn the_futures_ticker_answers_funding_and_mark_index_on_gate() {
        let (mut gate, ws) = futures_ws_client();
        ws.push_connection(vec![Ok(Some(
            r#"{"time":1788462378,"channel":"futures.tickers","event":"update",
            "result":[{"contract":"BTC_USDT","last":"81231.4","mark_price":"81238.4",
            "index_price":"81271.1","funding_rate":"0.000073",
            "volume_24h_base":"81628.265","t":1788462378855}]}"#
                .to_string(),
        ))]);
        Gate::subscribe_derivatives(&mut gate, &symbol(), DerivativesChannel::Funding).unwrap();
        Gate::subscribe_derivatives(&mut gate, &symbol(), DerivativesChannel::MarkIndex).unwrap();

        let events = Gate::poll_events(&mut gate);
        assert_eq!(events.len(), 3, "ticker, funding, mark/index: {events:?}");

        let Event::Derivatives(DerivativesFeed::Funding(funding)) = &events[1] else {
            panic!("expected funding, got {:?}", events[1]);
        };
        assert_eq!(funding.rate, dec!(0.000073));
        assert_eq!(funding.mark_price, dec!(81238.4));

        let Event::Derivatives(DerivativesFeed::MarkIndex(mark)) = &events[2] else {
            panic!("expected mark/index, got {:?}", events[2]);
        };
        assert_eq!(mark.index_price, dec!(81271.1));
    }

    /// Gate's `futures.liquidates` needs authentication and reports the
    /// caller's own liquidations, not the venue's forced flow, so it is not the
    /// public feed this channel means.
    #[test]
    fn gate_refuses_liquidations() {
        let (mut gate, ws) = futures_ws_client();
        let err =
            Gate::subscribe_derivatives(&mut gate, &symbol(), DerivativesChannel::Liquidations)
                .expect_err("Gate publishes no public forced-order feed");
        assert!(matches!(err, Error::Exchange { ref code, .. } if code == "unsupported"));
        assert_eq!(ws.sent(), Vec::<String>::new());
    }

    /// `contract_stats` carries both polled figures, and stamps in **seconds**.
    #[test]
    fn the_polled_figures_come_from_one_row_stamped_in_seconds() {
        let http = Arc::new(MockHttpTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::UsdMFutures);
        let gate = Gate::with_http(Box::new(ArcTransport(Arc::clone(&http))), &opts);
        http.push_json(
            200,
            r#"[{"time":1788464400,"lsr_taker":1.6098,"lsr_account":3.0,
            "open_interest":626095712,"mark_price":81477,
            "open_interest_usd":5101240032.6624}]"#,
        );
        let open_interest = Gate::open_interest(&gate, &symbol()).unwrap();
        assert_eq!(open_interest.open_interest, dec!(626095712));
        // Seconds on the wire, milliseconds in the type.
        assert_eq!(open_interest.timestamp, 1_788_464_400_000);

        http.push_json(
            200,
            r#"[{"time":1788464400,"lsr_account":3.0,"open_interest":626095712}]"#,
        );
        let ratio = Gate::long_short_ratio(&gate, &symbol()).unwrap();
        // A ratio of 3 is 0.75 long and 0.25 short, and the two sum to one.
        assert_eq!(ratio.long_size, dec!(0.75));
        assert_eq!(ratio.short_size, dec!(0.25));
        assert_eq!(ratio.long_size + ratio.short_size, Decimal::ONE);
    }

    #[test]
    fn a_spot_client_refuses_the_gate_derivatives_surface() {
        let ws = Arc::new(MockWsTransport::new());
        let http = Arc::new(MockHttpTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::Spot);
        let mut gate = Gate::with_http(Box::new(ArcTransport(Arc::clone(&http))), &opts)
            .with_ws(Box::new(ArcWs(Arc::clone(&ws))));
        for channel in [
            DerivativesChannel::Funding,
            DerivativesChannel::MarkIndex,
            DerivativesChannel::Liquidations,
        ] {
            assert!(Gate::subscribe_derivatives(&mut gate, &symbol(), channel).is_err());
        }
        assert!(Gate::open_interest(&gate, &symbol()).is_err());
        assert!(Gate::long_short_ratio(&gate, &symbol()).is_err());
    }

    /// Both the host and the channel prefix follow the market.
    #[test]
    fn a_futures_client_subscribes_on_the_futures_host() {
        let (mut gate, ws) = futures_ws_client();
        Gate::subscribe_trades(&mut gate, &symbol()).unwrap();
        Gate::subscribe_book(&mut gate, &symbol()).unwrap();

        assert_eq!(ws.connected_urls()[0], "wss://fx-ws.gateio.ws/v4/ws/usdt");
        assert!(ws.sent()[0].contains(r#""channel":"futures.trades""#));
        assert!(!ws.sent()[0].contains("spot."));
        // The book channel needs an interval and a depth beside the contract.
        assert!(ws.sent()[1].contains(r#""channel":"futures.order_book_update""#));
        assert!(ws.sent()[1].contains(r#""payload":["BTC_USDT","100ms","20"]"#));
    }

    /// A futures trade carries no side: the size is signed, and negative means
    /// the aggressor sold.
    #[test]
    fn a_futures_trade_takes_its_side_from_the_sign_of_the_size() {
        let (mut gate, ws) = futures_ws_client();
        ws.push_connection(vec![
            Ok(Some(
                r#"{"time":1788462378,"time_ms":1788462378855,"channel":"futures.trades",
                "event":"update","result":[{"id":826990332,"size":14372,
                "create_time":1788462378,"create_time_ms":1788462378855,
                "price":"81231.4","contract":"BTC_USDT"}]}"#
                    .to_string(),
            )),
            Ok(Some(
                r#"{"time":1788462379,"channel":"futures.trades","event":"update",
                "result":[{"id":826990333,"size":-25,"create_time_ms":1788462379000,
                "price":"81230.0","contract":"BTC_USDT"}]}"#
                    .to_string(),
            )),
        ]);
        Gate::subscribe_trades(&mut gate, &symbol()).unwrap();

        let events = Gate::poll_events(&mut gate);
        let Event::Trade(bought) = &events[0] else {
            panic!("expected a trade, got {:?}", events[0]);
        };
        assert_eq!(bought.aggressor, OrderSide::Buy);
        assert_eq!(bought.quantity, dec!(14372));
        assert_eq!(bought.price, dec!(81231.4));
        assert_eq!(bought.timestamp, 1_788_462_378_855);

        let Event::Trade(sold) = &events[1] else {
            panic!("expected a trade, got {:?}", events[1]);
        };
        assert_eq!(sold.aggressor, OrderSide::Sell);
        // The magnitude, not the signed figure: a quantity is not negative.
        assert_eq!(sold.quantity, dec!(25));
    }

    #[test]
    fn a_futures_book_update_parses_both_sides() {
        let (mut gate, ws) = futures_ws_client();
        ws.push_connection(vec![Ok(Some(
            r#"{"time":1788462378,"channel":"futures.order_book_update","event":"update",
            "result":{"t":1788462378780,"U":124074489866,"u":124074489905,"s":"BTC_USDT",
            "a":[{"p":"81231.4","s":4572},{"p":"81239.3","s":0}],
            "b":[{"p":"81230.0","s":12}],"l":"20"}}"#
                .to_string(),
        ))]);
        Gate::subscribe_book(&mut gate, &symbol()).unwrap();

        let events = Gate::poll_events(&mut gate);
        let Event::BookDelta(delta) = &events[0] else {
            panic!("expected a delta, got {:?}", events[0]);
        };
        assert_eq!(delta.asks.len(), 2);
        assert_eq!(delta.asks[0].price, dec!(81231.4));
        // A size of zero removes the level, which the delta type already means.
        assert_eq!(delta.asks[1].quantity, Decimal::ZERO);
        assert_eq!(delta.bids.len(), 1);
        assert_eq!(delta.first_update_id, 124_074_489_866);
        assert_eq!(delta.final_update_id, 124_074_489_905);
    }

    /// The futures ticker publishes no top of book, so those stay zero rather
    /// than being invented from the last price.
    #[test]
    fn a_futures_ticker_reports_no_top_of_book() {
        let (mut gate, ws) = futures_ws_client();
        ws.push_connection(vec![Ok(Some(
            r#"{"time":1788462378,"channel":"futures.tickers","event":"update",
            "result":[{"contract":"BTC_USDT","last":"81231.4","mark_price":"81238.4",
            "index_price":"81271.1","funding_rate":"0.000073","volume_24h_base":"81628.265",
            "t":1788462378855}]}"#
                .to_string(),
        ))]);
        Gate::subscribe_ticker(&mut gate, &symbol()).unwrap();

        let events = Gate::poll_events(&mut gate);
        let Event::Ticker(ticker) = &events[0] else {
            panic!("expected a ticker, got {:?}", events[0]);
        };
        assert_eq!(ticker.last, dec!(81231.4));
        assert_eq!(ticker.volume, dec!(81628.265));
        assert_eq!(ticker.bid, Decimal::ZERO);
        assert_eq!(ticker.ask, Decimal::ZERO);
        assert_eq!(ticker.timestamp, 1_788_462_378_855);
    }

    /// The spot client keeps its own host and channels.
    #[test]
    fn a_spot_client_still_subscribes_to_spot_channels() {
        let ws = Arc::new(MockWsTransport::new());
        let http = Arc::new(MockHttpTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::Spot);
        let mut gate = Gate::with_http(Box::new(ArcTransport(http)), &opts)
            .with_ws(Box::new(ArcWs(Arc::clone(&ws))));
        Gate::subscribe_trades(&mut gate, &symbol()).unwrap();

        assert_eq!(ws.connected_urls()[0], "wss://api.gateio.ws/ws/v4/");
        assert!(ws.sent()[0].contains(r#""channel":"spot.trades""#));
    }

    fn signed_client(now_ms: i64) -> (Gate, Arc<MockHttpTransport>) {
        let mock = Arc::new(MockHttpTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::Spot);
        let gate = Gate::with_credentials(
            Box::new(ArcTransport(Arc::clone(&mock))),
            &opts,
            Credentials::new("APIKEY", "SECRET"),
        )
        .with_clock(Box::new(move || now_ms));
        (gate, mock)
    }

    fn signed_ws_client(now_ms: i64) -> (Gate, Arc<MockWsTransport>) {
        let http = Arc::new(MockHttpTransport::new());
        let ws = Arc::new(MockWsTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::Spot);
        let gate = Gate::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));
        (gate, ws)
    }

    #[test]
    fn subscribe_user_data_authenticates_and_streams_orders_and_balances() {
        let (mut gate, ws) = signed_ws_client(1_700_000_000_000);
        ws.push_connection(vec![
            Ok(Some(r#"{"channel":"spot.orders","event":"subscribe"}"#.to_string())),
            Ok(Some(r#"{"channel":"spot.balances","event":"subscribe"}"#.to_string())),
            Ok(Some(
                r#"{"time":1,"channel":"spot.orders","event":"update","result":[{"id":"55",
                "text":"my","currency_pair":"BTC_USDT","side":"buy","type":"limit","status":"closed",
                "amount":"1","left":"0","price":"100","avg_deal_price":"100"}]}"#
                    .to_string(),
            )),
            Ok(Some(
                r#"{"time":2,"channel":"spot.balances","event":"update","result":[{"currency":"USDT",
                "available":"900","total":"950"}]}"#
                    .to_string(),
            )),
        ]);
        gate.subscribe_user_data().unwrap();
        assert_eq!(ws.connected_urls()[0], "wss://api.gateio.ws/ws/v4/");
        assert!(ws.sent()[0].contains(r#""channel":"spot.orders""#));
        assert!(ws.sent()[0].contains(r#""KEY":"APIKEY""#));
        assert!(ws.sent()[0].contains(r#""SIGN""#));
        assert!(ws.sent()[1].contains(r#""channel":"spot.balances""#));

        let events = gate.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, "55");
        assert_eq!(order.symbol, symbol());
        assert_eq!(order.side, OrderSide::Buy);
        assert_eq!(order.status, OrderStatus::Filled);
        assert_eq!(order.filled_quantity, dec!(1));
        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(), 1);
        assert_eq!(balances[0].asset, "USDT");
        assert_eq!(balances[0].free, dec!(900));
        assert_eq!(balances[0].locked, dec!(50));
    }

    #[test]
    fn subscribe_user_data_requires_credentials() {
        let http = Arc::new(MockHttpTransport::new());
        let ws = Arc::new(MockWsTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::Spot);
        let mut gate = Gate::with_http(Box::new(ArcTransport(http)), &opts)
            .with_ws(Box::new(ArcWs(Arc::clone(&ws))));
        assert!(matches!(
            gate.subscribe_user_data().unwrap_err(),
            Error::InvalidCredentials(_)
        ));
    }

    #[test]
    fn keepalive_user_data_pings_the_private_stream() {
        let (mut gate, ws) = signed_ws_client(1_700_000_000_000);
        ws.push_connection(vec![]);
        gate.subscribe_user_data().unwrap();
        gate.keepalive_user_data().unwrap();
        assert!(ws.sent().iter().any(|f| f == "ping"));
    }

    #[test]
    fn keepalive_user_data_is_a_noop_before_subscribe() {
        let (mut gate, ws) = signed_ws_client(1_700_000_000_000);
        gate.keepalive_user_data().unwrap();
        assert_eq!(ws.sent(), Vec::<String>::new());
    }

    #[test]
    fn dropped_user_data_stream_reconnects_with_fresh_signed_frames() {
        let (mut gate, ws) = signed_ws_client(1_700_000_000_000);
        // The 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![]);
        gate.subscribe_user_data().unwrap();

        let events = gate.poll_events();
        assert!(events.contains(&Event::Disconnected));
        assert!(events.contains(&Event::Reconnected));
        // Two private connections (initial + reconnect); each re-signs the
        // spot.orders subscribe, so four signed subscribe frames total.
        let signed_subs = ws
            .sent()
            .into_iter()
            .filter(|f| f.contains(r#""SIGN""#))
            .count();
        assert_eq!(signed_subs, 4);
        assert_eq!(ws.connected_urls().len(), 2);
        assert_eq!(ws.connected_urls()[1], "wss://api.gateio.ws/ws/v4/");
    }

    #[test]
    fn the_websocket_frame_carries_the_stp_policy() {
        // `stp_act` is on the REST spot body and was missing from this frame,
        // which otherwise uses the same field names.
        let (mut gate, ws) = signed_ws_client(1_700_000_000_000);
        ws.push_connection(vec![
            Ok(Some(
                r#"{"request_id":"login","header":{"status":"200","channel":"spot.login",
                "event":"api"},"data":{"result":{"api_key":"APIKEY"}}}"#
                    .to_string(),
            )),
            Ok(Some(
                r#"{"request_id":"b","header":{"status":"200","channel":"spot.order_place",
                "event":"api"},"data":{"result":{"id":"55","text":"","currency_pair":"BTC_USDT",
                "side":"buy","type":"limit","status":"open","amount":"1","left":"1","price":"100",
                "avg_deal_price":"0"}}}"#
                    .to_string(),
            )),
        ]);
        gate.place_order_ws(
            &OrderRequest::limit_buy(symbol(), dec!(1), dec!(100))
                .with_stp(SelfTradePrevention::ExpireTaker),
        )
        .unwrap();
        assert!(ws.sent()[1].contains(r#""stp_act":"cn""#));
    }

    #[test]
    fn place_and_cancel_order_over_ws() {
        let (mut gate, ws) = signed_ws_client(1_700_000_000_000);
        ws.push_connection(vec![
            Ok(Some(
                r#"{"request_id":"login","header":{"status":"200","channel":"spot.login",
                "event":"api"},"data":{"result":{"api_key":"APIKEY"}}}"#
                    .to_string(),
            )),
            Ok(Some(
                r#"{"request_id":"o","header":{"status":"200","channel":"spot.order_place",
                "event":"api"},"data":{"result":{"id":"55","text":"t-my","currency_pair":"BTC_USDT",
                "side":"buy","type":"limit","status":"closed","amount":"1","left":"0","price":"100",
                "avg_deal_price":"100"}}}"#
                    .to_string(),
            )),
            Ok(Some(
                r#"{"request_id":"c","header":{"status":"200","channel":"spot.order_cancel",
                "event":"api"},"data":{"result":{"id":"55"}}}"#
                    .to_string(),
            )),
        ]);
        let order = gate
            .place_order_ws(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)))
            .unwrap();
        assert_eq!(order.id, "55");
        assert_eq!(order.symbol, symbol());
        assert_eq!(order.status, OrderStatus::Filled);
        assert_eq!(order.filled_quantity, dec!(1));
        assert_eq!(ws.connected_urls()[0], "wss://api.gateio.ws/ws/v4/");
        // The login frame is sent first, then the order request.
        assert!(ws.sent()[0].contains(r#""channel":"spot.login""#));
        assert!(ws.sent()[0].contains(r#""signature""#));
        assert!(ws.sent()[1].contains(r#""channel":"spot.order_place""#));
        assert!(ws.sent()[1].contains(r#""currency_pair":"BTC_USDT""#));

        gate.cancel_order_ws(&symbol(), "55").unwrap();
        assert!(ws.sent()[2].contains(r#""channel":"spot.order_cancel""#));
        assert!(ws.sent()[2].contains(r#""order_id":"55""#));
    }

    #[test]
    fn ws_order_surfaces_rejection() {
        let (mut gate, ws) = signed_ws_client(1000);
        ws.push_connection(vec![
            Ok(Some(
                r#"{"header":{"status":"200","channel":"spot.login","event":"api"}}"#.to_string(),
            )),
            Ok(Some(
                r#"{"header":{"status":"400","channel":"spot.order_place","event":"api"},
                "data":{"errs":{"label":"BALANCE_NOT_ENOUGH","message":"not enough balance"}}}"#
                    .to_string(),
            )),
        ]);
        assert!(matches!(
            gate.place_order_ws(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)))
                .unwrap_err(),
            Error::OrderRejected { .. }
        ));
    }

    #[test]
    fn ws_order_requires_credentials() {
        let http = Arc::new(MockHttpTransport::new());
        let ws = Arc::new(MockWsTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::Spot);
        let mut gate = Gate::with_http(Box::new(ArcTransport(http)), &opts)
            .with_ws(Box::new(ArcWs(Arc::clone(&ws))));
        assert!(matches!(
            gate.place_order_ws(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)))
                .unwrap_err(),
            Error::InvalidCredentials(_)
        ));
    }

    fn signed_futures_client(now_ms: i64) -> (Gate, Arc<MockHttpTransport>) {
        let mock = Arc::new(MockHttpTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::UsdMFutures);
        let gate = Gate::with_credentials(
            Box::new(ArcTransport(Arc::clone(&mock))),
            &opts,
            Credentials::new("APIKEY", "SECRET"),
        )
        .with_clock(Box::new(move || now_ms));
        (gate, mock)
    }

    /// A spot trigger goes to the price-order endpoint, whose body nests a
    /// `trigger` (when to act) inside a `put` (what to place).
    ///
    /// `rule` is the comparison and Gate will not infer it: `<=` protects a
    /// long, `>=` covers a short. The wrong one arms the order on the side that
    /// never comes.
    #[test]
    fn a_spot_trigger_goes_to_the_price_order_endpoint_with_its_rule() {
        for (side, rule) in [(OrderSide::Sell, "<="), (OrderSide::Buy, ">=")] {
            let (gate, mock) = signed_client(1_000_000);
            mock.push_json(200, r#"{"id":77}"#);
            let request = OrderRequest {
                order_type: OrderType::StopLimit,
                stop_price: Some(dec!(19000)),
                side,
                ..OrderRequest::limit_sell(symbol(), dec!(1), dec!(18900))
            };
            let order = gate.place_order(&request).unwrap();
            assert_eq!(order.id, "77");

            let sent = &mock.recorded_requests()[0];
            assert!(
                sent.url.contains("/api/v4/spot/price_orders"),
                "{}",
                sent.url
            );
            let body = sent.body.clone().unwrap();
            assert!(body.contains(r#""price":"19000""#), "{body}");
            assert!(
                body.contains(&format!(r#""rule":"{rule}""#)),
                "a {side:?} stop fires the other way: {body}"
            );
            // The limit that gets placed once it fires, not the trigger.
            assert!(body.contains(r#""price":"18900""#), "{body}");
        }
    }

    /// Gate's spot price order can only place a limit.
    ///
    /// A stop-market is refused rather than sent with an invented limit price:
    /// that price is exactly how much slippage the caller's stop is allowed to
    /// take, and it is not this library's to choose.
    #[test]
    fn a_spot_stop_market_is_refused_rather_than_given_an_invented_price() {
        let (gate, mock) = signed_client(1_000_000);
        let request = OrderRequest {
            order_type: OrderType::StopMarket,
            stop_price: Some(dec!(19000)),
            ..OrderRequest::market_sell(symbol(), dec!(1))
        };
        let err = gate.place_order(&request).unwrap_err();
        assert!(matches!(err, Error::Exchange { ref code, .. } if code == "unsupported"));
        assert_eq!(mock.recorded_requests(), Vec::new());
    }

    /// Futures has no such limit: `0` there means "take the market", so a
    /// stop-market is carried rather than refused. Size sits on the initial
    /// order and is signed by side, the way every other Gate futures order is.
    #[test]
    fn a_futures_stop_market_takes_the_market_and_signs_its_size() {
        let (gate, mock) = signed_futures_client(1_000_000);
        mock.push_json(200, r#"{"id":78}"#);
        let request = OrderRequest {
            order_type: OrderType::StopMarket,
            stop_price: Some(dec!(19000)),
            ..OrderRequest::market_sell(symbol(), dec!(1))
        };
        gate.place_order(&request).unwrap();

        let sent = &mock.recorded_requests()[0];
        assert!(
            sent.url.contains("/api/v4/futures/usdt/price_orders"),
            "{}",
            sent.url
        );
        let body = sent.body.clone().unwrap();
        assert!(body.contains(r#""price":"0""#), "{body}");
        assert!(
            body.contains(r#""size":-1"#),
            "a sell is a negative size: {body}"
        );
        assert!(body.contains(r#""rule":2"#), "{body}");
    }

    #[test]
    fn a_gate_trigger_without_a_stop_price_is_refused() {
        let (gate, mock) = signed_futures_client(1_000_000);
        let request = OrderRequest {
            order_type: OrderType::StopMarket,
            stop_price: None,
            ..OrderRequest::market_sell(symbol(), dec!(1))
        };
        assert!(gate.place_order(&request).is_err());
        assert_eq!(mock.recorded_requests(), Vec::new());
    }

    fn signed_futures_ws_client(
        now_ms: i64,
    ) -> (Gate, Arc<MockHttpTransport>, Arc<MockWsTransport>) {
        let http = Arc::new(MockHttpTransport::new());
        let ws = Arc::new(MockWsTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::UsdMFutures);
        let gate = Gate::with_credentials(
            Box::new(ArcTransport(Arc::clone(&http))),
            &opts,
            Credentials::new("APIKEY", "SECRET"),
        )
        .with_ws(Box::new(ArcWs(Arc::clone(&ws))))
        .with_clock(Box::new(move || now_ms));
        (gate, http, ws)
    }

    /// A futures client watches the futures account, on the futures socket.
    ///
    /// The host and the channel name were verified against the live venue:
    /// `fx-ws.gateio.ws/v4/ws/usdt` accepts the socket and answers a
    /// `futures.orders` subscribe with `authentication required` -- an
    /// unrecognised channel answers differently.
    ///
    /// Gate addresses these channels to a **user id**, which the spot channels
    /// do not take. Subscribing without it is a subscription to nobody, so the
    /// id is fetched first.
    #[test]
    fn a_futures_client_subscribes_to_the_futures_channels_for_its_own_user() {
        let (mut gate, http, ws) = signed_futures_ws_client(1_700_000_000_000);
        http.push_json(
            200,
            r#"{"user":4242,"currency":"USDT","total":"1","available":"1"}"#,
        );
        gate.subscribe_user_data().unwrap();

        let looked_up = &http.recorded_requests()[0];
        assert!(
            looked_up.url.contains("/api/v4/futures/usdt/accounts"),
            "{}",
            looked_up.url
        );
        assert_eq!(ws.connected_urls()[0], "wss://fx-ws.gateio.ws/v4/ws/usdt");
        let sent = ws.sent();
        assert!(
            sent[0].contains(r#""channel":"futures.orders""#),
            "{}",
            sent[0]
        );
        assert!(
            sent[0].contains(r#""payload":["4242","!all"]"#),
            "{}",
            sent[0]
        );
        assert!(
            sent[1].contains(r#""channel":"futures.balances""#),
            "{}",
            sent[1]
        );
        assert!(
            !sent.iter().any(|frame| frame.contains("spot.")),
            "a futures client subscribed to a spot channel: {sent:?}"
        );
    }

    /// The user id is fetched once, not per subscribe.
    #[test]
    fn the_futures_user_id_is_looked_up_once() {
        let (mut gate, http, ws) = signed_futures_ws_client(1_700_000_000_000);
        http.push_json(
            200,
            r#"{"user":4242,"currency":"USDT","total":"1","available":"1"}"#,
        );
        gate.subscribe_user_data().unwrap();
        gate.subscribe_user_data().unwrap();
        assert_eq!(http.recorded_requests().len(), 1);
        assert_eq!(ws.sent().len(), 4);
    }

    /// A futures order frame says everything the spot one says, differently:
    /// a signed size instead of a side, what is left instead of what filled,
    /// and a two-part outcome.
    #[test]
    fn a_futures_order_frame_becomes_an_order_update() {
        let (mut gate, http, ws) = signed_futures_ws_client(1_700_000_000_000);
        http.push_json(
            200,
            r#"{"user":1,"currency":"USDT","total":"1","available":"1"}"#,
        );
        ws.push_connection(vec![Ok(Some(
            r#"{"time":1700000000,"channel":"futures.orders","event":"update","result":[
                {"id":88,"contract":"BTC_USDT","size":-4,"left":1,"price":"19000",
                 "status":"open","text":"t-mine","fill_price":"19010"}]}"#
                .to_string(),
        ))]);
        gate.subscribe_user_data().unwrap();

        let events = gate.poll_events();
        let Some(Event::OrderUpdate(order)) = events.first() else {
            panic!("expected an order update, got {events:?}");
        };
        assert_eq!(order.id, "88");
        assert_eq!(order.symbol, Symbol::new("BTC", "USDT"));
        // A negative size is a sell; there is no side field to read.
        assert_eq!(order.side, OrderSide::Sell);
        assert_eq!(order.quantity, dec!(4));
        // Three of four contracts filled -- the frame says only that one is left.
        assert_eq!(order.filled_quantity, dec!(3));
        assert_eq!(order.status, OrderStatus::PartiallyFilled);
        assert_eq!(order.client_order_id.as_deref(), Some("t-mine"));
    }

    /// `status` only ever reaches `finished`; `finish_as` says whether that was
    /// a fill or a cancel. Reading the status alone reports every cancelled
    /// order as filled.
    #[test]
    fn a_finished_futures_order_is_a_fill_or_a_cancel_by_finish_as() {
        assert_eq!(
            futures_order_status("finished", "filled", dec!(4)),
            OrderStatus::Filled
        );
        assert_eq!(
            futures_order_status("finished", "cancelled", dec!(0)),
            OrderStatus::Canceled
        );
        // Ended early for any other reason: not filled either.
        assert_eq!(
            futures_order_status("finished", "reduce_only", dec!(0)),
            OrderStatus::Canceled
        );
        assert_eq!(futures_order_status("open", "", dec!(0)), OrderStatus::New);
    }

    #[test]
    fn a_futures_balance_frame_becomes_a_balance_update() {
        let (mut gate, http, ws) = signed_futures_ws_client(1_700_000_000_000);
        http.push_json(
            200,
            r#"{"user":1,"currency":"USDT","total":"1","available":"1"}"#,
        );
        ws.push_connection(vec![Ok(Some(
            r#"{"time":1700000000,"channel":"futures.balances","event":"update","result":[
                {"balance":9999.5,"change":"-0.5","currency":"USDT","type":"fee"}]}"#
                .to_string(),
        ))]);
        gate.subscribe_user_data().unwrap();

        let events = gate.poll_events();
        let Some(Event::BalanceUpdate(balances)) = events.first() else {
            panic!("expected a balance update, got {events:?}");
        };
        assert_eq!(balances[0].asset, "USDT");
        // The frame carries a number, not a string, and it is the whole balance.
        assert_eq!(balances[0].free, dec!(9999.5));
    }

    const GATE_ORDER: &str = r#"{"id":"1","text":"","side":"buy","type":"limit","status":"open",
        "amount":"1","filled_amount":"0","price":"100","avg_deal_price":"0"}"#;

    #[test]
    fn stp_maps_to_stp_act() {
        let (gate, mock) = signed_client(1_000_000);
        mock.push_json(200, GATE_ORDER);
        gate.place_order(
            &OrderRequest::limit_buy(symbol(), dec!(1), dec!(100))
                .with_stp(SelfTradePrevention::ExpireBoth),
        )
        .unwrap();
        let reqs = mock.recorded_requests();
        assert!(reqs[0].body.as_ref().unwrap().contains(r#""stp_act":"cb""#));
    }

    #[test]
    fn amend_order_patches_in_place() {
        let (gate, mock) = signed_client(1_000_000);
        mock.push_json(
            200,
            r#"{"id":"1","text":"","side":"buy","type":"limit","status":"open",
            "amount":"2","filled_amount":"0","price":"101","avg_deal_price":"0"}"#,
        );
        let order = gate
            .amend_order(&symbol(), "1", Some(dec!(101)), Some(dec!(2)))
            .unwrap();
        assert_eq!(order.quantity, dec!(2));
        assert_eq!(order.price, Some(dec!(101)));
        let reqs = mock.recorded_requests();
        assert_eq!(reqs[0].method, HttpMethod::Patch);
        assert!(reqs[0]
            .url
            .contains("/api/v4/spot/orders/1?currency_pair=BTC_USDT"));
        let body = reqs[0].body.as_ref().unwrap();
        assert!(body.contains(r#""amount":"2""#));
        assert!(body.contains(r#""price":"101""#));
    }

    /// The futures order path spells the time-in-force in `tif`, and a futures
    /// market order is a zero-price IOC with no fill-or-kill spelling at all.
    #[test]
    fn futures_orders_carry_the_time_in_force_or_refuse_it() {
        let (gate, mock) = signed_futures_client(1000);
        mock.push_json(200, "{}");
        let ioc = OrderRequest::limit_buy(symbol(), dec!(1), dec!(100))
            .with_time_in_force(TimeInForce::Ioc);
        let _ = gate.place_order(&ioc);
        let body = mock.recorded_requests()[0].body.clone().unwrap_or_default();
        assert!(body.contains(r#""tif":"ioc""#));

        let (gate, mock) = signed_futures_client(1000);
        mock.push_json(200, "{}");
        let poc = OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)).post_only();
        let _ = gate.place_order(&poc);
        let body = mock.recorded_requests()[0].body.clone().unwrap_or_default();
        assert!(body.contains(r#""tif":"poc""#));

        let (gate, mock) = signed_futures_client(1000);
        let fok = OrderRequest::market_buy(symbol(), dec!(1)).with_time_in_force(TimeInForce::Fok);
        let err = gate.place_order(&fok).unwrap_err();
        assert!(matches!(err, Error::Exchange { ref code, .. } if code == "unsupported"));
        assert_eq!(mock.recorded_requests(), Vec::new());
    }

    #[test]
    fn place_batch_reads_succeeded_flag() {
        let (gate, mock) = signed_client(1_000_000);
        mock.push_json(
            200,
            r#"[{"succeeded":true,"id":"o1","text":"","side":"buy","type":"limit","status":"open",
            "amount":"1","filled_amount":"0","price":"100","avg_deal_price":"0"},
            {"succeeded":false,"label":"BALANCE_NOT_ENOUGH","message":"no funds"}]"#,
        );
        let results = gate
            .place_batch(&[
                OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)),
                OrderRequest::limit_buy(symbol(), dec!(1), dec!(101)),
            ])
            .unwrap();
        assert_eq!(results[0].as_ref().unwrap().id, "o1");
        assert!(matches!(
            results[1].as_ref().unwrap_err(),
            Error::OrderRejected { .. }
        ));
        assert!(mock.recorded_requests()[0]
            .url
            .contains("/api/v4/spot/batch_orders"));
    }

    #[test]
    fn cancel_batch_is_one_call() {
        let (gate, mock) = signed_client(1_000_000);
        mock.push_json(200, "[]");
        gate.cancel_batch(&symbol(), &["1".to_string(), "2".to_string()])
            .unwrap();
        let reqs = mock.recorded_requests();
        assert_eq!(reqs.len(), 1);
        assert!(reqs[0].url.contains("/api/v4/spot/cancel_batch_orders"));
    }

    #[test]
    fn place_oco_is_unsupported() {
        let (mut gate, _mock) = signed_client(1_000_000);
        assert!(matches!(
            AdvancedOrders::place_oco(
                &mut gate,
                &OcoRequest::new(symbol(), OrderSide::Sell, dec!(1), dec!(110), dec!(95))
            )
            .unwrap_err(),
            Error::Exchange { .. }
        ));
    }

    fn futures_client() -> (Gate, Arc<MockHttpTransport>) {
        let mock = Arc::new(MockHttpTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::UsdMFutures);
        (
            Gate::with_http(Box::new(ArcTransport(Arc::clone(&mock))), &opts),
            mock,
        )
    }

    #[test]
    fn futures_ticker_takes_bid_ask_from_the_book() {
        let (gate, mock) = futures_client();
        mock.push_json(
            200,
            r#"[{"contract":"BTC_USDT","last":"20000","volume_24h_base":"1234"}]"#,
        );
        mock.push_json(
            200,
            r#"{"id":66,"bids":[{"p":"19999","s":10}],"asks":[{"p":"20001","s":8}]}"#,
        );
        let ticker = gate.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));
        assert!(mock.recorded_requests()[0]
            .url
            .contains("/api/v4/futures/usdt/tickers?contract=BTC_USDT"));
    }

    #[test]
    fn futures_klines_parse_object_rows() {
        let (gate, mock) = futures_client();
        mock.push_json(
            200,
            r#"[{"t":1700000000,"v":12,"o":"100","h":"110","l":"95","c":"105"}]"#,
        );
        let candles = gate.klines(&symbol(), "1h", 1).unwrap();
        assert!((candles[0].open - 100.0).abs() < 1e-9);
        assert!((candles[0].high - 110.0).abs() < 1e-9);
        assert!((candles[0].close - 105.0).abs() < 1e-9);
        assert_eq!(candles[0].timestamp, 1_700_000_000);
        assert!(mock.recorded_requests()[0]
            .url
            .contains("/api/v4/futures/usdt/candlesticks"));
    }

    #[test]
    fn futures_order_book_parses_object_levels() {
        let (gate, mock) = futures_client();
        mock.push_json(
            200,
            r#"{"id":77,"bids":[{"p":"100","s":1}],"asks":[{"p":"101","s":2}]}"#,
        );
        let book = gate.order_book(&symbol(), 5).unwrap();
        assert_eq!(book.last_update_id, 77);
        assert_eq!(book.bids[0], BookLevel::new(dec!(100), dec!(1)));
        assert_eq!(book.asks[0], BookLevel::new(dec!(101), dec!(2)));
    }

    fn hedged_futures_client(now_ms: i64) -> (Gate, Arc<MockHttpTransport>) {
        let mock = Arc::new(MockHttpTransport::new());
        let mut opts = ExchangeOptions::mainnet(crate::MarketType::UsdMFutures);
        opts.position_mode = crate::PositionMode::Hedge;
        let gate = Gate::with_credentials(
            Box::new(ArcTransport(Arc::clone(&mock))),
            &opts,
            Credentials::new("APIKEY", "SECRET"),
        )
        .with_clock(Box::new(move || now_ms));
        (gate, mock)
    }

    const GATE_FUTURES_FILL: &str = r#"{"id":88,"size":2,"left":0,"price":"0",
        "fill_price":"20000","status":"finished","finish_as":"filled","text":""}"#;

    #[test]
    fn dual_mode_closes_with_auto_size_and_opens_by_sign() {
        // Gate calls hedge "dual mode". A close there names the side and sends
        // no size of its own; `reduce_only` alone does not say which of the two
        // open sides is meant. Opening is unchanged: the sign of `size` says it.
        let (hedged, mock) = hedged_futures_client(1_000_000);
        for _ in 0..2 {
            mock.push_json(200, GATE_FUTURES_FILL);
        }
        hedged
            .place_order(&OrderRequest::market_sell(symbol(), dec!(2)).reduce_only())
            .unwrap();
        hedged
            .place_order(&OrderRequest::market_buy(symbol(), dec!(2)))
            .unwrap();

        let reqs = mock.recorded_requests();
        let close = reqs[0].body.as_deref().unwrap();
        assert!(close.contains(r#""auto_size":"close_long""#));
        assert!(close.contains(r#""size":0"#));
        let open = reqs[1].body.as_deref().unwrap();
        assert!(open.contains(r#""size":2"#));
        assert!(!open.contains("auto_size"));

        // The other close: a buy that reduces is closing the short side.
        mock.push_json(200, GATE_FUTURES_FILL);
        hedged
            .place_order(&OrderRequest::market_buy(symbol(), dec!(2)).reduce_only())
            .unwrap();
        assert!(mock.recorded_requests()[2]
            .body
            .as_deref()
            .unwrap()
            .contains(r#""auto_size":"close_short""#));

        // One-way is untouched: reduce_only, real size, no auto_size.
        let (one_way, one_way_mock) = signed_futures_client(1_000_000);
        one_way_mock.push_json(200, GATE_FUTURES_FILL);
        one_way
            .place_order(&OrderRequest::market_sell(symbol(), dec!(2)).reduce_only())
            .unwrap();
        let body = one_way_mock.recorded_requests()[0].body.clone().unwrap();
        assert!(body.contains(r#""reduce_only":true"#));
        assert!(body.contains(r#""size":-2"#));
        assert!(!body.contains("auto_size"));
    }

    #[test]
    fn futures_market_order_uses_signed_size_and_ioc() {
        let (gate, mock) = signed_futures_client(1_000_000);
        mock.push_json(
            200,
            r#"{"id":88,"size":2,"left":0,"price":"0","fill_price":"20000",
            "status":"finished","finish_as":"filled","text":""}"#,
        );
        let order = gate
            .place_order(&OrderRequest::market_buy(symbol(), dec!(2)))
            .unwrap();
        assert_eq!(order.id, "88");
        assert_eq!(order.status, OrderStatus::Filled);
        assert_eq!(order.side, OrderSide::Buy);
        assert_eq!(order.average_price, Some(dec!(20000)));
        let req = &mock.recorded_requests()[0];
        assert!(req.url.contains("/api/v4/futures/usdt/orders"));
        let body = req.body.as_ref().unwrap();
        assert!(body.contains(r#""contract":"BTC_USDT""#));
        assert!(body.contains(r#""size":2"#));
        assert!(body.contains(r#""price":"0""#));
        assert!(body.contains(r#""tif":"ioc""#));
        assert!(body.contains(r#""reduce_only":false"#));
    }

    #[test]
    fn futures_limit_sell_signs_size_negative() {
        let (gate, mock) = signed_futures_client(1_000_000);
        mock.push_json(
            200,
            r#"{"id":90,"size":-3,"left":3,"price":"21000","fill_price":"0",
            "status":"open","finish_as":"","text":""}"#,
        );
        let order = gate
            .place_order(&OrderRequest::limit_sell(symbol(), dec!(3), dec!(21000)))
            .unwrap();
        assert_eq!(order.side, OrderSide::Sell);
        assert_eq!(order.status, OrderStatus::New);
        assert_eq!(order.order_type, OrderType::Limit);
        let reqs = mock.recorded_requests();
        let body = reqs[0].body.as_ref().unwrap();
        assert!(body.contains(r#""size":-3"#));
        assert!(body.contains(r#""price":"21000""#));
    }

    #[test]
    fn derivatives_positions_parse_cross_and_isolated() {
        let (mut gate, mock) = signed_futures_client(1_000_000);
        mock.push_json(
            200,
            r#"[{"contract":"BTC_USDT","size":3,"leverage":"10","entry_price":"20000",
            "mark_price":"20100","unrealised_pnl":"30"},
            {"contract":"ETH_USDT","size":-2,"leverage":"0","cross_leverage_limit":"5",
            "entry_price":"3000","mark_price":"2900","unrealised_pnl":"200"}]"#,
        );
        let positions = Derivatives::positions(&mut gate, None).unwrap();
        assert_eq!(positions.len(), 2);
        assert_eq!(positions[0].symbol, Symbol::new("BTC", "USDT"));
        assert_eq!(positions[0].side, PositionSide::Long);
        assert_eq!(positions[0].quantity, dec!(3));
        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].leverage, dec!(5));
        assert_eq!(positions[1].margin_mode, MarginMode::Cross);
        assert!(mock.recorded_requests()[0]
            .url
            .contains("/api/v4/futures/usdt/positions"));
    }

    #[test]
    fn derivatives_set_leverage_and_cross_switch() {
        let (mut gate, mock) = signed_futures_client(1_000_000);
        mock.push_json(200, "{}");
        Derivatives::set_leverage(&mut gate, &symbol(), 5).unwrap();
        assert!(mock.recorded_requests()[0]
            .url
            .contains("/api/v4/futures/usdt/positions/BTC_USDT/leverage?leverage=5"));

        mock.push_json(200, "{}");
        Derivatives::set_margin_mode(&mut gate, &symbol(), MarginMode::Cross).unwrap();
        assert!(mock.recorded_requests()[1]
            .url
            .contains("leverage?leverage=0"));
    }

    #[test]
    fn derivatives_close_position_is_reduce_only_opposite() {
        let (mut gate, mock) = signed_futures_client(1_000_000);
        mock.push_json(
            200,
            r#"[{"contract":"BTC_USDT","size":3,"leverage":"10","entry_price":"20000",
            "mark_price":"20100","unrealised_pnl":"30"}]"#,
        );
        mock.push_json(
            200,
            r#"{"id":99,"size":-3,"left":0,"price":"0","fill_price":"20100",
            "status":"finished","finish_as":"filled","text":""}"#,
        );
        let order = Derivatives::close_position(&mut gate, &symbol()).unwrap();
        assert_eq!(order.status, OrderStatus::Filled);
        let reqs = mock.recorded_requests();
        let body = reqs[1].body.as_ref().unwrap();
        assert!(body.contains(r#""size":-3"#));
        assert!(body.contains(r#""reduce_only":true"#));
    }

    #[test]
    fn futures_balances_split_total_and_available() {
        let (gate, mock) = signed_futures_client(1_000_000);
        mock.push_json(
            200,
            r#"{"currency":"USDT","total":"1000","available":"800"}"#,
        );
        let bals = gate.balances().unwrap();
        assert_eq!(bals[0].asset, "USDT");
        assert_eq!(bals[0].free, dec!(800));
        assert_eq!(bals[0].locked, dec!(200));
        assert!(mock.recorded_requests()[0]
            .url
            .contains("/api/v4/futures/usdt/accounts"));
    }

    #[test]
    fn futures_query_order_uses_futures_endpoint_and_shape() {
        let (gate, mock) = signed_futures_client(1_000_000);
        mock.push_json(
            200,
            r#"{"id":88,"size":2,"left":0,"price":"100","fill_price":"100",
            "status":"finished","finish_as":"filled","text":""}"#,
        );
        let order = gate.query_order(&symbol(), "88").unwrap();
        assert_eq!(order.id, "88");
        assert_eq!(order.side, OrderSide::Buy);
        assert_eq!(order.status, OrderStatus::Filled);
        assert!(mock.recorded_requests()[0]
            .url
            .contains("/api/v4/futures/usdt/orders/88"));
    }

    #[test]
    fn futures_cancel_order_targets_futures_endpoint() {
        let (gate, mock) = signed_futures_client(1_000_000);
        mock.push_json(
            200,
            r#"{"id":88,"size":0,"left":0,"status":"finished","finish_as":"cancelled"}"#,
        );
        gate.cancel_order(&symbol(), "88").unwrap();
        let req = &mock.recorded_requests()[0];
        assert_eq!(req.method, HttpMethod::Delete);
        assert!(req.url.contains("/api/v4/futures/usdt/orders/88"));
    }

    #[test]
    fn futures_open_orders_parse_contract_shape() {
        let (gate, mock) = signed_futures_client(1_000_000);
        mock.push_json(
            200,
            r#"[{"id":90,"size":-3,"left":3,"price":"21000","fill_price":"0",
            "status":"open","finish_as":"","text":""}]"#,
        );
        let orders = gate.open_orders(Some(&symbol())).unwrap();
        assert_eq!(orders.len(), 1);
        assert_eq!(orders[0].side, OrderSide::Sell);
        assert_eq!(orders[0].status, OrderStatus::New);
        assert!(mock.recorded_requests()[0]
            .url
            .contains("/api/v4/futures/usdt/orders?contract=BTC_USDT&status=open"));
    }

    #[test]
    fn ticker_parses() {
        let (gate, mock) = client();
        mock.push_json(
            200,
            r#"[{"currency_pair":"BTC_USDT","last":"20000","highest_bid":"19999",
            "lowest_ask":"20001","base_volume":"1234"}]"#,
        );
        let ticker = gate.ticker(&symbol()).unwrap();
        assert_eq!(ticker.last, dec!(20000));
        assert_eq!(ticker.bid, dec!(19999));
        let req = &mock.recorded_requests()[0];
        assert_eq!(
            req.url,
            "https://api.gateio.ws/api/v4/spot/tickers?currency_pair=BTC_USDT"
        );
    }

    #[test]
    fn klines_field_order() {
        let (gate, mock) = client();
        // [ts, quoteVol, close, high, low, open, baseVol, closed].
        mock.push_json(
            200,
            r#"[["1700000000","0","105","110","95","100","12","true"]]"#,
        );
        let candles = gate.klines(&symbol(), "1h", 1).unwrap();
        assert!((candles[0].open - 100.0).abs() < 1e-9);
        assert!((candles[0].high - 110.0).abs() < 1e-9);
        assert!((candles[0].close - 105.0).abs() < 1e-9);
        assert_eq!(candles[0].timestamp, 1_700_000_000);
    }

    #[test]
    fn order_book_parses() {
        let (gate, mock) = client();
        mock.push_json(
            200,
            r#"{"update":66,"bids":[["100","1"]],"asks":[["101","2"]]}"#,
        );
        let book = gate.order_book(&symbol(), 5).unwrap();
        assert_eq!(book.last_update_id, 66);
        assert_eq!(book.bids[0], BookLevel::new(dec!(100), dec!(1)));
    }

    #[test]
    fn http_error_maps_to_taxonomy() {
        let (gate, mock) = client();
        mock.push_json(400, r#"{"label":"BALANCE_NOT_ENOUGH","message":"nope"}"#);
        assert!(matches!(
            gate.ticker(&symbol()).unwrap_err(),
            Error::InsufficientBalance
        ));
    }

    #[test]
    fn place_order_signs_with_sha512_body_hash() {
        let (gate, mock) = signed_client(1_000_000); // ms -> 1000 s
        mock.push_json(
            200,
            r#"{"id":"77","text":"t-abc","side":"buy","type":"limit","status":"open",
            "amount":"1","filled_amount":"0","price":"100","avg_deal_price":"0"}"#,
        );
        let order = gate
            .place_order(
                &OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)).with_client_order_id("abc"),
            )
            .unwrap();
        assert_eq!(order.id, "77");
        assert_eq!(order.status, OrderStatus::New);

        let req = &mock.recorded_requests()[0];
        let header = |name: &str| {
            req.headers
                .iter()
                .find(|(k, _)| k == name)
                .map(|(_, v)| v.as_str())
                .unwrap()
        };
        assert_eq!(header("Timestamp"), "1000");
        assert_eq!(header("KEY"), "APIKEY");
        let body = req.body.as_ref().unwrap();
        let body_hash = sha512_hex(body.as_bytes());
        let sign_string = format!("POST\n/api/v4/spot/orders\n\n{body_hash}\n1000");
        assert_eq!(
            header("SIGN"),
            hmac_sha512_hex(b"SECRET", sign_string.as_bytes())
        );
        assert!(body.contains(r#""text":"t-abc""#));
    }

    #[test]
    fn query_and_balances() {
        let (gate, mock) = signed_client(1_000_000);
        mock.push_json(
            200,
            r#"{"id":"77","text":"","side":"sell","type":"market","status":"closed",
            "amount":"2","filled_amount":"2","price":"0","avg_deal_price":"100"}"#,
        );
        let order = gate.query_order(&symbol(), "77").unwrap();
        assert_eq!(order.status, OrderStatus::Filled);
        assert_eq!(order.average_price, Some(dec!(100)));

        mock.push_json(
            200,
            r#"[{"currency":"USDT","available":"100.5","locked":"25.5"}]"#,
        );
        let bals = gate.balances().unwrap();
        assert_eq!(bals[0].total(), dec!(126));
    }

    #[test]
    fn open_orders_requires_symbol() {
        let (gate, _mock) = signed_client(1_000_000);
        assert!(matches!(
            gate.open_orders(None).unwrap_err(),
            Error::InvalidOrder(_)
        ));
    }

    #[test]
    fn signed_requires_credentials() {
        let (gate, _) = client();
        assert!(matches!(
            gate.balances().unwrap_err(),
            Error::InvalidCredentials(_)
        ));
    }

    #[test]
    fn ws_parses_trade_and_book() {
        let ws = Arc::new(MockWsTransport::new());
        ws.push_connection(vec![
            Ok(Some(
                r#"{"time":1,"channel":"spot.trades","event":"update","result":
                {"currency_pair":"BTC_USDT","side":"buy","amount":"0.5","price":"100","create_time_ms":1700}}"#
                    .to_string(),
            )),
            Ok(Some(
                r#"{"time":2,"channel":"spot.order_book_update","event":"update","result":
                {"s":"BTC_USDT","u":9,"b":[["100","1"]],"a":[["101","2"]]}}"#
                    .to_string(),
            )),
            Ok(Some(r#"{"channel":"spot.trades","event":"subscribe"}"#.to_string())),
        ]);
        let http = Arc::new(MockHttpTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::Spot);
        let mut gate = Gate::with_http(Box::new(ArcTransport(http)), &opts)
            .with_ws(Box::new(ArcWs(Arc::clone(&ws))));
        gate.subscribe_trades(&symbol()).unwrap();
        assert!(ws.sent()[0].contains(r#""channel":"spot.trades""#));

        let events = gate.poll_events();
        assert_eq!(events.len(), 2);
        let Event::Trade(t) = &events[0] else {
            panic!("expected trade")
        };
        assert_eq!(t.aggressor, OrderSide::Buy);
        assert_eq!(t.timestamp, 1700);
        let Event::BookDelta(d) = &events[1] else {
            panic!("expected book delta")
        };
        assert_eq!(d.final_update_id, 9);
    }

    #[test]
    fn works_as_a_boxed_exchange() {
        let (gate, mock) = signed_client(1_000_000);
        mock.push_json(
            200,
            r#"{"id":"1","text":"","side":"buy","type":"limit","status":"open",
            "amount":"1","filled_amount":"0","price":"100","avg_deal_price":"0"}"#,
        );
        let mut exchange: Box<dyn Exchange> = Box::new(gate);
        assert_eq!(exchange.name(), "gate");
        let order = exchange
            .place_order(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)))
            .unwrap();
        assert_eq!(order.id, "1");
    }

    #[test]
    fn system_clock_is_sane() {
        assert!(system_now_ms() > 1_600_000_000_000);
    }

    /// `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("Gate {"));
        assert!(rendered.contains("authenticated: true"));
        assert!(!rendered.contains("SECRET"));
        assert!(!rendered.contains("APIKEY"));
    }

    /// The clock offset must reach the wire, not just the struct.
    ///
    /// A venue refuses a signed request whose timestamp is outside its own
    /// receive window, so a machine a few seconds off has every order rejected
    /// -- with a message about the 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 gate, http) = signed_client(1_000_000);

        // Shape verified against the live public endpoint on 2026-09-01.
        http.push_json(200, r#"{"server_time":1004500}"#);
        let offset = gate.sync_time().expect("sync must succeed");
        assert_eq!(offset, 4_500, "the venue is 4.5 s ahead of this machine");

        http.push_json(200, r"[]");
        gate.balances().expect("balances must succeed");

        let requests = http.recorded_requests();
        let signed = requests.last().expect("a signed request was recorded");
        let header = signed
            .headers
            .iter()
            .find(|(name, _)| name == "Timestamp")
            .map(|(_, value)| value.as_str())
            .expect("signed request carries Timestamp");
        assert_eq!(header, "1004", "seconds of the venue's time, not ours");
    }

    /// 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 (gate, mock) = client();
        mock.push_response(
            crate::transport::HttpResponse::new(
                429,
                r#"{"label":"TOO_MANY_REQUESTS","message":"slow down"}"#,
            )
            .with_header("Retry-After", "2.5"),
        );
        let err = gate.ticker(&symbol()).unwrap_err();
        let wait = std::time::Duration::from_millis(2500);
        assert!(matches!(err, Error::RateLimited { retry_after: Some(d) } if d == wait));
    }
}