wickra-exchange-core 0.2.0

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
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
//! Kraken — the eighth exchange.
//!
//! Kraken's private signing is the most involved: `API-Sign = base64(HMAC-SHA512(
//! base64decode(secret), path_bytes ++ SHA256(nonce ++ postdata)))`, with the
//! request sent as a form-encoded POST carrying an increasing `nonce`. The API
//! secret is itself base64. REST uses concatenated symbols with Bitcoin spelled
//! `XBT` (`XBTUSDT`) and returns a `{error, result}` envelope where `result` is
//! keyed by the venue's own pair name; the v2 WebSocket uses slash symbols
//! (`BTC/USDT`).
//!
//! When built with a futures [`MarketType`](crate::MarketType), the client
//! targets **Kraken Futures** (`futures.kraken.com`), a separate product: flex
//! multi-collateral perpetuals named `PF_XBTUSD` (USD-settled), a distinct
//! `{"result":"success"|"error"}` envelope, and its own signing
//! (`Authent = base64(HMAC-SHA512(b64secret, SHA256(postData ++ nonce ++
//! path)))`). Market data uses `/derivatives/api/v3/{tickers,orderbook}` and the
//! `/api/charts/v1` OHLC feed; execution and the [`Derivatives`] trait use
//! `sendorder`/`openpositions`/`leveragepreferences`, and
//! `query_order`/`cancel_order`/`open_orders` route to
//! `/derivatives/api/v3/{orders/status,cancelorder,openorders}` with the Kraken
//! Futures order shape. The [`WsUserData`] stream routes to the separate Kraken
//! Futures feed (`wss://futures.kraken.com/ws/v1`, challenge/response auth →
//! `open_orders`/`balances`). Documented gaps: [`WsExecution`] stays REST-only
//! (Kraken Futures has no WebSocket order-entry API), `openpositions` omits mark
//! price and unrealized PnL, and `set_margin_mode(Isolated)` is unsupported within
//! the flex (cross) account.
//!
//! [`AdvancedOrders`]: native in-place amend (`/0/private/EditOrder`, which
//! assigns a new txid), native batch placement (`/0/private/AddOrderBatch`, whose
//! indexed `orders[i][…]` form array is built by a dedicated encoder) and native
//! batch cancel (`/0/private/CancelOrderBatch`). Kraken has no OCO order-list (it
//! uses conditional-close orders), so `place_oco` is a documented gap.

use std::collections::HashMap;

use crate::clock::{NonceGenerator, ServerClock, TokenTtl};
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_base64_with_b64_secret, sha256};
use crate::symbol::Symbol;
use crate::traits::{
    AdvancedOrders, Derivatives, DerivativesStream, Exchange, Execution, MarketData, WsExecution,
    WsUserData,
};
use crate::transport::{HttpMethod, HttpRequest, HttpTransport, WsConnection, WsTransport};
use crate::types::{
    Balance, OcoRequest, Order, OrderRequest, OrderSide, OrderStatus, OrderType, Ticker,
    TimeInForce,
};
use rust_decimal::Decimal;
use std::cell::Cell;
use std::fmt;
use wickra_core::Candle;

/// Spot REST host.
const SPOT_HOST: &str = "https://api.kraken.com";
/// Kraken Futures host (a separate product with its own signing and symbols).
const FUTURES_HOST: &str = "https://futures.kraken.com";

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 Kraken client over injected transports.
pub struct Kraken {
    http: Box<dyn HttpTransport>,
    ws: Option<Box<dyn WsTransport>>,
    rest_base: String,
    market_type: MarketType,
    /// One-way or hedge. Kraken Futures is one-way only, so a hedged
    /// configuration is refused rather than silently ignored.
    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,
    /// Kraken requires a strictly increasing nonce per API key. The wall
    /// clock alone is not one: two signed calls inside the same millisecond
    /// produce the same value, and a clock that steps backwards produces a
    /// smaller one -- both are refused with `Invalid nonce`.
    nonces: NonceGenerator,
    connection: Option<Box<dyn WsConnection>>,
    sub_messages: Vec<String>,
    /// `product_id` -> canonical symbol, for the futures stream.
    ///
    /// The spot v2 frames carry the canonical slash symbol and need no
    /// mapping. Futures frames carry `PF_XBTUSD`, which cannot be turned
    /// back into `BTC/USDT` without knowing what was asked for: the quote
    /// is folded to USD on the way out, and `XBT` is Kraken's own spelling.
    futures_subscriptions: Vec<(String, Symbol)>,
    /// Which derivatives channels are subscribed, per product.
    ///
    /// Kraken's futures `ticker` frame carries the funding rate, the mark
    /// price and the index together, so one frame can answer three
    /// subscriptions. Only what was asked for is emitted.
    derivatives_channels: Vec<(String, DerivativesChannel)>,
    /// Leverage applied on Kraken Futures (`maxLeverage` preference), recorded so
    /// [`positions`](Self::positions) can report it (the venue omits per-position
    /// leverage in `openpositions`).
    leverage: Cell<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 (re-fetching a fresh single-use token) after a drop.
    user_data_active: bool,
    /// A dedicated connection to the v2 authenticated order API, opened lazily on
    /// the first [`place_order_ws`](Self::place_order_ws) / [`cancel_order_ws`](Self::cancel_order_ws)
    /// call, together with the WebSocket token each request carries.
    ws_api_connection: Option<Box<dyn WsConnection>>,
    ws_api_token: Option<String>,
    /// When the cached `ws_api_token` stops being accepted.
    ///
    /// `GetWebSocketsToken` returns the token together with an `expires`
    /// (900 seconds). The token was cached and the expiry discarded, so a
    /// client placing orders over the WebSocket API for longer than fifteen
    /// minutes kept sending one the venue had stopped accepting -- and
    /// `ensure_ws_api` would not refetch, because the *connection* was still
    /// open.
    ws_api_token_ttl: Option<TokenTtl>,
}

/// 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 Kraken {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Kraken")
            .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("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())
            // Presence, never the value: this token authenticates the
            // WebSocket session, so it is credential material and must not
            // reach a log line.
            .field("ws_api_token", &self.ws_api_token.is_some())
            .finish_non_exhaustive()
    }
}

impl Kraken {
    /// 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("Kraken", self.market_type, super::SPOT_AND_LINEAR)
    }

    fn build(
        http: Box<dyn HttpTransport>,
        options: &ExchangeOptions,
        credentials: Option<Credentials>,
    ) -> Self {
        let futures = options.market_type.is_derivatives();
        Self {
            http,
            ws: None,
            rest_base: if futures { FUTURES_HOST } else { SPOT_HOST }.to_string(),
            market_type: options.market_type,
            position_mode: options.position_mode,
            credentials,
            now_ms: Box::new(system_now_ms),
            clock: ServerClock::new(),
            nonces: NonceGenerator::new(0),
            connection: None,
            sub_messages: Vec::new(),
            futures_subscriptions: Vec::new(),
            derivatives_channels: Vec::new(),
            leverage: Cell::new(1),
            private_connection: None,
            user_data_active: false,
            ws_api_connection: None,
            ws_api_token: None,
            ws_api_token_ttl: None,
        }
    }

    /// The timestamp a signed request must carry: this machine's clock plus the
    /// offset learned from the venue.
    fn signed_now_ms(&self) -> i64 {
        self.clock.server_time_ms((self.now_ms)())
    }

    /// The next nonce for a signed request: strictly greater than the last one
    /// this client issued, whatever the clock does.
    ///
    /// Kraken documents the nonce as an always-increasing unsigned integer and
    /// refuses anything else. Milliseconds alone do not satisfy that -- two
    /// signed calls inside one millisecond yield the same value -- so the
    /// generator raises the candidate above the previous nonce when it has to.
    fn next_nonce(&self) -> u64 {
        let candidate = u64::try_from(self.signed_now_ms()).unwrap_or(0);
        self.nonces.next(candidate)
    }

    /// Learn the offset between this machine's clock and the venue's, from
    /// `GET /0/public/Time`.
    ///
    /// Explicit rather than automatic: it costs a request, and a client should
    /// not make one the caller did not ask for.
    ///
    /// 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> {
        // Kraken is the one venue here that reports *seconds*:
        // {"error":[],"result":{"unixtime":1788295967,"rfc1123":"..."}}
        let local_before = (self.now_ms)();
        let value = self.get("/0/public/Time", "")?;
        let seconds = value
            .get("unixtime")
            .and_then(serde_json::Value::as_i64)
            .ok_or_else(|| Error::Deserialization("public/Time: no unixtime".into()))?;
        self.clock.sync(local_before, seconds * 1000);
        Ok(self.clock.offset_ms())
    }

    /// Whether this client targets Kraken Futures (`futures.kraken.com`) rather
    /// than the spot REST API.
    fn is_futures(&self) -> bool {
        self.market_type.is_derivatives()
    }

    /// Refuse a futures order on a client configured for hedge mode.
    ///
    /// Kraken Futures holds one net position per contract and has no
    /// hedge (dual-side) mode, so there is no
    /// field on the order that could carry the side. Placing the order anyway
    /// would open or close the single net position -- which is what the caller
    /// asked to avoid by configuring hedge. Same treatment as
    /// `set_margin_mode(Isolated)` here: say so rather than do something else.
    ///
    /// # Errors
    /// Returns [`Error::Exchange`] on a futures client in
    /// [`PositionMode::Hedge`](crate::PositionMode).
    fn ensure_one_way(&self) -> Result<()> {
        if self.is_futures() && self.position_mode == PositionMode::Hedge {
            return Err(Error::Exchange {
                code: "unsupported".to_string(),
                message: "Kraken Futures is one-way only; PositionMode::Hedge cannot be                           expressed on its orders"
                    .to_string(),
            });
        }
        Ok(())
    }

    /// The Kraken **Futures** perpetual symbol for a canonical [`Symbol`]
    /// (`BTC/USD` -> `PF_XBTUSD`). Kraken flex perpetuals are USD-settled, so a
    /// `USDT` quote maps to the `USD` contract.
    fn futures_symbol(symbol: &Symbol) -> String {
        let quote = if symbol.quote() == "USDT" {
            "USD"
        } else {
            symbol.quote()
        };
        format!("PF_{}{}", kraken_asset(symbol.base()), quote)
    }

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

    /// Build an authenticated Kraken client (the secret must be base64).
    #[must_use]
    pub fn with_credentials(
        http: Box<dyn HttpTransport>,
        options: &ExchangeOptions,
        credentials: Credentials,
    ) -> Self {
        Self::build(http, options, Some(credentials))
    }

    /// Override the timestamp/nonce 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 Kraken REST wire symbol (`BTC/USDT` -> `XBTUSDT`, Bitcoin spelled XBT).
    #[must_use]
    pub fn wire_symbol(symbol: &Symbol) -> String {
        format!("{}{}", kraken_asset(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!("pair={}", Self::wire_symbol(symbol));
        let result = self.get("/0/public/Ticker", &query)?;
        let tick = single_result(&result)?;
        Ok(Ticker {
            symbol: symbol.clone(),
            last: decimal_at(tick, "c", 0)?,
            bid: decimal_at(tick, "b", 0)?,
            ask: decimal_at(tick, "a", 0)?,
            volume: decimal_at(tick, "v", 1)?,
            // Kraken's spot ticker carries no timestamp; verified against the
            // live endpoint.
            timestamp: 0,
        })
    }

    fn futures_ticker(&self, symbol: &Symbol) -> Result<Ticker> {
        let wanted = Self::futures_symbol(symbol);
        let value = self.futures_get("/derivatives/api/v3/tickers", "")?;
        let tick = value
            .get("tickers")
            .and_then(serde_json::Value::as_array)
            .and_then(|list| {
                list.iter().find(|t| {
                    t.get("symbol")
                        .and_then(serde_json::Value::as_str)
                        .is_some_and(|s| s.eq_ignore_ascii_case(&wanted))
                })
            })
            .ok_or_else(|| Error::NotFound(format!("no ticker for {symbol}")))?;
        Ok(Ticker {
            symbol: symbol.clone(),
            last: decimal_field(tick, "last").or_else(|_| decimal_field(tick, "markPrice"))?,
            bid: decimal_field(tick, "bid").unwrap_or(Decimal::ZERO),
            ask: decimal_field(tick, "ask").unwrap_or(Decimal::ZERO),
            volume: decimal_field(tick, "vol24h").unwrap_or(Decimal::ZERO),
            timestamp: 0,
        })
    }

    /// Up to `limit` candles for `symbol` at `interval` (unified). Kraken returns
    /// oldest-first.
    ///
    /// # 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() {
            return self.futures_klines(symbol, interval);
        }
        let query = format!(
            "pair={}&interval={}",
            Self::wire_symbol(symbol),
            map_interval(interval),
        );
        let result = self.get("/0/public/OHLC", &query)?;
        // result has the pair key (an array) plus a scalar "last".
        let rows = result
            .as_object()
            .and_then(|obj| {
                obj.iter()
                    .find(|(key, value)| *key != "last" && value.is_array())
            })
            .map(|(_, value)| value)
            .and_then(serde_json::Value::as_array)
            .ok_or_else(|| Error::Deserialization("missing OHLC rows".to_string()))?;
        rows.iter().map(parse_kline_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!("symbol={}", Self::futures_symbol(symbol));
            let value = self.futures_get("/derivatives/api/v3/orderbook", &query)?;
            let book = value
                .get("orderBook")
                .ok_or_else(|| Error::Deserialization("missing orderBook".to_string()))?;
            return Ok(OrderBookSnapshot {
                symbol: symbol.clone(),
                last_update_id: 0,
                bids: num_pair_levels(book.get("bids"))?,
                asks: num_pair_levels(book.get("asks"))?,
                timestamp: 0,
            });
        }
        let query = format!("pair={}&count={depth}", Self::wire_symbol(symbol));
        let result = self.get("/0/public/Depth", &query)?;
        let book = single_result(&result)?;
        Ok(OrderBookSnapshot {
            symbol: symbol.clone(),
            last_update_id: 0,
            bids: rest_levels(book.get("bids"))?,
            asks: rest_levels(book.get("asks"))?,
            // Kraken's REST depth stamps each level, not the book; there is no
            // single "as of" to report here.
            timestamp: 0,
        })
    }

    /// 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, "trade")
    }

    /// 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, "book")
    }

    /// 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, "ticker")
    }

    fn subscribe(&mut self, symbol: &Symbol, channel: &str) -> Result<()> {
        self.ensure_market_is_routed()?;
        if self.is_futures() {
            return self.subscribe_futures(symbol, channel);
        }

        if self.connection.is_none() {
            let ws = self.ws.as_ref().ok_or(Error::NotConnected)?;
            let connection = ws.connect("wss://ws.kraken.com/v2")?;
            self.connection = Some(connection);
        }
        // The v2 WebSocket uses the canonical slash symbol.
        let message = format!(
            r#"{{"method":"subscribe","params":{{"channel":"{channel}","symbol":["{symbol}"]}}}}"#
        );
        self.connection
            .as_mut()
            .expect("connection just ensured")
            .send(&message)?;
        if !self.sub_messages.contains(&message) {
            self.sub_messages.push(message.clone());
        }
        Ok(())
    }

    /// Subscribe on Kraken Futures, which is a different service from the spot
    /// v2 socket rather than the same one with other names.
    ///
    /// `{"event":"subscribe","feed":..,"product_ids":[..]}` against
    /// `futures.kraken.com`, keyed by `PF_XBTUSD`. The three feeds happen to be
    /// spelled the same as the spot channels -- `trade`, `book`, `ticker` --
    /// which is the only thing the two protocols share.
    fn subscribe_futures(&mut self, symbol: &Symbol, feed: &str) -> Result<()> {
        self.ensure_market_is_routed()?;
        let product = Self::futures_symbol(symbol);
        if self.connection.is_none() {
            let ws = self.ws.as_ref().ok_or(Error::NotConnected)?;
            let connection = ws.connect(FUTURES_WS_URL)?;
            self.connection = Some(connection);
        }
        let message =
            format!(r#"{{"event":"subscribe","feed":"{feed}","product_ids":["{product}"]}}"#);
        self.connection
            .as_mut()
            .expect("connection just ensured")
            .send(&message)?;
        if !self.sub_messages.contains(&message) {
            self.sub_messages.push(message);
        }
        if !self
            .futures_subscriptions
            .iter()
            .any(|(p, _)| p == &product)
        {
            self.futures_subscriptions.push((product, symbol.clone()));
        }
        Ok(())
    }

    /// Subscribe to a pushed derivatives channel.
    ///
    /// Kraken Futures publishes the funding rate, the mark price and the index
    /// in its `ticker` feed -- one reading, one moment -- so `Funding` and
    /// `MarkIndex` are the same subscription seen two ways.
    ///
    /// The rate carried is `relative_funding_rate`, the proportion charged for
    /// the interval. `funding_rate` beside it is that proportion times the
    /// index, an absolute amount per contract, and reporting it as a rate would
    /// be off by four orders of magnitude.
    ///
    /// `Liquidations` is refused: Kraken Futures publishes no public feed of
    /// forced orders.
    ///
    /// # 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(
                "Kraken",
                "a derivatives channel on a spot client",
                "funding and mark/index exist only on Kraken Futures",
            ));
        }
        if channel == DerivativesChannel::Liquidations {
            return Err(Error::unsupported_field(
                "Kraken",
                "a liquidations channel",
                "Kraken Futures publishes no public feed of forced orders",
            ));
        }
        let product = Self::futures_symbol(symbol);
        if !self
            .derivatives_channels
            .iter()
            .any(|(p, c)| p == &product && *c == channel)
        {
            self.derivatives_channels.push((product, channel));
        }
        self.subscribe_futures(symbol, "ticker")
    }

    /// The current open interest (`GET /derivatives/api/v3/tickers`).
    ///
    /// Polled, not pushed. Kraken publishes one row per product and the figure
    /// is in base units, as its `PF_` contracts quote.
    ///
    /// # Errors
    /// Returns an [`Error`] on a spot client, if the request fails, or if the
    /// product is not in the reply.
    pub fn open_interest(&self, symbol: &Symbol) -> Result<OpenInterest> {
        if !self.is_futures() {
            return Err(Error::unsupported_field(
                "Kraken",
                "open interest on a spot client",
                "open interest is a futures figure",
            ));
        }
        let product = Self::futures_symbol(symbol);
        let value = self.futures_get("/derivatives/api/v3/tickers", "")?;
        let row = value
            .get("tickers")
            .and_then(serde_json::Value::as_array)
            .and_then(|rows| {
                rows.iter().find(|row| {
                    row.get("symbol").and_then(serde_json::Value::as_str) == Some(&product)
                })
            })
            .ok_or_else(|| Error::NotFound(format!("{product} is not in the ticker list")))?;
        Ok(OpenInterest {
            symbol: symbol.clone(),
            open_interest: futures_decimal(row, "openInterest")
                .ok_or_else(|| Error::Deserialization("no openInterest".to_string()))?,
            timestamp: 0,
        })
    }

    /// Kraken publishes no long/short positioning figure.
    ///
    /// # Errors
    /// Always returns an [`Error`]: there is nothing to read.
    pub fn long_short_ratio(&self, _symbol: &Symbol) -> Result<LongShortRatio> {
        Err(Error::unsupported_field(
            "Kraken",
            "long/short positioning",
            "Kraken publishes no public account-positioning figure",
        ))
    }

    /// Drain all stream events available since the last call. Non-blocking.
    pub fn poll_events(&mut self) -> Vec<Event> {
        let products: HashMap<String, Symbol> =
            self.futures_subscriptions.iter().cloned().collect();
        let resolve = |product: &str| products.get(product).cloned();
        let channels = self.derivatives_channels.clone();
        let subscribed = |product: &str, channel: DerivativesChannel| {
            channels.iter().any(|(p, c)| p == product && *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, if open. The spot client streams the
        // v2 executions/balances channels; the futures client streams the separate
        // Kraken Futures open_orders/balances feeds, which use a different shape.
        let futures = self.is_futures();
        if let Some(connection) = self.private_connection.as_mut() {
            while let Ok(Some(frame)) = connection.recv() {
                let parsed = if futures {
                    parse_futures_private(&frame)
                } else {
                    parse_ws_message(&frame, &resolve, &subscribed)
                };
                if let Ok(mut parsed) = parsed {
                    events.append(&mut parsed);
                }
            }
        }
        // A dropped private stream is re-subscribed with a fresh handshake — the
        // spot client re-fetches a single-use WebSockets token, the futures client
        // re-runs the challenge/response — neither of which can be replayed.
        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://ws.kraken.com/v2";
        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. Fetches a single-use token over REST
    /// (`POST /0/private/GetWebSocketsToken`, signed), connects
    /// `wss://ws-auth.kraken.com/v2`, then subscribes to the token-authenticated
    /// `executions` and `balances` channels. 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), which re-fetches a fresh token; call
    /// [`keepalive_user_data`](Self::keepalive_user_data) periodically to keep it
    /// from being dropped for inactivity.
    ///
    /// The **futures** client routes to the separate Kraken Futures feed
    /// (`wss://futures.kraken.com/ws/v1`), which authenticates by
    /// challenge/response rather than with a token.
    ///
    /// # Errors
    /// Returns [`Error::InvalidCredentials`] without credentials,
    /// [`Error::NotConnected`] without a WebSocket transport, or another
    /// [`Error`] if the token request fails.
    pub fn subscribe_user_data(&mut self) -> Result<()> {
        self.ensure_market_is_routed()?;
        if self.is_futures() {
            return self.subscribe_user_data_futures();
        }
        let result = self.signed_post("/0/private/GetWebSocketsToken", &[])?;
        let token = result
            .get("token")
            .and_then(serde_json::Value::as_str)
            .ok_or_else(|| Error::Deserialization("missing WebSockets token".to_string()))?;
        let executions = format!(
            r#"{{"method":"subscribe","params":{{"channel":"executions","token":"{token}","snap_orders":true}}}}"#
        );
        let balances = format!(
            r#"{{"method":"subscribe","params":{{"channel":"balances","token":"{token}","snap_balances":true}}}}"#
        );
        let ws = self.ws.as_ref().ok_or(Error::NotConnected)?;
        let mut connection = ws.connect("wss://ws-auth.kraken.com/v2")?;
        connection.send(&executions)?;
        connection.send(&balances)?;
        self.private_connection = Some(connection);
        self.user_data_active = true;
        Ok(())
    }

    /// Open the Kraken Futures private feed (`wss://futures.kraken.com/ws/v1`).
    /// Runs the challenge/response handshake — request a challenge
    /// (`{"event":"challenge","api_key":…}`), read the `{"event":"challenge",
    /// "message":<uuid>}` reply, and compute `signed_challenge =
    /// base64(HMAC-SHA512(base64decode(secret), SHA256(challenge)))` — then
    /// subscribes to the `open_orders` and `balances` feeds with the api key, the
    /// original challenge and the signed challenge. Afterwards
    /// [`poll_events`](Self::poll_events) surfaces the account's own
    /// [`Event::OrderUpdate`] and [`Event::BalanceUpdate`].
    ///
    /// # Errors
    /// Returns [`Error::InvalidCredentials`] without credentials,
    /// [`Error::NotConnected`] without a WebSocket transport, or another
    /// [`Error`] if the handshake fails.
    fn subscribe_user_data_futures(&mut self) -> Result<()> {
        self.ensure_market_is_routed()?;
        let creds = self.credentials.as_ref().ok_or(Error::InvalidCredentials(
            "user-data stream requires credentials",
        ))?;
        let api_key = creds.api_key.clone();
        let api_secret = creds.api_secret.clone();
        let ws = self.ws.as_ref().ok_or(Error::NotConnected)?;
        let mut connection = ws.connect("wss://futures.kraken.com/ws/v1")?;
        // 1. Request a challenge for this api key.
        connection.send(&format!(r#"{{"event":"challenge","api_key":"{api_key}"}}"#))?;
        // 2. Read the challenge message, skipping any unrelated frames.
        let challenge = loop {
            let Some(frame) = connection.recv()? else {
                return Err(Error::NotConnected);
            };
            let value: serde_json::Value =
                serde_json::from_str(&frame).map_err(|e| Error::Deserialization(e.to_string()))?;
            if value.get("event").and_then(serde_json::Value::as_str) == Some("challenge") {
                break value
                    .get("message")
                    .and_then(serde_json::Value::as_str)
                    .ok_or_else(|| Error::Deserialization("missing challenge message".to_string()))?
                    .to_string();
            }
        };
        // 3. signed_challenge = base64(HMAC-SHA512(base64decode(secret), SHA256(challenge))).
        let signed =
            hmac_sha512_base64_with_b64_secret(&api_secret, &sha256(challenge.as_bytes()))?;
        // 4. Subscribe to the private feeds with the signed challenge.
        for feed in ["open_orders", "balances"] {
            connection.send(&format!(
                r#"{{"event":"subscribe","feed":"{feed}","api_key":"{api_key}","original_challenge":"{challenge}","signed_challenge":"{signed}"}}"#
            ))?;
        }
        self.private_connection = Some(connection);
        self.user_data_active = true;
        Ok(())
    }

    /// Send the Kraken v2 application-level heartbeat (`{"method":"ping"}`) on the
    /// spot private stream so it is not dropped for inactivity. A no-op before
    /// [`subscribe_user_data`](Self::subscribe_user_data), and a no-op on the
    /// futures client (Kraken Futures keeps the feed alive server-side via its
    /// heartbeat feed, so no client ping is required).
    ///
    /// # Errors
    /// Returns an [`Error`] if the ping cannot be sent.
    pub fn keepalive_user_data(&mut self) -> Result<()> {
        if self.is_futures() {
            return Ok(());
        }
        if let Some(connection) = self.private_connection.as_mut() {
            connection.send(r#"{"method":"ping"}"#)?;
        }
        Ok(())
    }

    /// Place an order over the Kraken v2 authenticated WebSocket order API
    /// (`add_order`). Fetches a `GetWebSocketsToken` token over REST on first use, connects
    /// `wss://ws-auth.kraken.com/v2`, and sends the order with the token.
    ///
    /// # Errors
    /// Returns [`Error::Exchange`] on the **futures** client (Kraken Futures uses a
    /// separate feed), [`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("Kraken"));
        }
        self.ensure_reduce_only_is_reducible(request)?;
        self.ensure_one_way()?;
        // The REST spot body spells post-only as `oflags=post`; this frame is
        // the v2 WebSocket protocol, which names every other field differently
        // (`order_qty`, `limit_price`, `cl_ord_id`), so the REST spelling does
        // not carry over. Sending the order without it would place a limit that
        // may take liquidity -- the one thing post-only exists to prevent.
        ensure_no_stp(request)?;
        if request.post_only {
            return Err(Error::Exchange {
                code: "unsupported".to_string(),
                message: "Kraken: post-only is not wired on the v2 WebSocket order                           API; place post-only orders over REST (/0/private/AddOrder)"
                    .to_string(),
            });
        }
        request.validate()?;
        let mut params = serde_json::Map::new();
        params.insert(
            "order_type".to_string(),
            serde_json::json!(order_type_str(request.order_type)),
        );
        params.insert(
            "side".to_string(),
            serde_json::json!(side_str(request.side)),
        );
        params.insert("order_qty".to_string(), json_number(request.quantity));
        params.insert(
            "symbol".to_string(),
            serde_json::json!(request.symbol.to_string()),
        );
        if let Some(price) = request.price {
            params.insert("limit_price".to_string(), json_number(price));
        }
        if let Some(tif) = tif_str(request.time_in_force)? {
            params.insert(
                "time_in_force".to_string(),
                serde_json::json!(tif.to_lowercase()),
            );
        }
        if let Some(id) = &request.client_order_id {
            params.insert("cl_ord_id".to_string(), serde_json::json!(id.clone()));
        }
        let result = self.ws_order_request("add_order", params)?;
        let id = result
            .get("order_id")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default()
            .to_string();
        Ok(Order {
            id,
            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,
        })
    }

    /// Cancel an order over the Kraken v2 authenticated WebSocket order API
    /// (`cancel_order`).
    ///
    /// # 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<()> {
        let mut params = serde_json::Map::new();
        params.insert("order_id".to_string(), serde_json::json!([order_id]));
        self.ws_order_request("cancel_order", params)?;
        Ok(())
    }

    /// Open the authenticated order connection if needed: fetch a
    /// `GetWebSocketsToken` token over REST, connect `wss://ws-auth.kraken.com/v2`,
    /// and cache both.
    fn ensure_ws_api(&mut self) -> Result<()> {
        self.ensure_market_is_routed()?;
        // An open connection is not enough: the token is sent with every order
        // frame and expires on its own schedule, so a live connection can carry
        // a dead token.
        if self.ws_api_connection.is_some() && !self.ws_api_token_expired() {
            return Ok(());
        }
        // Past the expiry the cached pair is worthless: drop both so the fetch
        // below replaces them rather than layering a new token on a stale
        // connection.
        self.ws_api_connection = None;
        self.ws_api_token = None;
        self.ws_api_token_ttl = None;
        if self.is_futures() {
            return Err(Error::Exchange {
                code: "unsupported".to_string(),
                message: "Kraken Futures exposes a separate WebSocket order feed \
                          (challenge/response auth on futures.kraken.com); the spot \
                          v2 order API is not available for the futures client"
                    .to_string(),
            });
        }
        let result = self.signed_post("/0/private/GetWebSocketsToken", &[])?;
        let token = result
            .get("token")
            .and_then(serde_json::Value::as_str)
            .ok_or_else(|| Error::Deserialization("missing WebSockets token".to_string()))?
            .to_string();
        // `expires` is seconds and was previously read past. Kraken has returned
        // 900 for as long as this endpoint has existed, but the response is the
        // authority, not that constant.
        let expires_s = result
            .get("expires")
            .and_then(serde_json::Value::as_i64)
            .unwrap_or(900);
        let ws = self.ws.as_ref().ok_or(Error::NotConnected)?;
        let connection = ws.connect("wss://ws-auth.kraken.com/v2")?;
        self.ws_api_connection = Some(connection);
        self.ws_api_token = Some(token);
        self.ws_api_token_ttl = Some(TokenTtl::new(self.signed_now_ms(), expires_s * 1000));
        Ok(())
    }

    /// Whether the cached WebSocket token has passed its expiry.
    ///
    /// A token with no recorded lifetime counts as expired: it predates this
    /// tracking, and refetching one is cheaper than sending one the venue will
    /// refuse.
    fn ws_api_token_expired(&self) -> bool {
        self.ws_api_token_ttl
            .is_none_or(|ttl| ttl.is_expired(self.signed_now_ms()))
    }

    /// Send a token-authenticated order request frame and return its `result`,
    /// mapping `success == false` onto the error taxonomy.
    fn ws_order_request(
        &mut self,
        method: &str,
        mut params: serde_json::Map<String, serde_json::Value>,
    ) -> Result<serde_json::Value> {
        self.ensure_ws_api()?;
        let token = self
            .ws_api_token
            .clone()
            .expect("token set alongside the connection");
        params.insert("token".to_string(), serde_json::json!(token));
        let req_id = (self.now_ms)();
        let frame = serde_json::json!({
            "method": method,
            "params": serde_json::Value::Object(params),
            "req_id": req_id,
        })
        .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()))?;
        if value.get("success").and_then(serde_json::Value::as_bool) == Some(true) {
            Ok(value
                .get("result")
                .cloned()
                .unwrap_or(serde_json::Value::Null))
        } else {
            let message = value
                .get("error")
                .and_then(serde_json::Value::as_str)
                .unwrap_or("order rejected")
                .to_string();
            Err(Error::OrderRejected {
                code: "ws".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(
                "Kraken",
                "reduce_only on a spot order",
                "spot holds balances, not positions, and has none to reduce",
            ));
        }
        Ok(())
    }

    pub fn place_order(&self, request: &OrderRequest) -> Result<Order> {
        self.ensure_reduce_only_is_reducible(request)?;
        self.ensure_one_way()?;
        request.validate()?;
        ensure_no_stp(request)?;
        if self.is_futures() {
            return self.place_futures_order(request);
        }
        let volume = format_decimal(request.quantity);
        let mut params: Vec<(&str, String)> = vec![
            ("pair", Self::wire_symbol(&request.symbol)),
            ("type", side_str(request.side).to_string()),
            ("ordertype", spot_order_type(request.order_type).to_string()),
            ("volume", volume),
        ];
        // On a trigger order `price` is the *trigger* and `price2` the limit;
        // on a plain limit `price` is the limit. Getting this the wrong way
        // round would arm the stop at the limit price.
        if request.order_type.is_trigger() {
            let stop = request
                .stop_price
                .ok_or(Error::InvalidOrder("a trigger order requires a stop price"))?;
            params.push(("price", format_decimal(stop)));
            if let Some(price) = request.price {
                params.push(("price2", format_decimal(price)));
            }
        } else if let Some(price) = request.price {
            params.push(("price", format_decimal(price)));
        }
        if request.post_only {
            params.push(("oflags", "post".to_string()));
        }
        if let Some(tif) = tif_str(request.time_in_force)? {
            params.push(("timeinforce", tif.to_string()));
        }
        if let Some(id) = &request.client_order_id {
            params.push(("cl_ord_id", id.clone()));
        }
        let result = self.signed_post("/0/private/AddOrder", &params)?;
        let txid = result
            .get("txid")
            .and_then(serde_json::Value::as_array)
            .and_then(|a| a.first())
            .and_then(serde_json::Value::as_str)
            .ok_or_else(|| Error::Deserialization("missing txid".to_string()))?;
        Ok(Order {
            id: txid.to_string(),
            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,
        })
    }

    /// 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() {
            self.signed_futures(
                HttpMethod::Post,
                "/derivatives/api/v3/cancelorder",
                &[("order_id", order_id.to_string())],
            )?;
            return Ok(());
        }
        self.signed_post("/0/private/CancelOrder", &[("txid", order_id.to_string())])?;
        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 value = self.signed_futures(
                HttpMethod::Post,
                "/derivatives/api/v3/orders/status",
                &[("orderIds", format!("[\"{order_id}\"]"))],
            )?;
            let order = value
                .get("orders")
                .and_then(serde_json::Value::as_array)
                .and_then(|a| a.first())
                .ok_or_else(|| Error::NotFound(format!("order {order_id}")))?;
            return kraken_futures_order(symbol.clone(), order_id, order);
        }
        let result =
            self.signed_post("/0/private/QueryOrders", &[("txid", order_id.to_string())])?;
        let order = result
            .get(order_id)
            .ok_or_else(|| Error::NotFound(format!("order {order_id}")))?;
        order_from_value(symbol.clone(), order_id, order)
    }

    /// Open orders (Kraken returns them all; the `symbol` filter is applied locally).
    ///
    /// # Errors
    /// Returns an [`Error`] if credentials are missing or the request fails.
    pub fn open_orders(&self, symbol: Option<&Symbol>) -> Result<Vec<Order>> {
        if self.is_futures() {
            let value =
                self.signed_futures(HttpMethod::Get, "/derivatives/api/v3/openorders", &[])?;
            let open = value
                .get("openOrders")
                .and_then(serde_json::Value::as_array)
                .ok_or_else(|| Error::Deserialization("missing openOrders".to_string()))?;
            let want = symbol.map(Self::futures_symbol);
            return open
                .iter()
                .filter(|order| {
                    want.as_ref().is_none_or(|w| {
                        order
                            .get("symbol")
                            .and_then(serde_json::Value::as_str)
                            .is_some_and(|s| s.eq_ignore_ascii_case(w))
                    })
                })
                .map(|order| {
                    let sym = symbol.cloned().unwrap_or_else(|| {
                        symbol_from_futures(
                            order
                                .get("symbol")
                                .and_then(serde_json::Value::as_str)
                                .unwrap_or(""),
                        )
                    });
                    let id = order
                        .get("order_id")
                        .and_then(serde_json::Value::as_str)
                        .unwrap_or("");
                    kraken_futures_order(sym, id, order)
                })
                .collect();
        }
        let result = self.signed_post("/0/private/OpenOrders", &[])?;
        let open = result
            .get("open")
            .and_then(serde_json::Value::as_object)
            .ok_or_else(|| Error::Deserialization("missing open orders".to_string()))?;
        let want = symbol.map(Self::wire_symbol);
        open.iter()
            .filter(|(_, order)| match &want {
                None => true,
                Some(w) => descr_pair(order) == *w,
            })
            .map(|(id, order)| {
                let sym = symbol
                    .cloned()
                    .unwrap_or_else(|| unmap_pair(&descr_pair(order)));
                order_from_value(sym, id, order)
            })
            .collect()
    }

    /// Account balances (free/locked from `BalanceEx`).
    ///
    /// # Errors
    /// Returns an [`Error`] if credentials are missing or the request fails.
    pub fn balances(&self) -> Result<Vec<Balance>> {
        if self.is_futures() {
            return self.futures_balances();
        }
        let result = self.signed_post("/0/private/BalanceEx", &[])?;
        let map = result
            .as_object()
            .ok_or_else(|| Error::Deserialization("missing balances".to_string()))?;
        let mut balances: Vec<Balance> = map
            .iter()
            .map(|(asset, detail)| {
                let balance = decimal_field(detail, "balance").unwrap_or(Decimal::ZERO);
                let hold = decimal_field(detail, "hold_trade").unwrap_or(Decimal::ZERO);
                Balance {
                    asset: asset.clone(),
                    free: balance - hold,
                    locked: hold,
                }
            })
            .collect();
        balances.sort_by(|a, b| a.asset.cmp(&b.asset));
        Ok(balances)
    }

    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))?;
        unwrap_result(&response.body).map_err(|e| {
            super::attribute_to_http_status(&response, e).with_retry_after(response.retry_after())
        })
    }

    /// Sign a private POST: `API-Sign = base64(HMAC-SHA512(base64decode(secret),
    /// path ++ SHA256(nonce ++ postdata)))`, form-encoded body with the nonce.
    fn signed_post(&self, path: &str, params: &[(&str, String)]) -> Result<serde_json::Value> {
        let owned: Vec<(String, String)> = params
            .iter()
            .map(|(key, val)| ((*key).to_string(), val.clone()))
            .collect();
        self.signed_post_pairs(path, &owned)
    }

    /// Signed POST with owned form keys, for endpoints whose field names are built
    /// dynamically (e.g. `AddOrderBatch`'s `orders[i][…]` indexed array).
    fn signed_post_pairs(
        &self,
        path: &str,
        params: &[(String, String)],
    ) -> Result<serde_json::Value> {
        self.ensure_market_is_routed()?;
        let creds = self.credentials.as_ref().ok_or(Error::InvalidCredentials(
            "signed endpoint requires credentials",
        ))?;
        let nonce = self.next_nonce().to_string();
        let mut form = vec![format!("nonce={nonce}")];
        for (key, val) in params {
            form.push(format!("{key}={val}"));
        }
        let postdata = form.join("&");
        let mut message = path.as_bytes().to_vec();
        message.extend_from_slice(&sha256(format!("{nonce}{postdata}").as_bytes()));
        let signature = hmac_sha512_base64_with_b64_secret(&creds.api_secret, &message)?;
        let url = format!("{}{path}", self.rest_base);
        let request = HttpRequest::new(HttpMethod::Post, url)
            .with_header("API-Key", creds.api_key.clone())
            .with_header("API-Sign", signature)
            .with_header("Content-Type", "application/x-www-form-urlencoded")
            .with_body(postdata);
        let response = self.http.execute(&request)?;
        unwrap_result(&response.body).map_err(|e| {
            super::attribute_to_http_status(&response, e).with_retry_after(response.retry_after())
        })
    }

    /// Public Kraken Futures GET (no signing).
    fn futures_get(&self, path: &str, query: &str) -> Result<serde_json::Value> {
        self.ensure_market_is_routed()?;
        let url = if query.is_empty() {
            format!("{}{path}", self.rest_base)
        } else {
            format!("{}{path}?{query}", self.rest_base)
        };
        let response = self.http.execute(&HttpRequest::get(url))?;
        unwrap_futures(&response.body).map_err(|e| e.with_retry_after(response.retry_after()))
    }

    /// Signed Kraken Futures request. The signature is
    /// `Authent = base64(HMAC-SHA512(base64decode(secret), SHA256(postData ++
    /// nonce ++ endpointPath)))`, where `endpointPath` is the path **without** the
    /// `/derivatives` prefix. `postData` is the form body (empty for a plain GET).
    fn signed_futures(
        &self,
        method: HttpMethod,
        path: &str,
        params: &[(&str, String)],
    ) -> Result<serde_json::Value> {
        self.ensure_market_is_routed()?;
        let creds = self.credentials.as_ref().ok_or(Error::InvalidCredentials(
            "signed endpoint requires credentials",
        ))?;
        let nonce = self.next_nonce().to_string();
        let post_data = params
            .iter()
            .map(|(key, val)| format!("{key}={val}"))
            .collect::<Vec<_>>()
            .join("&");
        // The signed endpoint path drops the leading `/derivatives`.
        let endpoint_path = path.strip_prefix("/derivatives").unwrap_or(path);
        let concat = format!("{post_data}{nonce}{endpoint_path}");
        let message = sha256(concat.as_bytes());
        let signature = hmac_sha512_base64_with_b64_secret(&creds.api_secret, &message)?;
        let is_get = matches!(method, HttpMethod::Get);
        let url = if is_get && !post_data.is_empty() {
            format!("{}{path}?{post_data}", self.rest_base)
        } else {
            format!("{}{path}", self.rest_base)
        };
        let mut request = HttpRequest::new(method, url)
            .with_header("APIKey", creds.api_key.clone())
            .with_header("Nonce", nonce)
            .with_header("Authent", signature);
        if !is_get {
            request = request
                .with_header("Content-Type", "application/x-www-form-urlencoded")
                .with_body(post_data);
        }
        let response = self.http.execute(&request)?;
        unwrap_futures(&response.body).map_err(|e| e.with_retry_after(response.retry_after()))
    }

    fn futures_klines(&self, symbol: &Symbol, interval: &str) -> Result<Vec<Candle>> {
        // Charts live under a separate base path (no `/derivatives`).
        let path = format!(
            "/api/charts/v1/trade/{}/{}",
            Self::futures_symbol(symbol),
            map_futures_resolution(interval),
        );
        let value = self.futures_get(&path, "")?;
        let candles = value
            .get("candles")
            .and_then(serde_json::Value::as_array)
            .ok_or_else(|| Error::Deserialization("missing candles".to_string()))?;
        candles.iter().map(parse_futures_candle).collect()
    }

    /// Place a Kraken Futures order (`/derivatives/api/v3/sendorder`): `orderType`
    /// (`mkt`/`lmt`/`post`), `symbol`, `side`, `size`, optional `limitPrice`, and
    /// `reduceOnly`.
    fn place_futures_order(&self, request: &OrderRequest) -> Result<Order> {
        ensure_no_stp(request)?;
        // Kraken Futures carries post-only and IOC *inside* `orderType`, so the
        // two cannot both be spelled on one order, and there is no fill-or-kill
        // at all -- both are refused rather than dropped down to a plain limit.
        let order_type = match (request.order_type, request.time_in_force, request.post_only) {
            (_, TimeInForce::Fok, _) => {
                return Err(Error::unsupported_field(
                    "Kraken",
                    "a FOK time-in-force",
                    "Kraken Futures orderType is mkt, lmt, post or ioc",
                ))
            }
            (OrderType::Limit | OrderType::StopLimit, TimeInForce::Ioc, true) => {
                return Err(Error::unsupported_field(
                    "Kraken",
                    "post_only together with an IOC time-in-force",
                    "both are Kraken Futures order types and only one is sent",
                ))
            }
            // A trigger is its own order type here, so it is matched before
            // the plain forms. Falling through to `mkt` would send the order
            // with no trigger at all -- the stop-loss that executes at once.
            (OrderType::StopMarket | OrderType::StopLimit, _, _) => "stp",
            (OrderType::Market, _, _) => "mkt",
            (OrderType::Limit, TimeInForce::Ioc, false) => "ioc",
            (OrderType::Limit, TimeInForce::Gtc, true) => "post",
            (OrderType::Limit, TimeInForce::Gtc, false) => "lmt",
        };
        let mut params: Vec<(&str, String)> = vec![
            ("orderType", order_type.to_string()),
            ("symbol", Self::futures_symbol(&request.symbol)),
            ("side", side_str(request.side).to_string()),
            ("size", format_decimal(request.quantity)),
            ("reduceOnly", request.reduce_only.to_string()),
        ];
        if request.order_type.is_trigger() {
            let stop = request
                .stop_price
                .ok_or(Error::InvalidOrder("a trigger order requires a stop price"))?;
            params.push(("stopPrice", format_decimal(stop)));
            // Which price arms the stop. `mark` is the venue's default and the
            // one a position is liquidated against, so it is the one a stop is
            // usually meant to watch; naming it is better than inheriting a
            // default that may change.
            params.push(("triggerSignal", "mark".to_string()));
        }
        if let Some(price) = request.price {
            params.push(("limitPrice", format_decimal(price)));
        }
        if let Some(id) = &request.client_order_id {
            params.push(("cliOrdId", id.clone()));
        }
        let value =
            self.signed_futures(HttpMethod::Post, "/derivatives/api/v3/sendorder", &params)?;
        let send_status = value
            .get("sendStatus")
            .ok_or_else(|| Error::Deserialization("missing sendStatus".to_string()))?;
        let order_id = send_status
            .get("order_id")
            .and_then(serde_json::Value::as_str)
            .ok_or_else(|| Error::Deserialization("missing order_id".to_string()))?;
        Ok(Order {
            id: order_id.to_string(),
            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,
        })
    }

    /// Flex (multi-collateral) account balances
    /// (`/derivatives/api/v3/accounts`).
    fn futures_balances(&self) -> Result<Vec<Balance>> {
        let value = self.signed_futures(HttpMethod::Get, "/derivatives/api/v3/accounts", &[])?;
        let currencies = value
            .get("accounts")
            .and_then(|a| a.get("flex"))
            .and_then(|f| f.get("currencies"))
            .and_then(serde_json::Value::as_object)
            .ok_or_else(|| Error::Deserialization("missing flex currencies".to_string()))?;
        let mut balances: Vec<Balance> = currencies
            .iter()
            .map(|(asset, detail)| {
                let quantity = decimal_field(detail, "quantity").unwrap_or(Decimal::ZERO);
                let available = decimal_field(detail, "available").unwrap_or(quantity);
                Balance {
                    asset: asset.clone(),
                    free: available,
                    locked: (quantity - available).max(Decimal::ZERO),
                }
            })
            .collect();
        balances.sort_by(|a, b| a.asset.cmp(&b.asset));
        Ok(balances)
    }

    /// Open positions on the futures account
    /// (`/derivatives/api/v3/openpositions`).
    ///
    /// # 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_futures(HttpMethod::Get, "/derivatives/api/v3/openpositions", &[])?;
        let list = value
            .get("openPositions")
            .and_then(serde_json::Value::as_array)
            .ok_or_else(|| Error::Deserialization("missing openPositions".to_string()))?;
        let wanted = symbol.map(Self::futures_symbol);
        list.iter()
            .filter(|p| {
                wanted.as_ref().is_none_or(|w| {
                    p.get("symbol")
                        .and_then(serde_json::Value::as_str)
                        .is_some_and(|s| s.eq_ignore_ascii_case(w))
                })
            })
            .map(|p| self.parse_futures_position(p))
            .collect()
    }

    /// Set the leverage preference for `symbol`
    /// (`/derivatives/api/v3/leveragepreferences`, `maxLeverage`).
    ///
    /// # Errors
    /// Returns an [`Error`] if the request is rejected or credentials are missing.
    pub fn set_leverage(&self, symbol: &Symbol, leverage: u32) -> Result<()> {
        let lever = leverage.max(1);
        self.leverage.set(lever);
        let params = vec![
            ("symbol", Self::futures_symbol(symbol)),
            ("maxLeverage", lever.to_string()),
        ];
        self.signed_futures(
            HttpMethod::Put,
            "/derivatives/api/v3/leveragepreferences",
            &params,
        )?;
        Ok(())
    }

    /// Set the margin mode for `symbol`.
    ///
    /// Kraken Futures uses a **flex (multi-collateral, cross) account**, so
    /// `Cross` is a no-op success; there is no per-symbol switch to isolated
    /// within the flex account, so `Isolated` returns an [`Error::Exchange`].
    ///
    /// # Errors
    /// Returns [`Error::Exchange`] when `Isolated` is requested.
    pub fn set_margin_mode(&self, _symbol: &Symbol, mode: MarginMode) -> Result<()> {
        match mode {
            MarginMode::Cross => Ok(()),
            MarginMode::Isolated => Err(Error::Exchange {
                code: "unsupported".to_string(),
                message: "Kraken Futures flex account is cross-margin; isolated is \
                          not switchable per-symbol"
                    .to_string(),
            }),
        }
    }

    /// 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> {
        self.ensure_one_way()?;
        let want = Self::futures_symbol(symbol);
        let position = self
            .positions(Some(symbol))?
            .into_iter()
            .find(|p| Self::futures_symbol(&p.symbol).eq_ignore_ascii_case(&want))
            .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 parse_futures_position(&self, data: &serde_json::Value) -> Result<Position> {
        let side_raw = data
            .get("side")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("");
        let side = match side_raw {
            "long" => PositionSide::Long,
            "short" => PositionSide::Short,
            other => {
                return Err(Error::Deserialization(format!(
                    "unknown position side {other:?}"
                )))
            }
        };
        let contract = data
            .get("symbol")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("");
        Ok(Position {
            symbol: symbol_from_futures(contract),
            side,
            quantity: decimal_field(data, "size").unwrap_or(Decimal::ZERO),
            entry_price: decimal_field(data, "price").unwrap_or(Decimal::ZERO),
            // `openpositions` omits mark price and unrealized PnL; leverage is a
            // preference, not reported per-position, so the recorded value is used.
            mark_price: Decimal::ZERO,
            leverage: Decimal::from(self.leverage.get()),
            unrealized_pnl: Decimal::ZERO,
            margin_mode: MarginMode::Cross,
        })
    }
}

fn kraken_asset(asset: &str) -> String {
    match asset {
        "BTC" => "XBT".to_string(),
        other => other.to_string(),
    }
}

fn unmap_pair(pair: &str) -> Symbol {
    // Best-effort inverse of `wire_symbol` for the common quotes.
    for quote in ["USDT", "USDC", "EUR", "USD", "XBT", "ETH"] {
        if let Some(base) = pair.strip_suffix(quote) {
            if !base.is_empty() {
                let base = if base == "XBT" { "BTC" } else { base };
                return Symbol::new(base, quote);
            }
        }
    }
    Symbol::new(pair, "")
}

fn map_interval(interval: &str) -> &'static str {
    match interval {
        "1m" => "1",
        "5m" => "5",
        "15m" => "15",
        "30m" => "30",
        "4h" => "240",
        "1d" => "1440",
        "1w" => "10080",
        // Default (and "1h") map to 60-minute candles.
        _ => "60",
    }
}

/// The single value of a one-entry result object (Kraken keys it by pair name).
fn single_result(result: &serde_json::Value) -> Result<&serde_json::Value> {
    result
        .as_object()
        .and_then(|obj| obj.values().next())
        .ok_or_else(|| Error::Deserialization("empty result".to_string()))
}

fn unwrap_result(body: &str) -> Result<serde_json::Value> {
    let value: serde_json::Value =
        serde_json::from_str(body).map_err(|e| Error::Deserialization(e.to_string()))?;
    if let Some(errors) = value.get("error").and_then(serde_json::Value::as_array) {
        if let Some(first) = errors.first().and_then(serde_json::Value::as_str) {
            return Err(map_error(first));
        }
    }
    value
        .get("result")
        .cloned()
        .ok_or_else(|| Error::Deserialization("missing result".to_string()))
}

/// Unwrap a Kraken Futures envelope: `{"result":"success", ...}` on success,
/// `{"result":"error","error":"..."}` on failure. The payload fields are
/// siblings of `result`, so the whole value is returned.
fn unwrap_futures(body: &str) -> Result<serde_json::Value> {
    let value: serde_json::Value =
        serde_json::from_str(body).map_err(|e| Error::Deserialization(e.to_string()))?;
    match value.get("result").and_then(serde_json::Value::as_str) {
        Some("error") => {
            let error = value
                .get("error")
                .and_then(serde_json::Value::as_str)
                .unwrap_or("unknown error");
            Err(map_futures_error(error))
        }
        _ => Ok(value),
    }
}

fn map_futures_error(error: &str) -> Error {
    match error {
        "insufficientFunds" | "insufficientAvailableFunds" => Error::InsufficientBalance,
        "apiLimitExceeded" => Error::RateLimited { retry_after: None },
        "authenticationError" | "invalidAccount" => Error::Auth(error.to_string()),
        "invalidUnit" | "invalidArgument" | "marketSuspended" => {
            Error::InvalidSymbol(error.to_string())
        }
        "orderNotFound" | "notFound" => Error::NotFound(error.to_string()),
        other => Error::Exchange {
            code: "kraken-futures".to_string(),
            message: other.to_string(),
        },
    }
}

/// Kraken Futures resolution for a unified interval.
fn map_futures_resolution(interval: &str) -> &'static str {
    match interval {
        "1m" => "1m",
        "5m" => "5m",
        "15m" => "15m",
        "30m" => "30m",
        "4h" => "4h",
        "12h" => "12h",
        "1d" => "1d",
        "1w" => "1w",
        // Default (and "1h") map to the 1-hour resolution.
        _ => "1h",
    }
}

/// Kraken Futures order-book levels are `[price, size]` numeric arrays.
fn num_pair_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 = decimal_value(
                pair.first()
                    .ok_or_else(|| Error::Deserialization("depth price missing".to_string()))?,
            )?;
            let quantity =
                decimal_value(pair.get(1).ok_or_else(|| {
                    Error::Deserialization("depth quantity missing".to_string())
                })?)?;
            Ok(BookLevel { price, quantity })
        })
        .collect()
}

fn parse_futures_candle(row: &serde_json::Value) -> Result<Candle> {
    let ts = row
        .get("time")
        .and_then(serde_json::Value::as_i64)
        .ok_or_else(|| Error::Deserialization("candle time missing".to_string()))?;
    let f = |key: &str| -> Result<f64> {
        let field = row
            .get(key)
            .ok_or_else(|| Error::Deserialization(format!("candle {key} missing")))?;
        field
            .as_f64()
            .or_else(|| field.as_str().and_then(|s| s.parse().ok()))
            .ok_or_else(|| Error::Deserialization(format!("candle {key} not a number")))
    };
    Candle::new(
        f("open")?,
        f("high")?,
        f("low")?,
        f("close")?,
        f("volume")?,
        ts,
    )
    .map_err(|e| Error::Deserialization(e.to_string()))
}

/// Reconstruct a canonical [`Symbol`] from a Kraken Futures perpetual symbol
/// (`PF_XBTUSD` -> `BTC/USD`).
fn symbol_from_futures(contract: &str) -> Symbol {
    let core = contract
        .strip_prefix("PF_")
        .or_else(|| contract.strip_prefix("PI_"))
        .or_else(|| contract.strip_prefix("pf_"))
        .or_else(|| contract.strip_prefix("pi_"))
        .unwrap_or(contract)
        .to_uppercase();
    for quote in ["USDT", "USDC", "USD", "EUR"] {
        if let Some(base) = core.strip_suffix(quote) {
            if !base.is_empty() {
                let base = if base == "XBT" { "BTC" } else { base };
                return Symbol::new(base, quote);
            }
        }
    }
    Symbol::new(core, "")
}

/// Map a Kraken Futures order status string onto the unified status. Tolerant of
/// both the `orders/status` (`ENTERED_BOOK` / `FULLY_EXECUTED`) and `openorders`
/// (`untouched` / `partiallyFilled`) casings.
fn kraken_futures_status(raw: &str) -> OrderStatus {
    let s = raw.to_ascii_lowercase();
    if s.contains("cancel") || s.contains("expired") {
        OrderStatus::Canceled
    } else if s.contains("reject") {
        OrderStatus::Rejected
    } else if s.contains("partial") {
        OrderStatus::PartiallyFilled
    } else if s.contains("fully") || s.contains("filled") || s.contains("executed") {
        OrderStatus::Filled
    } else {
        OrderStatus::New
    }
}

fn kraken_futures_order_type(raw: &str) -> OrderType {
    let s = raw.to_ascii_lowercase();
    if s.contains("lmt") || s.contains("limit") || s.contains("post") {
        OrderType::Limit
    } else {
        OrderType::Market
    }
}

/// Parse a Kraken Futures order object. The `orders/status` endpoint nests the
/// detail under `order`; `openorders` is flat and reports `filledSize` /
/// `unfilledSize` instead of a total `quantity`.
fn kraken_futures_order(symbol: Symbol, id: &str, obj: &serde_json::Value) -> Result<Order> {
    let detail = obj.get("order").unwrap_or(obj);
    let side = detail
        .get("side")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("");
    let order_type = detail
        .get("orderType")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("");
    let status = obj
        .get("status")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("");
    let filled = decimal_field(detail, "filled")
        .or_else(|_| decimal_field(detail, "filledSize"))
        .unwrap_or(Decimal::ZERO);
    let quantity = decimal_field(detail, "quantity").unwrap_or_else(|_| {
        filled + decimal_field(detail, "unfilledSize").unwrap_or(Decimal::ZERO)
    });
    let price = decimal_field(detail, "limitPrice")
        .ok()
        .filter(|d| *d > Decimal::ZERO);
    let client_order_id = detail
        .get("cliOrdId")
        .and_then(serde_json::Value::as_str)
        .filter(|s| !s.is_empty())
        .map(str::to_string);
    Ok(Order {
        id: id.to_string(),
        client_order_id,
        symbol,
        side: parse_side(side)?,
        order_type: kraken_futures_order_type(order_type),
        status: kraken_futures_status(status),
        quantity,
        filled_quantity: filled,
        price,
        average_price: None,
    })
}

/// Map a Kraken Futures instrument (`PI_XBTUSD`, `PF_XBTUSD`, `FI_XBTUSD_240628`)
/// to a [`Symbol`]: drop the product prefix and any dated suffix, then invert the
/// asset aliasing (`XBT` → `BTC`).
fn futures_instrument_symbol(instrument: &str) -> Symbol {
    let core = instrument
        .split_once('_')
        .map_or(instrument, |(_, rest)| rest);
    let core = core.split('_').next().unwrap_or(core);
    unmap_pair(core)
}

/// Parse one order object from a Kraken Futures `open_orders` feed frame. The
/// numeric `direction` is `0` = buy / `1` = sell; `qty`/`filled`/`limit_price`
/// are JSON numbers.
fn futures_feed_order(order: &serde_json::Value, status: OrderStatus) -> Result<Order> {
    let direction = order.get("direction").and_then(serde_json::Value::as_i64);
    let side = match direction {
        Some(0) => OrderSide::Buy,
        Some(1) => OrderSide::Sell,
        _ => {
            return Err(Error::Deserialization(
                "missing order direction".to_string(),
            ))
        }
    };
    let order_type = order
        .get("type")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("");
    let quantity = decimal_field(order, "qty").unwrap_or(Decimal::ZERO);
    let filled = decimal_field(order, "filled").unwrap_or(Decimal::ZERO);
    let price = decimal_field(order, "limit_price")
        .ok()
        .filter(|d| *d > Decimal::ZERO);
    let instrument = order
        .get("instrument")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("");
    let client_order_id = order
        .get("cli_ord_id")
        .and_then(serde_json::Value::as_str)
        .filter(|s| !s.is_empty())
        .map(str::to_string);
    Ok(Order {
        id: order
            .get("order_id")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("")
            .to_string(),
        client_order_id,
        symbol: futures_instrument_symbol(instrument),
        side,
        order_type: kraken_futures_order_type(order_type),
        status,
        quantity,
        filled_quantity: filled,
        price,
        average_price: None,
    })
}

/// Parse a Kraken Futures private feed frame (`open_orders` / `balances`) into
/// account events. Subscription acks, heartbeats and pure cancel-only frames
/// (which carry no order fields) yield no events.
fn parse_futures_private(frame: &str) -> Result<Vec<Event>> {
    let value: serde_json::Value =
        serde_json::from_str(frame).map_err(|e| Error::Deserialization(e.to_string()))?;
    let feed = value
        .get("feed")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("");
    match feed {
        "open_orders_snapshot" => value
            .get("orders")
            .and_then(serde_json::Value::as_array)
            .map_or_else(
                || Ok(Vec::new()),
                |orders| {
                    orders
                        .iter()
                        .map(|order| {
                            Ok(Event::OrderUpdate(futures_feed_order(
                                order,
                                OrderStatus::New,
                            )?))
                        })
                        .collect::<Result<Vec<_>>>()
                },
            ),
        "open_orders" => {
            let Some(order) = value.get("order") else {
                return Ok(Vec::new());
            };
            let status =
                if value.get("is_cancel").and_then(serde_json::Value::as_bool) == Some(true) {
                    OrderStatus::Canceled
                } else {
                    OrderStatus::New
                };
            Ok(vec![Event::OrderUpdate(futures_feed_order(order, status)?)])
        }
        "balances_snapshot" | "balances" => {
            let Some(holding) = value.get("holding").and_then(serde_json::Value::as_object) else {
                return Ok(Vec::new());
            };
            let balances = holding
                .iter()
                .map(|(asset, amount)| {
                    Ok(Balance {
                        asset: asset.clone(),
                        free: decimal_value(amount)?,
                        locked: Decimal::ZERO,
                    })
                })
                .collect::<Result<Vec<_>>>()?;
            Ok(vec![Event::BalanceUpdate(balances)])
        }
        _ => Ok(Vec::new()),
    }
}

fn map_error(error: &str) -> Error {
    if error.contains("Insufficient funds") {
        Error::InsufficientBalance
    } else if error.contains("Invalid key")
        || error.contains("Invalid signature")
        || error.contains("Permission denied")
        || error.contains("Invalid nonce")
    {
        Error::Auth(error.to_string())
    } else if error.contains("Rate limit") {
        Error::RateLimited { retry_after: None }
    } else if error.contains("Unknown order") {
        Error::NotFound(error.to_string())
    } else if error.contains("Unknown asset pair") {
        Error::InvalidSymbol(error.to_string())
    } else {
        Error::Exchange {
            code: "kraken".to_string(),
            message: error.to_string(),
        }
    }
}

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

/// Kraken's order APIs -- spot `AddOrder`, the v2 WebSocket `add_order` and
/// Kraken Futures `sendorder` alike -- carry no self-trade-prevention field, so
/// a policy the caller set cannot be honoured and the order is refused rather
/// than placed without the protection it was given.
fn ensure_no_stp(request: &OrderRequest) -> Result<()> {
    if request.stp == SelfTradePrevention::None {
        return Ok(());
    }
    Err(Error::unsupported_field(
        "Kraken",
        "a self-trade-prevention policy",
        "Kraken's order APIs carry no STP field",
    ))
}

/// The Kraken `timeinforce` value for a spot order. Kraken spells GTC, IOC and
/// GTD; it has **no** fill-or-kill, so a FOK is refused rather than sent as the
/// resting GTC it is not. `Gtc` is Kraken's default and is left off the wire.
fn tif_str(tif: TimeInForce) -> Result<Option<&'static str>> {
    match tif {
        TimeInForce::Gtc => Ok(None),
        TimeInForce::Ioc => Ok(Some("IOC")),
        TimeInForce::Fok => Err(Error::unsupported_field(
            "Kraken",
            "a FOK time-in-force",
            "Kraken's timeinforce is GTC, IOC or GTD",
        )),
    }
}

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

/// The `ordertype` for a spot order, including its trigger forms.
///
/// Kraken names the trigger types `stop-loss` and `stop-loss-limit`, and
/// **moves what `price` means**: on a trigger order `price` is the trigger and
/// `price2` is the limit, where on a plain limit `price` is the limit. Sending
/// a stop-limit's limit price as `price` would place the trigger at the limit --
/// an order that fires at the wrong level, in the direction that hurts.
fn spot_order_type(order_type: OrderType) -> &'static str {
    match order_type {
        OrderType::Market => "market",
        OrderType::Limit => "limit",
        OrderType::StopMarket => "stop-loss",
        OrderType::StopLimit => "stop-loss-limit",
    }
}

/// Build one `place_batch` outcome from an `AddOrderBatch` per-order entry: a
/// `txid` marks acceptance (mapped to a fresh [`OrderStatus::New`] order carrying
/// the request's own fields), an `error` marks a per-order rejection.
fn kraken_batch_order(request: &OrderRequest, entry: &serde_json::Value) -> Result<Order> {
    if let Some(error) = entry.get("error").and_then(serde_json::Value::as_str) {
        if !error.is_empty() {
            return Err(map_error(error));
        }
    }
    let txid = entry
        .get("txid")
        .and_then(|value| {
            value.as_str().map(str::to_string).or_else(|| {
                value
                    .as_array()
                    .and_then(|ids| ids.first())
                    .and_then(serde_json::Value::as_str)
                    .map(str::to_string)
            })
        })
        .ok_or_else(|| Error::Deserialization("missing txid in AddOrderBatch entry".to_string()))?;
    Ok(Order {
        id: txid,
        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,
    })
}

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

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

fn parse_status(raw: &str) -> Result<OrderStatus> {
    match raw {
        "pending" | "open" => Ok(OrderStatus::New),
        "closed" => Ok(OrderStatus::Filled),
        "canceled" => Ok(OrderStatus::Canceled),
        "expired" => Ok(OrderStatus::Expired),
        other => Err(Error::Deserialization(format!("unknown status {other:?}"))),
    }
}

fn nonzero(value: Decimal) -> Option<Decimal> {
    (value > Decimal::ZERO).then_some(value)
}

/// Render a [`Decimal`] as a JSON number, preserving its exact digits. Kraken's
/// v2 order API expects `order_qty` / `limit_price` as numbers.
fn json_number(value: Decimal) -> serde_json::Value {
    serde_json::from_str(&value.to_string())
        .unwrap_or_else(|_| serde_json::json!(value.to_string()))
}

fn decimal_value(field: &serde_json::Value) -> Result<Decimal> {
    match field {
        serde_json::Value::String(s) => parse_decimal(s),
        serde_json::Value::Number(n) => parse_decimal(&n.to_string()),
        other => Err(Error::Deserialization(format!("not a number: {other}"))),
    }
}

fn decimal_field(value: &serde_json::Value, key: &str) -> Result<Decimal> {
    let field = value
        .get(key)
        .ok_or_else(|| Error::Deserialization(format!("missing field {key:?}")))?;
    decimal_value(field)
}

/// Read `value[key][index]` as a decimal (Kraken ticker fields are arrays).
fn decimal_at(value: &serde_json::Value, key: &str, index: usize) -> Result<Decimal> {
    let field = value
        .get(key)
        .and_then(serde_json::Value::as_array)
        .and_then(|a| a.get(index))
        .ok_or_else(|| Error::Deserialization(format!("missing {key}[{index}]")))?;
    decimal_value(field)
}

/// REST depth levels: `[price, volume, timestamp]` string arrays.
fn rest_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 = decimal_value(
                pair.first()
                    .ok_or_else(|| Error::Deserialization("depth price missing".to_string()))?,
            )?;
            let quantity =
                decimal_value(pair.get(1).ok_or_else(|| {
                    Error::Deserialization("depth quantity missing".to_string())
                })?)?;
            Ok(BookLevel { price, quantity })
        })
        .collect()
}

/// v2 WebSocket book levels: `{price, qty}` objects.
fn 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| {
            Ok(BookLevel {
                price: decimal_field(level, "price")?,
                quantity: decimal_field(level, "qty")?,
            })
        })
        .collect()
}

fn parse_kline_row(row: &serde_json::Value) -> Result<Candle> {
    // Kraken OHLC: [time, open, high, low, close, vwap, volume, count].
    let arr = row
        .as_array()
        .ok_or_else(|| Error::Deserialization("kline row not an array".to_string()))?;
    if arr.len() < 7 {
        return Err(Error::Deserialization("kline row too short".to_string()));
    }
    let ts = arr[0]
        .as_i64()
        .ok_or_else(|| Error::Deserialization("kline time not an integer".to_string()))?;
    let f = |i: usize| -> Result<f64> {
        let field = &arr[i];
        field
            .as_f64()
            .or_else(|| field.as_str().and_then(|s| s.parse().ok()))
            .ok_or_else(|| Error::Deserialization("kline field not a number".to_string()))
    };
    Candle::new(f(1)?, f(2)?, f(3)?, f(4)?, f(6)?, ts)
        .map_err(|e| Error::Deserialization(e.to_string()))
}

fn descr_pair(order: &serde_json::Value) -> String {
    order
        .get("descr")
        .and_then(|d| d.get("pair"))
        .and_then(serde_json::Value::as_str)
        .unwrap_or("")
        .to_string()
}

fn order_from_value(symbol: Symbol, id: &str, order: &serde_json::Value) -> Result<Order> {
    let descr = order.get("descr");
    let side = descr
        .and_then(|d| d.get("type"))
        .and_then(serde_json::Value::as_str)
        .unwrap_or("");
    let ordertype = descr
        .and_then(|d| d.get("ordertype"))
        .and_then(serde_json::Value::as_str)
        .unwrap_or("");
    let status = order
        .get("status")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("");
    let limit_price = descr
        .and_then(|d| d.get("price"))
        .map(decimal_value)
        .transpose()?
        .unwrap_or(Decimal::ZERO);
    Ok(Order {
        id: id.to_string(),
        client_order_id: order
            .get("cl_ord_id")
            .and_then(serde_json::Value::as_str)
            .filter(|s| !s.is_empty())
            .map(str::to_string),
        symbol,
        side: parse_side(side)?,
        order_type: parse_order_type(ordertype)?,
        status: parse_status(status)?,
        quantity: decimal_field(order, "vol")?,
        filled_quantity: decimal_field(order, "vol_exec").unwrap_or(Decimal::ZERO),
        price: nonzero(limit_price),
        average_price: decimal_field(order, "price").ok().and_then(nonzero),
    })
}

/// The Kraken Futures WebSocket URL.
const FUTURES_WS_URL: &str = "wss://futures.kraken.com/ws/v1";

/// A number field from a futures frame.
///
/// Kraken Futures sends prices and sizes as JSON *numbers*, where the spot v2
/// socket sends strings. Going through the string form keeps the decimal exact:
/// parsing `81234.0` as `f64` and converting would introduce the binary
/// rounding the order layer exists to avoid.
fn futures_decimal(value: &serde_json::Value, key: &str) -> Option<Decimal> {
    let raw = value.get(key)?;
    if let Some(text) = raw.as_str() {
        return parse_decimal(text).ok();
    }
    parse_decimal(&raw.as_number()?.to_string()).ok()
}

fn futures_levels(value: &serde_json::Value, key: &str) -> Vec<BookLevel> {
    value
        .get(key)
        .and_then(serde_json::Value::as_array)
        .map(|rows| {
            rows.iter()
                .filter_map(|row| {
                    Some(BookLevel {
                        price: futures_decimal(row, "price")?,
                        quantity: futures_decimal(row, "qty")?,
                    })
                })
                .collect()
        })
        .unwrap_or_default()
}

/// One trade frame, or one entry of a `trade_snapshot`.
fn futures_trade(value: &serde_json::Value, symbol: &Symbol) -> Option<Event> {
    Some(Event::Trade(TradePrint {
        symbol: symbol.clone(),
        price: futures_decimal(value, "price")?,
        quantity: futures_decimal(value, "qty")?,
        aggressor: parse_side(value.get("side")?.as_str()?).ok()?,
        timestamp: value
            .get("time")
            .and_then(serde_json::Value::as_i64)
            .unwrap_or(0),
    }))
}

/// Turn a Kraken Futures frame into events.
///
/// The feeds are `trade` / `trade_snapshot`, `book` / `book_snapshot` and
/// `ticker`. A frame for a product that was never subscribed to is dropped: one
/// connection carries every subscription, and a caller watching BTC should not
/// be handed another market's book.
fn parse_futures_frame(
    feed: &str,
    value: &serde_json::Value,
    resolve: &impl Fn(&str) -> Option<Symbol>,
    subscribed: &impl Fn(&str, DerivativesChannel) -> bool,
) -> Vec<Event> {
    let Some(product) = value.get("product_id").and_then(serde_json::Value::as_str) else {
        return Vec::new(); // subscription ack, info frame
    };
    let Some(symbol) = resolve(product) else {
        return Vec::new();
    };

    match feed {
        "trade" => futures_trade(value, &symbol).into_iter().collect(),
        "trade_snapshot" => value
            .get("trades")
            .and_then(serde_json::Value::as_array)
            .map(|trades| {
                trades
                    .iter()
                    .filter_map(|trade| futures_trade(trade, &symbol))
                    .collect()
            })
            .unwrap_or_default(),
        "book_snapshot" => vec![Event::BookSnapshot(OrderBookSnapshot {
            symbol,
            last_update_id: value
                .get("seq")
                .and_then(serde_json::Value::as_u64)
                .unwrap_or(0),
            bids: futures_levels(value, "bids"),
            asks: futures_levels(value, "asks"),
            timestamp: value
                .get("timestamp")
                .and_then(serde_json::Value::as_i64)
                .unwrap_or(0),
        })],
        // An incremental book frame is one level, on one side, at its new size;
        // a size of zero removes it, which is what the delta type already means.
        "book" => {
            let (Some(price), Some(quantity)) = (
                futures_decimal(value, "price"),
                futures_decimal(value, "qty"),
            ) else {
                return Vec::new();
            };
            let level = vec![BookLevel { price, quantity }];
            let (bids, asks) = match value.get("side").and_then(serde_json::Value::as_str) {
                Some("buy") => (level, Vec::new()),
                Some("sell") => (Vec::new(), level),
                _ => return Vec::new(),
            };
            let seq = value
                .get("seq")
                .and_then(serde_json::Value::as_u64)
                .unwrap_or(0);
            vec![Event::BookDelta(BookDelta {
                symbol,
                first_update_id: seq,
                final_update_id: seq,
                bids,
                asks,
                timestamp: value
                    .get("timestamp")
                    .and_then(serde_json::Value::as_i64)
                    .unwrap_or(0),
            })]
        }
        "ticker" => {
            let timestamp = value
                .get("time")
                .and_then(serde_json::Value::as_i64)
                .unwrap_or(0);
            let mut out = Vec::new();
            if let Some(last) = futures_decimal(value, "last") {
                out.push(Event::Ticker(Ticker {
                    symbol: symbol.clone(),
                    last,
                    bid: futures_decimal(value, "bid").unwrap_or_default(),
                    ask: futures_decimal(value, "ask").unwrap_or_default(),
                    volume: futures_decimal(value, "volume").unwrap_or_default(),
                    timestamp,
                }));
            }
            let mark = futures_decimal(value, "markPrice");
            if subscribed(product, DerivativesChannel::Funding) {
                // `relative_funding_rate` is the proportion charged for the
                // interval. `funding_rate` beside it is that proportion times
                // the index -- an absolute amount per contract -- and reporting
                // it as a rate would be wrong by four orders of magnitude.
                if let (Some(rate), Some(mark_price)) =
                    (futures_decimal(value, "relative_funding_rate"), mark)
                {
                    out.push(Event::Derivatives(DerivativesFeed::Funding(FundingRate {
                        symbol: symbol.clone(),
                        rate,
                        mark_price,
                        timestamp,
                    })));
                }
            }
            if subscribed(product, DerivativesChannel::MarkIndex) {
                if let (Some(mark_price), Some(index_price)) =
                    (mark, futures_decimal(value, "index"))
                {
                    out.push(Event::Derivatives(DerivativesFeed::MarkIndex(MarkIndex {
                        symbol,
                        mark_price,
                        index_price,
                        timestamp,
                    })));
                }
            }
            out
        }
        _ => Vec::new(),
    }
}

fn parse_ws_message(
    text: &str,
    resolve: &impl Fn(&str) -> Option<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 let Some(feed) = value.get("feed").and_then(serde_json::Value::as_str) {
        return Ok(parse_futures_frame(feed, &value, resolve, subscribed));
    }
    let Some(channel) = value.get("channel").and_then(serde_json::Value::as_str) else {
        return Ok(Vec::new()); // status/heartbeat/ack
    };
    let msg_type = value.get("type").and_then(serde_json::Value::as_str);
    let empty = Vec::new();
    let data = value
        .get("data")
        .and_then(serde_json::Value::as_array)
        .unwrap_or(&empty);

    match channel {
        "trade" => data
            .iter()
            .map(|t| {
                Ok(Event::Trade(TradePrint {
                    symbol: resolve_ws_symbol(t)?,
                    price: decimal_field(t, "price")?,
                    quantity: decimal_field(t, "qty")?,
                    aggressor: parse_side(
                        t.get("side")
                            .and_then(serde_json::Value::as_str)
                            .unwrap_or(""),
                    )?,
                    timestamp: 0,
                }))
            })
            .collect(),
        "ticker" => data
            .iter()
            .map(|t| {
                Ok(Event::Ticker(Ticker {
                    symbol: resolve_ws_symbol(t)?,
                    last: decimal_field(t, "last")?,
                    bid: decimal_field(t, "bid").unwrap_or(Decimal::ZERO),
                    ask: decimal_field(t, "ask").unwrap_or(Decimal::ZERO),
                    volume: decimal_field(t, "volume").unwrap_or(Decimal::ZERO),
                    // Kraken's v2 ticker payload carries no timestamp.
                    timestamp: 0,
                }))
            })
            .collect(),
        "book" => data
            .iter()
            .map(|b| {
                let symbol = resolve_ws_symbol(b)?;
                let bids = ws_levels(b.get("bids"))?;
                let asks = ws_levels(b.get("asks"))?;
                if msg_type == Some("snapshot") {
                    Ok(Event::BookSnapshot(OrderBookSnapshot {
                        symbol,
                        last_update_id: 0,
                        bids,
                        asks,
                        timestamp: 0,
                    }))
                } else {
                    Ok(Event::BookDelta(BookDelta {
                        symbol,
                        first_update_id: 0,
                        final_update_id: 0,
                        bids,
                        asks,
                        timestamp: 0,
                    }))
                }
            })
            .collect(),
        // Private order-execution channel. An order update is emitted only when
        // the frame carries the order's static fields (the snapshot and full
        // new/amended updates); pure fill-delta frames that omit side/order_type
        // are not surfaced as standalone updates.
        "executions" => {
            let mut out = Vec::new();
            for exec in data {
                let (Some(side), Some(order_type)) = (
                    exec.get("side").and_then(serde_json::Value::as_str),
                    exec.get("order_type").and_then(serde_json::Value::as_str),
                ) else {
                    continue;
                };
                out.push(Event::OrderUpdate(ws_exec_order(exec, side, order_type)?));
            }
            Ok(out)
        }
        // Private balances channel. The v2 frame reports each asset's wallet
        // balance; a per-hold breakdown lives under `wallets` and is not surfaced,
        // so the locked amount is reported as zero.
        "balances" => {
            let balances = data
                .iter()
                .map(|entry| {
                    Ok(Balance {
                        asset: entry
                            .get("asset")
                            .and_then(serde_json::Value::as_str)
                            .ok_or_else(|| {
                                Error::Deserialization("missing balance asset".to_string())
                            })?
                            .to_string(),
                        free: decimal_field(entry, "balance")?,
                        locked: Decimal::ZERO,
                    })
                })
                .collect::<Result<Vec<_>>>()?;
            Ok(vec![Event::BalanceUpdate(balances)])
        }
        _ => Ok(Vec::new()),
    }
}

/// Map a Kraken v2 `executions` order status to an [`OrderStatus`].
fn ws_exec_status(raw: &str) -> OrderStatus {
    match raw {
        "partially_filled" => OrderStatus::PartiallyFilled,
        "filled" => OrderStatus::Filled,
        "canceled" | "cancelled" => OrderStatus::Canceled,
        "expired" => OrderStatus::Expired,
        _ => OrderStatus::New, // new, pending_new, pending_cancel, ...
    }
}

/// Build an [`Order`] from a Kraken v2 `executions` frame that carries the
/// order's static fields.
fn ws_exec_order(exec: &serde_json::Value, side: &str, order_type: &str) -> Result<Order> {
    let id = exec
        .get("order_id")
        .and_then(serde_json::Value::as_str)
        .ok_or_else(|| Error::Deserialization("missing order_id".to_string()))?;
    let status = ws_exec_status(
        exec.get("order_status")
            .and_then(serde_json::Value::as_str)
            .unwrap_or("new"),
    );
    Ok(Order {
        id: id.to_string(),
        client_order_id: exec
            .get("cl_ord_id")
            .and_then(serde_json::Value::as_str)
            .filter(|s| !s.is_empty())
            .map(str::to_string),
        symbol: resolve_ws_symbol(exec)?,
        side: parse_side(side)?,
        order_type: parse_order_type(order_type)?,
        status,
        quantity: decimal_field(exec, "order_qty").unwrap_or(Decimal::ZERO),
        filled_quantity: decimal_field(exec, "cum_qty").unwrap_or(Decimal::ZERO),
        price: decimal_field(exec, "limit_price").ok().and_then(nonzero),
        average_price: decimal_field(exec, "avg_price").ok().and_then(nonzero),
    })
}

fn resolve_ws_symbol(data: &serde_json::Value) -> Result<Symbol> {
    let raw = data
        .get("symbol")
        .and_then(serde_json::Value::as_str)
        .ok_or_else(|| Error::Deserialization("missing ws symbol".to_string()))?;
    raw.parse()
        .map_err(|_| Error::Deserialization(format!("bad ws symbol {raw:?}")))
}

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

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

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

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

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

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

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

impl Kraken {
    /// Amend a resting spot order's price and/or volume in place
    /// (`/0/private/EditOrder`), then return the refreshed order (Kraken assigns a
    /// new txid on edit).
    ///
    /// # Errors
    /// Returns an [`Error`] if the order is unknown, the amend is rejected, or the
    /// client targets Kraken Futures (a separate product).
    pub fn amend_order(
        &self,
        symbol: &Symbol,
        order_id: &str,
        new_price: Option<Decimal>,
        new_quantity: Option<Decimal>,
    ) -> Result<Order> {
        if self.is_futures() {
            return Err(Error::Exchange {
                code: "unsupported".to_string(),
                message: "Kraken Futures edit is a separate endpoint".to_string(),
            });
        }
        let mut params: Vec<(&str, String)> = vec![
            ("txid", order_id.to_string()),
            ("pair", Self::wire_symbol(symbol)),
        ];
        if let Some(p) = new_price {
            params.push(("price", format_decimal(p)));
        }
        if let Some(q) = new_quantity {
            params.push(("volume", format_decimal(q)));
        }
        let result = self.signed_post("/0/private/EditOrder", &params)?;
        let new_txid = result
            .get("txid")
            .and_then(serde_json::Value::as_str)
            .ok_or_else(|| Error::Deserialization("missing txid".to_string()))?
            .to_string();
        self.query_order(symbol, &new_txid)
    }

    /// Place several orders in one `AddOrderBatch` request. Kraken batches share a
    /// single `pair`, so the first order's symbol sets the pair for the batch; each
    /// order contributes its own indexed `orders[i][…]` fields. The per-order
    /// results are returned individually, so a partially-accepted batch keeps the
    /// successes.
    ///
    /// # Errors
    /// Returns an [`Error`] if any order is invalid, credentials are missing, or
    /// the request itself fails (a per-order rejection is carried in its own
    /// [`Result`], not the outer one).
    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("Kraken"));
        }
        for request in requests {
            self.ensure_reduce_only_is_reducible(request)?;
        }
        self.ensure_one_way()?;
        if requests.is_empty() {
            return Ok(Vec::new());
        }
        for request in requests {
            request.validate()?;
            ensure_no_stp(request)?;
        }
        // Kraken's `AddOrderBatch` carries one shared `pair` plus an indexed
        // `orders[i][…]` array — a form shape the flat helper cannot express.
        let mut params: Vec<(String, String)> =
            vec![("pair".to_string(), Self::wire_symbol(&requests[0].symbol))];
        for (index, request) in requests.iter().enumerate() {
            params.push((
                format!("orders[{index}][ordertype]"),
                order_type_str(request.order_type).to_string(),
            ));
            params.push((
                format!("orders[{index}][type]"),
                side_str(request.side).to_string(),
            ));
            params.push((
                format!("orders[{index}][volume]"),
                format_decimal(request.quantity),
            ));
            if let Some(price) = request.price {
                params.push((format!("orders[{index}][price]"), format_decimal(price)));
            }
            if request.post_only {
                params.push((format!("orders[{index}][oflags]"), "post".to_string()));
            }
            if let Some(tif) = tif_str(request.time_in_force)? {
                params.push((format!("orders[{index}][timeinforce]"), tif.to_string()));
            }
            if let Some(id) = &request.client_order_id {
                params.push((format!("orders[{index}][cl_ord_id]"), id.clone()));
            }
        }
        let result = self.signed_post_pairs("/0/private/AddOrderBatch", &params)?;
        let orders = result
            .get("orders")
            .and_then(serde_json::Value::as_array)
            .ok_or_else(|| Error::Deserialization("missing orders in AddOrderBatch".to_string()))?;
        Ok(requests
            .iter()
            .zip(orders)
            .map(|(request, entry)| kraken_batch_order(request, entry))
            .collect())
    }

    /// Cancel several orders by id. The spot API cancels the whole set in one
    /// `CancelOrderBatch` request; the futures client has no such endpoint and
    /// cancels sequentially.
    ///
    /// # Errors
    /// Returns an [`Error`] if the request fails.
    pub fn cancel_batch(&self, symbol: &Symbol, order_ids: &[String]) -> Result<()> {
        if order_ids.is_empty() {
            return Ok(());
        }
        if self.is_futures() {
            for id in order_ids {
                self.cancel_order(symbol, id)?;
            }
            return Ok(());
        }
        let params: Vec<(String, String)> = order_ids
            .iter()
            .map(|id| ("orders[]".to_string(), id.clone()))
            .collect();
        self.signed_post_pairs("/0/private/CancelOrderBatch", &params)?;
        Ok(())
    }
}

impl AdvancedOrders for Kraken {
    fn amend_order(
        &mut self,
        symbol: &Symbol,
        order_id: &str,
        new_price: Option<Decimal>,
        new_quantity: Option<Decimal>,
    ) -> Result<Order> {
        Kraken::amend_order(self, symbol, order_id, new_price, new_quantity)
    }
    fn place_batch(&mut self, requests: &[OrderRequest]) -> Result<Vec<Result<Order>>> {
        Kraken::place_batch(self, requests)
    }
    fn cancel_batch(&mut self, symbol: &Symbol, order_ids: &[String]) -> Result<()> {
        Kraken::cancel_batch(self, symbol, order_ids)
    }
    /// Kraken has no OCO order-list (it uses conditional-close 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: "Kraken has no OCO order-list; use conditional-close orders".to_string(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::transport::{HttpResponse, 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")
    }

    #[test]
    fn a_blocked_reply_is_reported_as_the_block_not_as_drift() {
        let (kraken, mock) = client();
        // What a geo-blocked runner receives: a status of its own and a body
        // that was never this venue's JSON. Read as an envelope it fails at
        // line 2 column 5, which says nothing about why it failed.
        mock.push_json(403, "{\n    error: 'unavailable in your region'\n}");
        let error = kraken.ticker(&symbol()).unwrap_err();
        let named = matches!(&error, Error::Exchange { code, .. } if code == "403");
        assert!(named, "a blocked reply must not be reported as drift");
    }

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

    fn signed_client(now_ms: i64) -> (Kraken, Arc<MockHttpTransport>) {
        let mock = Arc::new(MockHttpTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::Spot);
        // The secret is base64 (base64("secret") == "c2VjcmV0").
        let kraken = Kraken::with_credentials(
            Box::new(ArcTransport(Arc::clone(&mock))),
            &opts,
            Credentials::new("APIKEY", "c2VjcmV0"),
        )
        .with_clock(Box::new(move || now_ms));
        (kraken, mock)
    }

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

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

    /// Kraken's trigger types **move what `price` means**.
    ///
    /// On a plain limit, `price` is the limit. On `stop-loss-limit`, `price` is
    /// the *trigger* and `price2` is the limit. Sending the limit as `price`
    /// would arm the stop at the limit level -- an order that fires at the
    /// wrong price, in the direction that hurts.
    #[test]
    fn a_spot_stop_limit_sends_the_trigger_as_price_and_the_limit_as_price2() {
        let (kraken, mock) = signed_client(1000);
        mock.push_json(200, r#"{"error":[],"result":{"txid":["OABC-1"]}}"#);
        let request = OrderRequest {
            order_type: OrderType::StopLimit,
            stop_price: Some(dec!(19000)),
            ..OrderRequest::limit_sell(symbol(), dec!(1), dec!(18900))
        };
        Kraken::place_order(&kraken, &request).unwrap();

        let body = mock.recorded_requests()[0].body.clone().unwrap();
        assert!(body.contains("ordertype=stop-loss-limit"), "{body}");
        assert!(
            body.contains("price=19000"),
            "the trigger rides in `price`: {body}"
        );
        assert!(
            body.contains("price2=18900"),
            "the limit rides in `price2`: {body}"
        );
    }

    #[test]
    fn a_spot_stop_market_sends_only_the_trigger() {
        let (kraken, mock) = signed_client(1000);
        mock.push_json(200, r#"{"error":[],"result":{"txid":["OABC-1"]}}"#);
        let request = OrderRequest {
            order_type: OrderType::StopMarket,
            stop_price: Some(dec!(19000)),
            ..OrderRequest::market_sell(symbol(), dec!(1))
        };
        Kraken::place_order(&kraken, &request).unwrap();

        let body = mock.recorded_requests()[0].body.clone().unwrap();
        assert!(body.contains("ordertype=stop-loss"), "{body}");
        assert!(body.contains("price=19000"), "{body}");
        assert!(
            !body.contains("price2"),
            "a stop-market has no limit: {body}"
        );
    }

    /// A trigger order with no trigger price is refused before it is built.
    #[test]
    fn a_trigger_without_a_stop_price_is_refused() {
        let (kraken, mock) = signed_client(1000);
        let request = OrderRequest {
            order_type: OrderType::StopMarket,
            stop_price: None,
            ..OrderRequest::market_sell(symbol(), dec!(1))
        };
        assert!(Kraken::place_order(&kraken, &request).is_err());
        assert_eq!(mock.recorded_requests(), Vec::new());
    }

    /// The futures path must not flatten a trigger into a plain market order.
    ///
    /// Kraken Futures spells a trigger as its own `orderType`, so a `StopMarket`
    /// that fell through to the `mkt` arm would go out with no trigger at all --
    /// the stop-loss that executes at once, at the price it existed to protect
    /// against.
    #[test]
    fn a_futures_trigger_carries_its_stop_price_and_signal() {
        let (kraken, mock) = signed_futures_client(1000);
        mock.push_json(
            200,
            r#"{"result":"success","sendStatus":{"order_id":"1","status":"placed",
            "orderEvents":[]}}"#,
        );
        let request = OrderRequest {
            order_type: OrderType::StopMarket,
            stop_price: Some(dec!(19000)),
            ..OrderRequest::market_sell(symbol(), dec!(1))
        };
        let _ = Kraken::place_order(&kraken, &request);

        let sent = format!(
            "{} {}",
            mock.recorded_requests()[0].url,
            mock.recorded_requests()[0].body.clone().unwrap_or_default()
        );
        assert!(sent.contains("orderType=stp"), "{sent}");
        assert!(sent.contains("stopPrice=19000"), "{sent}");
        // Which price arms the stop: `mark` is the one a position is liquidated
        // against, and naming it beats inheriting a default that may change.
        assert!(sent.contains("triggerSignal=mark"), "{sent}");
        assert!(!sent.contains("orderType=mkt"), "flattened: {sent}");
    }
    fn hedged_futures_client(now_ms: i64) -> (Kraken, Arc<MockHttpTransport>) {
        let mock = Arc::new(MockHttpTransport::new());
        let mut opts = ExchangeOptions::mainnet(crate::MarketType::UsdMFutures);
        opts.position_mode = PositionMode::Hedge;
        let kraken = Kraken::with_credentials(
            Box::new(ArcTransport(Arc::clone(&mock))),
            &opts,
            Credentials::new("APIKEY", "c2VjcmV0"),
        )
        .with_clock(Box::new(move || now_ms));
        (kraken, mock)
    }

    #[test]
    fn hedge_mode_is_refused_rather_than_ignored() {
        // Kraken Futures is one-way only: there is no field on the order that
        // could carry a side. Placing it anyway would move the single net
        // position, which is what configuring hedge asked to avoid.
        let (hedged, _mock) = hedged_futures_client(1000);
        let err = hedged
            .place_order(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)))
            .unwrap_err();
        assert!(matches!(err, Error::Exchange { ref code, .. } if code == "unsupported"));

        // One-way on the same venue still places orders.
        let (one_way, _) = signed_futures_client(1000);
        let _ = one_way.place_order(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)));
    }

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

    #[test]
    fn the_websocket_path_refuses_post_only_rather_than_dropping_it() {
        // The REST spot body spells post-only as `oflags=post`; this frame is
        // the v2 protocol, which names every other field differently, so the
        // REST spelling proves nothing about it. Sending the order without the
        // flag would place a limit that may take liquidity.
        let (mut kraken, _http, _ws) = signed_ws_client(1000);
        let err = kraken
            .place_order_ws(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)).post_only())
            .unwrap_err();
        assert!(matches!(err, Error::Exchange { ref code, .. } if code == "unsupported"));

        // Without the flag the same client reaches the connection instead.
        let (mut plain, _http2, ws2) = signed_ws_client(1000);
        let _ = plain.place_order_ws(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)));
        let _ = ws2;
    }

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

    /// A futures client with a mock socket.
    fn futures_ws_client() -> (Kraken, Arc<MockWsTransport>) {
        let http = Arc::new(MockHttpTransport::new());
        let ws = Arc::new(MockWsTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::UsdMFutures);
        let kraken = Kraken::with_http(Box::new(ArcTransport(http)), &opts)
            .with_ws(Box::new(ArcWs(Arc::clone(&ws))));
        (kraken, ws)
    }

    /// The answers a venue gives on a bad day: a product that is not in the
    /// list, and a row without the figure. Neither had ever run.
    #[test]
    fn kraken_open_interest_reports_what_went_wrong() {
        let http = Arc::new(MockHttpTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::UsdMFutures);
        let kraken = Kraken::with_http(Box::new(ArcTransport(Arc::clone(&http))), &opts);

        http.push_json(200, r#"{"result":"success","tickers":[]}"#);
        assert!(matches!(
            Kraken::open_interest(&kraken, &symbol()),
            Err(Error::NotFound(_))
        ));

        http.push_json(
            200,
            r#"{"result":"success","tickers":[{"symbol":"PF_XBTUSD","last":1.0}]}"#,
        );
        assert!(matches!(
            Kraken::open_interest(&kraken, &symbol()),
            Err(Error::Deserialization(_))
        ));
    }

    /// Frames the futures parser cannot use are dropped, not guessed at.
    #[test]
    fn kraken_drops_futures_frames_it_cannot_read() {
        let (mut kraken, ws) = futures_ws_client();
        ws.push_connection(vec![
            // No product id: a subscription ack or an info frame.
            Ok(Some(r#"{"feed":"ticker_lite"}"#.to_string())),
            // A book delta with no side.
            Ok(Some(
                r#"{"feed":"book","product_id":"PF_XBTUSD","price":1.0,"qty":2.0}"#.to_string(),
            )),
            // A trade with no price.
            Ok(Some(
                r#"{"feed":"trade","product_id":"PF_XBTUSD","side":"buy","qty":1.0}"#.to_string(),
            )),
            // A ticker with no last price.
            Ok(Some(
                r#"{"feed":"ticker","product_id":"PF_XBTUSD"}"#.to_string(),
            )),
            // A feed this client does not subscribe to.
            Ok(Some(
                r#"{"feed":"heartbeat","product_id":"PF_XBTUSD"}"#.to_string(),
            )),
        ]);
        Kraken::subscribe_trades(&mut kraken, &symbol()).unwrap();

        assert_eq!(Kraken::poll_events(&mut kraken), Vec::new());
    }

    /// A trade snapshot replays several trades in one frame.
    #[test]
    fn kraken_parses_a_trade_snapshot() {
        let (mut kraken, ws) = futures_ws_client();
        ws.push_connection(vec![Ok(Some(
            r#"{"feed":"trade_snapshot","product_id":"PF_XBTUSD","trades":[
            {"feed":"trade","product_id":"PF_XBTUSD","side":"sell","time":1788462438934,
             "qty":0.0062,"price":81229.0},
            {"feed":"trade","product_id":"PF_XBTUSD","side":"buy","time":1788462438268,
             "qty":0.0002,"price":81231.0}]}"#
                .to_string(),
        ))]);
        Kraken::subscribe_trades(&mut kraken, &symbol()).unwrap();

        let events = Kraken::poll_events(&mut kraken);
        assert_eq!(events.len(), 2, "{events:?}");
    }

    /// One ticker frame answers both subscriptions, because Kraken reads the
    /// funding rate, the mark price and the index at one moment and sends them
    /// together.
    #[test]
    fn the_futures_ticker_answers_funding_and_mark_index() {
        let (mut kraken, ws) = futures_ws_client();
        ws.push_connection(vec![Ok(Some(
            r#"{"time":1788462442280,"product_id":"PF_XBTUSD","funding_rate":-0.6559492877,
            "relative_funding_rate":-8.071979166667e-6,"feed":"ticker","bid":81233.0,
            "ask":81234.0,"volume":8837.1259,"index":81231.21,"last":81229.0,
            "openInterest":1895.2046,"markPrice":81235.79652525584,"tag":"perpetual"}"#
                .to_string(),
        ))]);
        Kraken::subscribe_derivatives(&mut kraken, &symbol(), DerivativesChannel::Funding).unwrap();
        Kraken::subscribe_derivatives(&mut kraken, &symbol(), DerivativesChannel::MarkIndex)
            .unwrap();

        let events = Kraken::poll_events(&mut kraken);
        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]);
        };
        // The relative rate, not the absolute per-contract amount beside it:
        // reporting `funding_rate` as a rate would be off by four orders of
        // magnitude.
        assert_eq!(funding.rate, dec!(-0.000008071979166667));
        assert_eq!(funding.mark_price, dec!(81235.79652525584));

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

    /// A caller watching prices does not start receiving funding prints.
    #[test]
    fn an_unsubscribed_derivatives_print_is_not_emitted_by_kraken() {
        let (mut kraken, ws) = futures_ws_client();
        ws.push_connection(vec![Ok(Some(
            r#"{"time":1,"product_id":"PF_XBTUSD","feed":"ticker","bid":1.0,"ask":2.0,
            "volume":3.0,"index":4.0,"last":5.0,"markPrice":6.0,
            "relative_funding_rate":-0.00001}"#
                .to_string(),
        ))]);
        Kraken::subscribe_ticker(&mut kraken, &symbol()).unwrap();

        let events = Kraken::poll_events(&mut kraken);
        assert_eq!(events.len(), 1, "only the ticker was asked for: {events:?}");
        assert!(matches!(events[0], Event::Ticker(_)));
    }

    /// Kraken publishes no public feed of forced orders, and no positioning
    /// figure, so both are refused rather than left to deliver nothing.
    #[test]
    fn kraken_refuses_what_it_does_not_publish() {
        let (mut kraken, ws) = futures_ws_client();
        let err =
            Kraken::subscribe_derivatives(&mut kraken, &symbol(), DerivativesChannel::Liquidations)
                .expect_err("Kraken has no public liquidation feed");
        assert!(matches!(err, Error::Exchange { ref code, .. } if code == "unsupported"));
        assert!(ws.sent().is_empty(), "refused, yet subscribed");

        let (kraken, _) = futures_ws_client();
        assert!(Kraken::long_short_ratio(&kraken, &symbol()).is_err());
    }

    #[test]
    fn open_interest_reads_the_products_row() {
        let http = Arc::new(MockHttpTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::UsdMFutures);
        let kraken = Kraken::with_http(Box::new(ArcTransport(Arc::clone(&http))), &opts);
        http.push_json(
            200,
            r#"{"result":"success","tickers":[
            {"symbol":"PF_ETHUSD","openInterest":100.0},
            {"symbol":"PF_XBTUSD","last":81582,"markPrice":81570.61,"openInterest":1863.9616,
             "fundingRate":-0.655949}]}"#,
        );
        let open_interest = Kraken::open_interest(&kraken, &symbol()).unwrap();
        assert_eq!(open_interest.open_interest, dec!(1863.9616));
    }

    /// A spot client has no derivatives surface at all.
    #[test]
    fn a_spot_client_refuses_the_kraken_derivatives_surface() {
        let ws = Arc::new(MockWsTransport::new());
        let http = Arc::new(MockHttpTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::Spot);
        let mut kraken = Kraken::with_http(Box::new(ArcTransport(http)), &opts)
            .with_ws(Box::new(ArcWs(Arc::clone(&ws))));
        for channel in [
            DerivativesChannel::Funding,
            DerivativesChannel::MarkIndex,
            DerivativesChannel::Liquidations,
        ] {
            assert!(Kraken::subscribe_derivatives(&mut kraken, &symbol(), channel).is_err());
        }
        assert!(Kraken::open_interest(&kraken, &symbol()).is_err());
    }

    /// Kraken Futures is a different service, not the spot socket with other
    /// names: another host, another subscribe shape, another frame shape.
    #[test]
    fn a_futures_client_subscribes_on_the_futures_service() {
        let (mut kraken, ws) = futures_ws_client();
        Kraken::subscribe_trades(&mut kraken, &symbol()).unwrap();
        Kraken::subscribe_book(&mut kraken, &symbol()).unwrap();

        assert_eq!(ws.connected_urls()[0], "wss://futures.kraken.com/ws/v1");
        assert!(ws.sent()[0].contains(r#""event":"subscribe""#));
        assert!(ws.sent()[0].contains(r#""feed":"trade""#));
        assert!(ws.sent()[0].contains(r#""product_ids":["PF_XBTUSD"]"#));
        assert!(ws.sent()[1].contains(r#""feed":"book""#));
        // The spot protocol must not leak into it.
        assert!(!ws.sent()[0].contains(r#""method":"subscribe""#));
    }

    /// The trade frame, as `futures.kraken.com` sends it: JSON numbers, `qty`
    /// in base units, `time` in milliseconds.
    #[test]
    fn a_futures_trade_frame_parses() {
        let (mut kraken, ws) = futures_ws_client();
        ws.push_connection(vec![Ok(Some(
            r#"{"product_id":"PF_XBTUSD","feed":"trade","uid":"066870ad","side":"buy",
            "type":"fill","time":1788462443224,"qty":0.0012,"price":81234.0,"seq":131499}"#
                .to_string(),
        ))]);
        Kraken::subscribe_trades(&mut kraken, &symbol()).unwrap();

        let events = Kraken::poll_events(&mut kraken);
        let Event::Trade(trade) = &events[0] else {
            panic!("expected a trade, got {:?}", events[0]);
        };
        assert_eq!(trade.symbol, symbol());
        assert_eq!(trade.price, dec!(81234.0));
        assert_eq!(trade.quantity, dec!(0.0012));
        assert_eq!(trade.aggressor, OrderSide::Buy);
        assert_eq!(trade.timestamp, 1_788_462_443_224);
    }

    /// The book snapshot, with levels as `{price, qty}` objects of numbers.
    #[test]
    fn a_futures_book_snapshot_parses() {
        let (mut kraken, ws) = futures_ws_client();
        ws.push_connection(vec![Ok(Some(
            r#"{"feed":"book_snapshot","product_id":"PF_XBTUSD","timestamp":1788462442376,
            "seq":48891892,"tickSize":null,
            "bids":[{"price":81233.0,"qty":1.1465},{"price":81232.0,"qty":0.0124}],
            "asks":[{"price":81234.0,"qty":0.0012}]}"#
                .to_string(),
        ))]);
        Kraken::subscribe_book(&mut kraken, &symbol()).unwrap();

        let events = Kraken::poll_events(&mut kraken);
        let Event::BookSnapshot(book) = &events[0] else {
            panic!("expected a snapshot, got {:?}", events[0]);
        };
        assert_eq!(book.bids.len(), 2);
        assert_eq!(book.bids[0].price, dec!(81233.0));
        assert_eq!(book.asks[0].quantity, dec!(0.0012));
        assert_eq!(book.timestamp, 1_788_462_442_376);
        assert_eq!(book.last_update_id, 48_891_892);
    }

    /// An incremental book frame is one level on one side at its new size.
    #[test]
    fn a_futures_book_delta_carries_one_side() {
        let (mut kraken, ws) = futures_ws_client();
        ws.push_connection(vec![Ok(Some(
            r#"{"feed":"book","product_id":"PF_XBTUSD","side":"sell","seq":48891893,
            "price":81270.0,"qty":3.1591,"timestamp":1788462442378}"#
                .to_string(),
        ))]);
        Kraken::subscribe_book(&mut kraken, &symbol()).unwrap();

        let events = Kraken::poll_events(&mut kraken);
        let Event::BookDelta(delta) = &events[0] else {
            panic!("expected a delta, got {:?}", events[0]);
        };
        assert_eq!(delta.bids, Vec::new());
        assert_eq!(delta.asks.len(), 1);
        assert_eq!(delta.asks[0].price, dec!(81270.0));
        assert_eq!(delta.asks[0].quantity, dec!(3.1591));
    }

    /// The prices are exact, not routed through `f64`.
    ///
    /// Kraken Futures sends numbers where the spot socket sends strings. Going
    /// through the binary form would introduce the rounding the order layer
    /// keeps `Decimal` to avoid, and `0.1 + 0.2` is the standing reminder.
    #[test]
    fn futures_numbers_stay_exact() {
        let (mut kraken, ws) = futures_ws_client();
        ws.push_connection(vec![Ok(Some(
            r#"{"product_id":"PF_XBTUSD","feed":"trade","side":"buy","time":1,
            "qty":0.1,"price":0.3}"#
                .to_string(),
        ))]);
        Kraken::subscribe_trades(&mut kraken, &symbol()).unwrap();

        let events = Kraken::poll_events(&mut kraken);
        let Event::Trade(trade) = &events[0] else {
            panic!("expected a trade");
        };
        assert_eq!(trade.price, dec!(0.3));
        assert_eq!(trade.quantity, dec!(0.1));
    }

    /// One connection carries every subscription, so a product that was never
    /// asked for is dropped rather than delivered.
    #[test]
    fn a_futures_frame_for_an_unsubscribed_product_is_dropped() {
        let (mut kraken, ws) = futures_ws_client();
        ws.push_connection(vec![Ok(Some(
            r#"{"product_id":"PF_ETHUSD","feed":"trade","side":"buy","time":1,
            "qty":1.0,"price":3000.0}"#
                .to_string(),
        ))]);
        Kraken::subscribe_trades(&mut kraken, &symbol()).unwrap();

        assert_eq!(Kraken::poll_events(&mut kraken), Vec::new());
    }

    /// The spot client is untouched by any of it.
    #[test]
    fn a_spot_client_still_speaks_the_v2_protocol() {
        let ws = Arc::new(MockWsTransport::new());
        let http = Arc::new(MockHttpTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::Spot);
        let mut kraken = Kraken::with_http(Box::new(ArcTransport(http)), &opts)
            .with_ws(Box::new(ArcWs(Arc::clone(&ws))));
        Kraken::subscribe_trades(&mut kraken, &symbol()).unwrap();
        assert_eq!(ws.connected_urls()[0], "wss://ws.kraken.com/v2");
        assert!(ws.sent()[0].contains(r#""method":"subscribe""#));
    }

    #[test]
    fn subscribe_user_data_fetches_token_and_streams_executions_and_balances() {
        let (mut kraken, http, ws) = signed_ws_client(1000);
        http.push_json(
            200,
            r#"{"error":[],"result":{"token":"tok","expires":900}}"#,
        );
        ws.push_connection(vec![
            Ok(Some(
                r#"{"method":"subscribe","success":true,"result":{"channel":"executions"}}"#
                    .to_string(),
            )),
            Ok(Some(
                r#"{"channel":"executions","type":"snapshot","data":[{"order_id":"O123",
                "symbol":"BTC/USDT","side":"buy","order_type":"limit","order_status":"filled",
                "order_qty":1.0,"cum_qty":1.0,"limit_price":100,"avg_price":100,"cl_ord_id":"my"}]}"#
                    .to_string(),
            )),
            Ok(Some(
                r#"{"channel":"balances","type":"snapshot","data":[{"asset":"USDT",
                "balance":900.0}]}"#
                    .to_string(),
            )),
        ]);
        kraken.subscribe_user_data().unwrap();

        let reqs = http.recorded_requests();
        assert!(reqs[0].url.contains("/0/private/GetWebSocketsToken"));
        assert_eq!(ws.connected_urls()[0], "wss://ws-auth.kraken.com/v2");
        assert!(ws.sent()[0].contains(r#""channel":"executions""#));
        assert!(ws.sent()[0].contains(r#""token":"tok""#));
        assert!(ws.sent()[1].contains(r#""channel":"balances""#));

        let events = kraken.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, "O123");
        assert_eq!(order.client_order_id.as_deref(), Some("my"));
        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));
    }

    #[test]
    fn futures_subscribe_user_data_signs_the_challenge_and_subscribes_the_feeds() {
        let (mut kraken, ws) = signed_futures_ws_client(1000);
        ws.push_connection(vec![
            // The challenge response, then a subscription ack and two feed frames.
            Ok(Some(
                r#"{"event":"challenge","message":"challenge-uuid"}"#.to_string(),
            )),
            Ok(Some(
                r#"{"feed":"open_orders_snapshot","account":"acct","orders":[{"instrument":"PF_XBTUSD",
                "order_id":"O123","cli_ord_id":"my","direction":0,"type":"limit","qty":2.0,"filled":0.0,
                "limit_price":100.0}]}"#
                    .to_string(),
            )),
            Ok(Some(
                r#"{"feed":"balances_snapshot","account":"acct","holding":{"USD":900.0}}"#.to_string(),
            )),
        ]);
        kraken.subscribe_user_data().unwrap();
        assert_eq!(ws.connected_urls()[0], "wss://futures.kraken.com/ws/v1");
        // First frame requests the challenge; the two subscribes carry the signed one.
        assert!(ws.sent()[0].contains(r#""event":"challenge""#));
        assert!(ws.sent()[0].contains(r#""api_key":"APIKEY""#));
        assert!(ws.sent()[1].contains(r#""feed":"open_orders""#));
        assert!(ws.sent()[1].contains(r#""original_challenge":"challenge-uuid""#));
        assert!(ws.sent()[1].contains(r#""signed_challenge""#));
        assert!(ws.sent()[2].contains(r#""feed":"balances""#));

        let events = kraken.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, "O123");
        assert_eq!(order.client_order_id.as_deref(), Some("my"));
        assert_eq!(order.symbol, Symbol::new("BTC", "USD"));
        assert_eq!(order.side, OrderSide::Buy);
        assert_eq!(order.order_type, OrderType::Limit);
        assert_eq!(order.quantity, dec!(2));
        assert_eq!(order.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, "USD");
        assert_eq!(balances[0].free, dec!(900));
    }

    #[test]
    fn futures_open_orders_update_reports_a_cancel() {
        let (mut kraken, ws) = signed_futures_ws_client(1000);
        ws.push_connection(vec![
            Ok(Some(
                r#"{"event":"challenge","message":"challenge-uuid"}"#.to_string(),
            )),
            Ok(Some(
                r#"{"feed":"open_orders","is_cancel":true,"order":{"instrument":"PF_ETHUSD",
                "order_id":"O9","direction":1,"type":"limit","qty":1.0,"filled":0.0,"limit_price":50.0}}"#
                    .to_string(),
            )),
        ]);
        kraken.subscribe_user_data().unwrap();
        let events = kraken.poll_events();
        assert_eq!(events.len(), 1);
        let Event::OrderUpdate(order) = &events[0] else {
            panic!("event must be an order update");
        };
        assert_eq!(order.id, "O9");
        assert_eq!(order.symbol, Symbol::new("ETH", "USD"));
        assert_eq!(order.side, OrderSide::Sell);
        assert_eq!(order.status, OrderStatus::Canceled);
    }

    #[test]
    fn futures_keepalive_user_data_is_a_noop() {
        // Kraken Futures keeps the feed alive server-side, so keepalive sends nothing.
        let (mut kraken, ws) = signed_futures_ws_client(1000);
        ws.push_connection(vec![Ok(Some(
            r#"{"event":"challenge","message":"challenge-uuid"}"#.to_string(),
        ))]);
        kraken.subscribe_user_data().unwrap();
        let sent_after_subscribe = ws.sent().len();
        kraken.keepalive_user_data().unwrap();
        assert_eq!(ws.sent().len(), sent_after_subscribe);
    }

    #[test]
    fn keepalive_user_data_pings_the_private_stream() {
        let (mut kraken, http, ws) = signed_ws_client(1000);
        http.push_json(
            200,
            r#"{"error":[],"result":{"token":"tok","expires":900}}"#,
        );
        ws.push_connection(vec![]);
        kraken.subscribe_user_data().unwrap();
        kraken.keepalive_user_data().unwrap();
        assert!(ws.sent().iter().any(|f| f == r#"{"method":"ping"}"#));
    }

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

    #[test]
    fn dropped_user_data_stream_reconnects_with_a_fresh_token() {
        let (mut kraken, http, ws) = signed_ws_client(1000);
        http.push_json(
            200,
            r#"{"error":[],"result":{"token":"tok-1","expires":900}}"#,
        );
        // 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![]);
        kraken.subscribe_user_data().unwrap();
        // The reconnect re-fetches a fresh single-use token over REST.
        http.push_json(
            200,
            r#"{"error":[],"result":{"token":"tok-2","expires":900}}"#,
        );

        let events = kraken.poll_events();
        assert!(events.contains(&Event::Disconnected));
        assert!(events.contains(&Event::Reconnected));
        // Two token POSTs (initial + reconnect) and a second WS connection whose
        // subscribe carries the fresh token.
        let tokens = http
            .recorded_requests()
            .into_iter()
            .filter(|r| r.url.contains("/0/private/GetWebSocketsToken"))
            .count();
        assert_eq!(tokens, 2);
        assert_eq!(ws.connected_urls().len(), 2);
        assert!(ws.sent().iter().any(|f| f.contains(r#""token":"tok-2""#)));
    }

    #[test]
    fn place_and_cancel_order_over_ws() {
        let (mut kraken, http, ws) = signed_ws_client(1000);
        http.push_json(
            200,
            r#"{"error":[],"result":{"token":"tok","expires":900}}"#,
        );
        ws.push_connection(vec![
            Ok(Some(
                r#"{"method":"add_order","req_id":1000,"success":true,
                "result":{"order_id":"O123","order_userref":0}}"#
                    .to_string(),
            )),
            Ok(Some(
                r#"{"method":"cancel_order","req_id":1000,"success":true,
                "result":{"order_id":"O123"}}"#
                    .to_string(),
            )),
        ]);
        let order = kraken
            .place_order_ws(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)))
            .unwrap();
        assert_eq!(order.id, "O123");
        assert_eq!(order.status, OrderStatus::New);
        let reqs = http.recorded_requests();
        assert!(reqs[0].url.contains("/0/private/GetWebSocketsToken"));
        assert_eq!(ws.connected_urls()[0], "wss://ws-auth.kraken.com/v2");
        assert!(ws.sent()[0].contains(r#""method":"add_order""#));
        assert!(ws.sent()[0].contains(r#""token":"tok""#));
        assert!(ws.sent()[0].contains(r#""symbol":"BTC/USDT""#));

        kraken.cancel_order_ws(&symbol(), "O123").unwrap();
        assert!(ws.sent()[1].contains(r#""method":"cancel_order""#));
        assert!(ws.sent()[1].contains(r#""order_id":["O123"]"#));
    }

    #[test]
    fn ws_order_surfaces_rejection() {
        let (mut kraken, http, ws) = signed_ws_client(1000);
        http.push_json(
            200,
            r#"{"error":[],"result":{"token":"tok","expires":900}}"#,
        );
        ws.push_connection(vec![Ok(Some(
            r#"{"method":"add_order","req_id":1000,"success":false,
            "error":"EOrder:Insufficient funds"}"#
                .to_string(),
        ))]);
        assert!(matches!(
            kraken
                .place_order_ws(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)))
                .unwrap_err(),
            Error::OrderRejected { .. }
        ));
    }

    #[test]
    fn ws_order_rejects_the_futures_client() {
        let (mut kraken, _mock) = futures_client();
        assert!(matches!(
            kraken
                .place_order_ws(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)))
                .unwrap_err(),
            Error::Exchange { .. }
        ));
    }

    #[test]
    fn amend_order_edits_then_reads_new_txid() {
        let (kraken, mock) = signed_client(1000);
        mock.push_json(
            200,
            r#"{"error":[],"result":{"status":"ok","txid":"NEW1"}}"#,
        );
        mock.push_json(
            200,
            r#"{"error":[],"result":{"NEW1":{"status":"open","vol":"2","vol_exec":"0",
            "price":"101","descr":{"pair":"XBTUSDT","type":"buy","ordertype":"limit","price":"101"}}}}"#,
        );
        let order = kraken
            .amend_order(&symbol(), "OLD1", Some(dec!(101)), Some(dec!(2)))
            .unwrap();
        assert_eq!(order.id, "NEW1");
        assert_eq!(order.quantity, dec!(2));
        let reqs = mock.recorded_requests();
        assert!(reqs[0].url.contains("/0/private/EditOrder"));
        let body = reqs[0].body.as_ref().unwrap();
        assert!(body.contains("txid=OLD1"));
        assert!(body.contains("volume=2"));
        assert!(body.contains("price=101"));
    }

    #[test]
    fn cancel_batch_uses_the_native_endpoint() {
        let (kraken, mock) = signed_client(1000);
        mock.push_json(200, r#"{"error":[],"result":{"count":2}}"#);
        kraken
            .cancel_batch(&symbol(), &["OID1".to_string(), "OID2".to_string()])
            .unwrap();
        let reqs = mock.recorded_requests();
        // One CancelOrderBatch request carries both ids as a form array.
        assert_eq!(reqs.len(), 1);
        assert!(reqs[0].url.contains("/0/private/CancelOrderBatch"));
        let body = reqs[0].body.as_ref().unwrap();
        assert!(body.contains("orders[]=OID1"));
        assert!(body.contains("orders[]=OID2"));
    }

    #[test]
    fn place_batch_uses_the_indexed_add_order_batch_form() {
        let (mut kraken, mock) = signed_client(1000);
        mock.push_json(
            200,
            r#"{"error":[],"result":{"orders":[{"txid":"OID1","descr":{"order":"buy"}},
            {"error":"EOrder:Insufficient funds"}]}}"#,
        );
        let results = AdvancedOrders::place_batch(
            &mut kraken,
            &[
                OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)),
                OrderRequest::limit_buy(symbol(), dec!(2), dec!(90)),
            ],
        )
        .unwrap();
        // The first order is accepted; the second carries its own rejection.
        assert_eq!(results.len(), 2);
        assert_eq!(results[0].as_ref().unwrap().id, "OID1");
        assert!(matches!(
            results[1].as_ref().unwrap_err(),
            Error::InsufficientBalance
        ));
        let reqs = mock.recorded_requests();
        assert!(reqs[0].url.contains("/0/private/AddOrderBatch"));
        let body = reqs[0].body.as_ref().unwrap();
        assert!(body.contains("pair=XBTUSDT"));
        assert!(body.contains("orders[0][ordertype]=limit"));
        assert!(body.contains("orders[0][type]=buy"));
        assert!(body.contains("orders[0][volume]=1"));
        assert!(body.contains("orders[0][price]=100"));
        assert!(body.contains("orders[1][volume]=2"));
        assert!(body.contains("orders[1][price]=90"));
    }

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

    #[test]
    fn futures_symbol_is_pf_usd_settled() {
        assert_eq!(Kraken::futures_symbol(&symbol()), "PF_XBTUSD");
        assert_eq!(
            Kraken::futures_symbol(&Symbol::new("ETH", "USD")),
            "PF_ETHUSD"
        );
    }

    #[test]
    fn futures_ticker_filters_by_symbol_on_the_futures_host() {
        let (kraken, mock) = futures_client();
        mock.push_json(
            200,
            r#"{"result":"success","tickers":[
            {"symbol":"pf_ethusd","last":3000,"bid":2999,"ask":3001,"vol24h":10},
            {"symbol":"pf_xbtusd","last":20000.5,"bid":19999,"ask":20001,"vol24h":1234}]}"#,
        );
        let ticker = kraken.ticker(&symbol()).unwrap();
        assert_eq!(ticker.last, dec!(20000.5));
        assert_eq!(ticker.bid, dec!(19999));
        assert_eq!(ticker.volume, dec!(1234));
        assert!(mock.recorded_requests()[0]
            .url
            .contains("futures.kraken.com/derivatives/api/v3/tickers"));
    }

    #[test]
    fn futures_order_book_numeric_pairs() {
        let (kraken, mock) = futures_client();
        mock.push_json(
            200,
            r#"{"result":"success","orderBook":{"bids":[[100.0,1.0]],"asks":[[101.0,2.0]]}}"#,
        );
        let book = kraken.order_book(&symbol(), 5).unwrap();
        assert_eq!(book.bids[0], BookLevel::new(dec!(100), dec!(1)));
        assert_eq!(book.asks[0], BookLevel::new(dec!(101), dec!(2)));
        assert!(mock.recorded_requests()[0]
            .url
            .contains("/derivatives/api/v3/orderbook?symbol=PF_XBTUSD"));
    }

    #[test]
    fn futures_klines_from_charts_api() {
        let (kraken, mock) = futures_client();
        mock.push_json(
            200,
            r#"{"candles":[{"time":1700000000,"open":100,"high":110,"low":95,"close":105,"volume":12}]}"#,
        );
        let candles = kraken.klines(&symbol(), "1h", 1).unwrap();
        assert_eq!(candles[0].timestamp, 1_700_000_000);
        assert!((candles[0].high - 110.0).abs() < 1e-9);
        assert!(mock.recorded_requests()[0]
            .url
            .contains("/api/charts/v1/trade/PF_XBTUSD/1h"));
    }

    #[test]
    fn futures_market_order_uses_sendorder() {
        let (kraken, mock) = signed_futures_client(1000);
        mock.push_json(
            200,
            r#"{"result":"success","sendStatus":{"order_id":"abc-1","status":"placed"}}"#,
        );
        let order = kraken
            .place_order(&OrderRequest::market_buy(symbol(), dec!(2)))
            .unwrap();
        assert_eq!(order.id, "abc-1");
        assert_eq!(order.status, OrderStatus::New);
        let req = &mock.recorded_requests()[0];
        assert!(req
            .url
            .contains("futures.kraken.com/derivatives/api/v3/sendorder"));
        let body = req.body.as_ref().unwrap();
        assert!(body.contains("orderType=mkt"));
        assert!(body.contains("symbol=PF_XBTUSD"));
        assert!(body.contains("side=buy"));
        assert!(body.contains("reduceOnly=false"));
        // Reconstruct the Authent signature over SHA256(postData ++ nonce ++ path).
        let concat = format!("{body}1000/api/v3/sendorder");
        let expected =
            hmac_sha512_base64_with_b64_secret("c2VjcmV0", &sha256(concat.as_bytes())).unwrap();
        let sign = req
            .headers
            .iter()
            .find(|(k, _)| k == "Authent")
            .map(|(_, v)| v.as_str())
            .unwrap();
        assert_eq!(sign, expected);
    }

    #[test]
    fn futures_query_order_uses_orders_status() {
        let (kraken, mock) = signed_futures_client(1000);
        mock.push_json(
            200,
            r#"{"result":"success","orders":[{"order_id":"o-1","status":"FULLY_EXECUTED",
            "order":{"orderType":"lmt","side":"buy","quantity":3,"filled":3,"limitPrice":100,
            "symbol":"pf_xbtusd","cliOrdId":""}}]}"#,
        );
        let order = kraken.query_order(&symbol(), "o-1").unwrap();
        assert_eq!(order.id, "o-1");
        assert_eq!(order.side, OrderSide::Buy);
        assert_eq!(order.order_type, OrderType::Limit);
        assert_eq!(order.status, OrderStatus::Filled);
        assert_eq!(order.quantity, dec!(3));
        let req = &mock.recorded_requests()[0];
        assert!(req.url.contains("/derivatives/api/v3/orders/status"));
    }

    #[test]
    fn futures_cancel_and_open_orders_use_derivatives_endpoints() {
        let (kraken, mock) = signed_futures_client(1000);
        mock.push_json(
            200,
            r#"{"result":"success","cancelStatus":{"status":"cancelled"}}"#,
        );
        kraken.cancel_order(&symbol(), "o-1").unwrap();
        mock.push_json(
            200,
            r#"{"result":"success","openOrders":[{"order_id":"o-2","symbol":"pf_xbtusd",
            "side":"sell","orderType":"lmt","limitPrice":21000,"filledSize":1,"unfilledSize":2,
            "status":"partiallyFilled","cliOrdId":""}]}"#,
        );
        let orders = kraken.open_orders(Some(&symbol())).unwrap();
        assert_eq!(orders.len(), 1);
        assert_eq!(orders[0].side, OrderSide::Sell);
        assert_eq!(orders[0].status, OrderStatus::PartiallyFilled);
        assert_eq!(orders[0].quantity, dec!(3)); // filledSize + unfilledSize
        assert_eq!(orders[0].filled_quantity, dec!(1));
        let reqs = mock.recorded_requests();
        assert!(reqs[0].url.contains("/derivatives/api/v3/cancelorder"));
        assert!(reqs[1].url.contains("/derivatives/api/v3/openorders"));
    }

    #[test]
    fn derivatives_positions_parse() {
        let (mut kraken, mock) = signed_futures_client(1000);
        mock.push_json(200, r#"{"result":"success"}"#);
        kraken.set_leverage(&symbol(), 5).unwrap();
        mock.push_json(
            200,
            r#"{"result":"success","openPositions":[
            {"symbol":"pf_xbtusd","side":"long","size":3,"price":20000}]}"#,
        );
        let positions = Derivatives::positions(&mut kraken, Some(&symbol())).unwrap();
        assert_eq!(positions.len(), 1);
        assert_eq!(positions[0].symbol, Symbol::new("BTC", "USD"));
        assert_eq!(positions[0].side, PositionSide::Long);
        assert_eq!(positions[0].quantity, dec!(3));
        assert_eq!(positions[0].entry_price, dec!(20000));
        assert_eq!(positions[0].leverage, dec!(5)); // recorded via set_leverage
        assert_eq!(positions[0].margin_mode, MarginMode::Cross);
        let reqs = mock.recorded_requests();
        assert!(reqs[0]
            .url
            .contains("/derivatives/api/v3/leveragepreferences"));
        assert_eq!(reqs[0].method, HttpMethod::Put);
        assert!(reqs[1].url.contains("/derivatives/api/v3/openpositions"));
    }

    #[test]
    fn set_margin_mode_isolated_is_unsupported() {
        let (kraken, _mock) = signed_futures_client(1000);
        assert!(kraken.set_margin_mode(&symbol(), MarginMode::Cross).is_ok());
        assert!(matches!(
            kraken
                .set_margin_mode(&symbol(), MarginMode::Isolated)
                .unwrap_err(),
            Error::Exchange { .. }
        ));
    }

    /// Kraken Futures carries post-only and IOC inside `orderType`, and has no
    /// fill-or-kill anywhere; its APIs carry no STP field either.
    #[test]
    fn futures_orders_carry_the_time_in_force_or_refuse_it() {
        let (kraken, 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 _ = kraken.place_order(&ioc);
        let body = mock.recorded_requests()[0].body.clone().unwrap_or_default();
        assert!(body.contains("orderType=ioc"));

        let (kraken, mock) = signed_futures_client(1000);
        let both = OrderRequest::limit_buy(symbol(), dec!(1), dec!(100))
            .post_only()
            .with_time_in_force(TimeInForce::Ioc);
        let err = kraken.place_order(&both).unwrap_err();
        assert!(matches!(err, Error::Exchange { ref code, .. } if code == "unsupported"));
        assert_eq!(mock.recorded_requests(), Vec::new());

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

        let (kraken, mock) = signed_futures_client(1000);
        let stp = OrderRequest::limit_buy(symbol(), dec!(1), dec!(100))
            .with_stp(SelfTradePrevention::ExpireMaker);
        let err = kraken.place_order(&stp).unwrap_err();
        assert!(matches!(err, Error::Exchange { ref code, .. } if code == "unsupported"));
        assert_eq!(mock.recorded_requests(), Vec::new());
    }

    /// The batch and WebSocket paths honour the same two limits.
    #[test]
    fn the_batch_and_websocket_paths_refuse_what_kraken_cannot_say() {
        let (mut kraken, mock) = signed_client(1000);
        let stp = OrderRequest::limit_buy(symbol(), dec!(1), dec!(100))
            .with_stp(SelfTradePrevention::ExpireMaker);
        let err = AdvancedOrders::place_batch(&mut kraken, &[stp]).unwrap_err();
        assert!(matches!(err, Error::Exchange { ref code, .. } if code == "unsupported"));
        assert_eq!(mock.recorded_requests(), Vec::new());

        let (mut kraken, mock) = signed_client(1000);
        let fok = OrderRequest::limit_buy(symbol(), dec!(1), dec!(100))
            .with_time_in_force(TimeInForce::Fok);
        let err = AdvancedOrders::place_batch(&mut kraken, &[fok]).unwrap_err();
        assert!(matches!(err, Error::Exchange { ref code, .. } if code == "unsupported"));
        assert_eq!(mock.recorded_requests(), Vec::new());

        let (mut kraken, _mock) = signed_client(1000);
        let ws_stp = OrderRequest::limit_buy(symbol(), dec!(1), dec!(100))
            .with_stp(SelfTradePrevention::ExpireMaker);
        let err = WsExecution::place_order_ws(&mut kraken, &ws_stp).unwrap_err();
        assert!(matches!(err, Error::Exchange { ref code, .. } if code == "unsupported"));
    }

    #[test]
    fn close_position_is_reduce_only_opposite() {
        let (mut kraken, mock) = signed_futures_client(1000);
        mock.push_json(
            200,
            r#"{"result":"success","openPositions":[
            {"symbol":"pf_xbtusd","side":"long","size":3,"price":20000}]}"#,
        );
        mock.push_json(
            200,
            r#"{"result":"success","sendStatus":{"order_id":"c-9","status":"placed"}}"#,
        );
        Derivatives::close_position(&mut kraken, &symbol()).unwrap();
        let reqs = mock.recorded_requests();
        let body = reqs[1].body.as_ref().unwrap();
        assert!(body.contains("side=sell"));
        assert!(body.contains("reduceOnly=true"));
    }

    #[test]
    fn futures_balances_from_flex_currencies() {
        let (kraken, mock) = signed_futures_client(1000);
        mock.push_json(
            200,
            r#"{"result":"success","accounts":{"flex":{"currencies":{
            "USD":{"quantity":1000,"available":800}}}}}"#,
        );
        let bals = kraken.balances().unwrap();
        assert_eq!(bals[0].asset, "USD");
        assert_eq!(bals[0].free, dec!(800));
        assert_eq!(bals[0].locked, dec!(200));
        assert!(mock.recorded_requests()[0]
            .url
            .contains("/derivatives/api/v3/accounts"));
    }

    #[test]
    fn futures_error_envelope_maps() {
        let (kraken, mock) = futures_client();
        mock.push_json(200, r#"{"result":"error","error":"insufficientFunds"}"#);
        assert!(matches!(
            kraken.ticker(&symbol()).unwrap_err(),
            Error::InsufficientBalance
        ));
    }

    #[test]
    fn wire_symbol_maps_btc_to_xbt() {
        assert_eq!(Kraken::wire_symbol(&symbol()), "XBTUSDT");
        assert_eq!(Kraken::wire_symbol(&Symbol::new("ETH", "USD")), "ETHUSD");
    }

    #[test]
    fn ticker_takes_single_result() {
        let (kraken, mock) = client();
        mock.push_json(
            200,
            r#"{"error":[],"result":{"XXBTZUSD":{"a":["20001","1","1"],"b":["19999","1","1"],
            "c":["20000.5","0.1"],"v":["10","1234"]}}}"#,
        );
        let ticker = kraken.ticker(&symbol()).unwrap();
        assert_eq!(ticker.last, dec!(20000.5));
        assert_eq!(ticker.bid, dec!(19999));
        assert_eq!(ticker.volume, dec!(1234));
    }

    #[test]
    fn klines_skip_last_key() {
        let (kraken, mock) = client();
        mock.push_json(
            200,
            r#"{"error":[],"result":{"XXBTZUSD":[
            [1700000000,"100","110","95","105","103","12","5"],
            [1700003600,"105","106","104","105.5","105","2","3"]],"last":1700003600}}"#,
        );
        let candles = kraken.klines(&symbol(), "1h", 2).unwrap();
        assert_eq!(candles.len(), 2);
        assert_eq!(candles[0].timestamp, 1_700_000_000);
        assert!((candles[0].high - 110.0).abs() < 1e-9);
    }

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

    #[test]
    fn error_array_maps() {
        let (kraken, mock) = client();
        mock.push_json(
            200,
            r#"{"error":["EOrder:Insufficient funds"],"result":{}}"#,
        );
        assert!(matches!(
            kraken.ticker(&symbol()).unwrap_err(),
            Error::InsufficientBalance
        ));
    }

    #[test]
    fn place_order_signs_with_sha256_and_hmac512() {
        let (kraken, mock) = signed_client(1000);
        mock.push_json(
            200,
            r#"{"error":[],"result":{"txid":["OABC-123"],"descr":{"order":"x"}}}"#,
        );
        let order = kraken
            .place_order(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)))
            .unwrap();
        assert_eq!(order.id, "OABC-123");

        let req = &mock.recorded_requests()[0];
        assert_eq!(req.method, HttpMethod::Post);
        let body = req.body.as_ref().unwrap();
        assert!(body.starts_with("nonce=1000&"));
        // Reconstruct API-Sign.
        let path = "/0/private/AddOrder";
        let mut message = path.as_bytes().to_vec();
        message.extend_from_slice(&sha256(format!("1000{body}").as_bytes()));
        let expected = hmac_sha512_base64_with_b64_secret("c2VjcmV0", &message).unwrap();
        let sign = req
            .headers
            .iter()
            .find(|(k, _)| k == "API-Sign")
            .map(|(_, v)| v.as_str())
            .unwrap();
        assert_eq!(sign, expected);
        assert!(req
            .headers
            .iter()
            .any(|(k, v)| k == "API-Key" && v == "APIKEY"));
    }

    #[test]
    fn query_order_parses() {
        let (kraken, mock) = signed_client(1000);
        mock.push_json(
            200,
            r#"{"error":[],"result":{"OABC-123":{"status":"closed","vol":"2","vol_exec":"2",
            "price":"100","descr":{"pair":"XBTUSDT","type":"sell","ordertype":"limit","price":"100"}}}}"#,
        );
        let order = kraken.query_order(&symbol(), "OABC-123").unwrap();
        assert_eq!(order.status, OrderStatus::Filled);
        assert_eq!(order.side, OrderSide::Sell);
        assert_eq!(order.filled_quantity, dec!(2));
        assert_eq!(order.average_price, Some(dec!(100)));
    }

    #[test]
    fn balances_free_minus_hold() {
        let (kraken, mock) = signed_client(1000);
        mock.push_json(
            200,
            r#"{"error":[],"result":{"USDT":{"balance":"126","hold_trade":"25.5"}}}"#,
        );
        let bals = kraken.balances().unwrap();
        assert_eq!(bals[0].asset, "USDT");
        assert_eq!(bals[0].free, dec!(100.5));
        assert_eq!(bals[0].locked, dec!(25.5));
    }

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

    /// Kraken's v2 ticker payload carries no timestamp of its own, so the quote
    /// reports 0 rather than the moment it was parsed. A locally stamped quote
    /// would look fresh by construction, which is the one thing a staleness
    /// check must never be told.
    #[test]
    fn a_ws_ticker_reports_no_stamp_because_kraken_sends_none() {
        let ws = Arc::new(MockWsTransport::new());
        ws.push_connection(vec![Ok(Some(
            r#"{"channel":"ticker","type":"update","data":[
            {"symbol":"BTC/USDT","last":100.0,"bid":99.5,"ask":100.5,"volume":12.0}]}"#
                .to_string(),
        ))]);
        let http = Arc::new(MockHttpTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::Spot);
        let mut kraken = Kraken::with_http(Box::new(ArcTransport(http)), &opts)
            .with_ws(Box::new(ArcWs(Arc::clone(&ws))));
        kraken.subscribe_ticker(&symbol()).unwrap();

        let events = kraken.poll_events();
        let quote = events
            .iter()
            .find_map(|e| match e {
                Event::Ticker(t) => Some(t),
                _ => None,
            })
            .expect("a ticker event");
        assert_eq!(quote.last, dec!(100));
        assert_eq!(quote.timestamp, 0);
    }

    #[test]
    fn ws_v2_parses_trade_and_book() {
        let ws = Arc::new(MockWsTransport::new());
        ws.push_connection(vec![
            Ok(Some(
                r#"{"channel":"trade","type":"update","data":[
                {"symbol":"BTC/USDT","side":"buy","price":100.0,"qty":0.5}]}"#
                    .to_string(),
            )),
            Ok(Some(
                r#"{"channel":"book","type":"snapshot","data":[
                {"symbol":"BTC/USDT","bids":[{"price":100.0,"qty":1.0}],"asks":[{"price":101.0,"qty":2.0}]}]}"#
                    .to_string(),
            )),
            Ok(Some(r#"{"channel":"status","data":[]}"#.to_string())),
        ]);
        let http = Arc::new(MockHttpTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::Spot);
        let mut kraken = Kraken::with_http(Box::new(ArcTransport(http)), &opts)
            .with_ws(Box::new(ArcWs(Arc::clone(&ws))));
        kraken.subscribe_trades(&symbol()).unwrap();
        assert!(ws.sent()[0].contains(r#""symbol":["BTC/USDT"]"#));
        assert_eq!(ws.connected_urls()[0], "wss://ws.kraken.com/v2");

        let events = kraken.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.symbol, symbol());
        assert!(matches!(events[1], Event::BookSnapshot(_)));
    }

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

    #[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("Kraken {"));
        assert!(rendered.contains("authenticated: true"));
        assert!(!rendered.contains("c2VjcmV0"));
        assert!(!rendered.contains("APIKEY"));

        // The WebSocket token authenticates the session; presence only.
        assert!(rendered.contains("ws_api_token: false"));
    }

    /// Kraken refuses a nonce that does not strictly increase. The wall clock
    /// alone is not one: two signed calls inside the same millisecond produced
    /// the same value, and a clock that stepped backwards produced a smaller
    /// one. Both were `Invalid nonce` from the venue, and neither was visible
    /// here.
    #[test]
    fn nonce_is_monotonic_within_a_millisecond() {
        // A frozen clock: every call reports the same millisecond.
        let (kraken, http) = signed_client(1_000_000);
        for _ in 0..3 {
            http.push_json(200, r#"{"error":[],"result":{}}"#);
            let _ = kraken.balances();
        }

        let nonces: Vec<i64> = http
            .recorded_requests()
            .iter()
            .filter_map(|request| request.body.as_deref())
            .filter_map(|body| {
                body.strip_prefix("nonce=")
                    .and_then(|rest| rest.split('&').next())
                    .and_then(|value| value.parse().ok())
            })
            .collect();

        assert_eq!(nonces.len(), 3, "three signed requests were recorded");
        assert!(
            nonces.windows(2).all(|pair| pair[1] > pair[0]),
            "nonces must strictly increase even on a frozen clock: {nonces:?}"
        );
    }

    /// The offset reaches the nonce, so a machine behind the venue does not
    /// start from a timestamp the venue has already seen.
    #[test]
    fn sync_time_shifts_the_nonce() {
        let (mut kraken, http) = signed_client(1_000_000);

        // Shape verified against the live public endpoint on 2026-09-01:
        // {"error":[],"result":{"unixtime":1788295967,"rfc1123":"..."}}
        // Kraken is the one venue here that reports seconds.
        http.push_json(200, r#"{"error":[],"result":{"unixtime":1004}}"#);
        let offset = kraken.sync_time().expect("sync must succeed");
        assert_eq!(offset, 4_000, "1004 s is 4 s ahead of 1_000_000 ms");

        http.push_json(200, r#"{"error":[],"result":{}}"#);
        let _ = kraken.balances();

        let requests = http.recorded_requests();
        let body = requests
            .last()
            .and_then(|request| request.body.as_deref())
            .expect("the signed request carries a form body");
        assert!(
            body.starts_with("nonce=1004000"),
            "the nonce must start from the venue's time: {body}"
        );
    }

    /// The WebSocket token expires; a live connection does not make it valid.
    ///
    /// `GetWebSocketsToken` returns the token with an `expires` (900 seconds).
    /// That field was read past: the token was cached and reused for as long as
    /// the connection stayed open, so a client placing orders over the
    /// WebSocket API for longer than fifteen minutes kept sending one the venue
    /// had stopped accepting.
    #[test]
    fn expired_ws_token_is_refetched() {
        use std::sync::atomic::{AtomicI64, Ordering};

        let clock = Arc::new(AtomicI64::new(1_000));
        let http = Arc::new(MockHttpTransport::new());
        let ws = Arc::new(MockWsTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::Spot);
        let reader = Arc::clone(&clock);
        let mut kraken = Kraken::with_credentials(
            Box::new(ArcTransport(Arc::clone(&http))),
            &opts,
            Credentials::new("APIKEY", "c2VjcmV0"),
        )
        .with_ws(Box::new(ArcWs(Arc::clone(&ws))))
        .with_clock(Box::new(move || reader.load(Ordering::Relaxed)));

        let accepted = r#"{"method":"add_order","req_id":1000,"success":true,
            "result":{"order_id":"O123"}}"#;

        // First order: fetches "first" and uses it.
        http.push_json(
            200,
            r#"{"error":[],"result":{"token":"first","expires":900}}"#,
        );
        ws.push_connection(vec![Ok(Some(accepted.to_string()))]);
        kraken
            .place_order_ws(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)))
            .expect("first order");
        assert!(ws.sent()[0].contains(r#""token":"first""#));

        // Sixteen minutes later the token has expired, so the next order must
        // fetch a new one rather than reuse it over the still-open connection.
        clock.store(1_000 + 960_000, Ordering::Relaxed);
        http.push_json(
            200,
            r#"{"error":[],"result":{"token":"second","expires":900}}"#,
        );
        ws.push_connection(vec![Ok(Some(accepted.to_string()))]);
        kraken
            .place_order_ws(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)))
            .expect("second order");

        let token_fetches = http
            .recorded_requests()
            .iter()
            .filter(|request| request.url.contains("/0/private/GetWebSocketsToken"))
            .count();
        assert_eq!(token_fetches, 2, "the expired token was refetched");
        assert!(
            ws.sent().last().unwrap().contains(r#""token":"second""#),
            "the new token is the one sent: {:?}",
            ws.sent().last()
        );
    }

    /// Inside the lifetime the token is reused: expiry tracking must not turn
    /// every order into an extra REST call.
    #[test]
    fn unexpired_ws_token_is_reused() {
        use std::sync::atomic::{AtomicI64, Ordering};

        let clock = Arc::new(AtomicI64::new(1_000));
        let http = Arc::new(MockHttpTransport::new());
        let ws = Arc::new(MockWsTransport::new());
        let opts = ExchangeOptions::mainnet(crate::MarketType::Spot);
        let reader = Arc::clone(&clock);
        let mut kraken = Kraken::with_credentials(
            Box::new(ArcTransport(Arc::clone(&http))),
            &opts,
            Credentials::new("APIKEY", "c2VjcmV0"),
        )
        .with_ws(Box::new(ArcWs(Arc::clone(&ws))))
        .with_clock(Box::new(move || reader.load(Ordering::Relaxed)));

        let accepted = r#"{"method":"add_order","req_id":1000,"success":true,
            "result":{"order_id":"O123"}}"#;
        http.push_json(
            200,
            r#"{"error":[],"result":{"token":"first","expires":900}}"#,
        );
        ws.push_connection(vec![
            Ok(Some(accepted.to_string())),
            Ok(Some(accepted.to_string())),
        ]);

        kraken
            .place_order_ws(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)))
            .expect("first order");
        clock.store(1_000 + 60_000, Ordering::Relaxed); // one minute later
        kraken
            .place_order_ws(&OrderRequest::limit_buy(symbol(), dec!(1), dec!(100)))
            .expect("second order");

        let token_fetches = http
            .recorded_requests()
            .iter()
            .filter(|request| request.url.contains("/0/private/GetWebSocketsToken"))
            .count();
        assert_eq!(token_fetches, 1, "a live token is not refetched");
    }

    /// 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 (kraken, mock) = client();
        mock.push_response(
            crate::transport::HttpResponse::new(200, r#"{"error":["EAPI:Rate limit exceeded"]}"#)
                .with_header("Retry-After", "2.5"),
        );
        let err = kraken.ticker(&symbol()).unwrap_err();
        let wait = std::time::Duration::from_millis(2500);
        assert!(matches!(err, Error::RateLimited { retry_after: Some(d) } if d == wait));
    }
}