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
// Native Rust — hand-written client for the CCXT order-router service.
//
// This is the SIXTH port of a class that is hand-written, not transpiled: the
// TypeScript reference lives in `ts/src/base/OrderRouter.ts`, and Python, PHP,
// C# and Go carry line-for-line siblings. They are held together by one shared
// fixture, `ts/src/test/base/fixtures/orderRouter.json`, which every port runs.
// A change to any of them that this port does not match fails that fixture, in
// this language, which is the entire point of writing it out again rather than
// generating it.
//
// Two things about Rust make the port read differently from its siblings while
// meaning the same thing, and both are load-bearing:
//
// * The other five pass dictionaries of `any`. Here that is `Value`, which is
// the same shape (`Value::Dict(Arc<IndexMap<String, Value>>)`) — so the
// accessors below are genuine equivalents of `numberAt`/`stringAt`/… and
// not a re-design.
// * The other five throw. Here the fallible methods return
// `Result<_, ExchangeError>`. `ExchangeError::kind` carries the same class
// names the other ports throw, so `is("NetworkError")` answers the same
// question `isOutcomeUnknownError` asks there.
use std::borrow::Cow;
use std::collections::BTreeSet;
use std::sync::Arc;
use crate::error::ExchangeError;
use crate::value::{HashMap, Value};
/// Result of a fallible router operation. The error's `kind` matches the
/// exception class the other five ports raise for the same condition.
pub type RouterResult<T> = std::result::Result<T, ExchangeError>;
fn arguments_required(message: &str) -> ExchangeError {
ExchangeError::new("ArgumentsRequired", message)
}
fn bad_request(message: &str) -> ExchangeError {
ExchangeError::new("BadRequest", message)
}
fn exchange_error(message: &str) -> ExchangeError {
ExchangeError::new("ExchangeError", message)
}
fn insufficient_funds(message: &str) -> ExchangeError {
ExchangeError::new("InsufficientFunds", message)
}
/// NO_CAP is the default: this class does not decide how much of your money you
/// may trade. `maxNotionalUsd` is an OPT-IN guardrail — set it and it is honoured
/// exactly, at whatever value you choose; leave it unset and no notional check
/// runs at all.
///
/// It used to be a hard 25 USD ceiling that could be lowered but never raised.
/// That number came from CLAUDE.md §5.5, which governs THIS REPOSITORY'S live
/// tests against real exchanges — not the people using the library. A client that
/// refuses a 30 USD order because its own test suite is cautious is broken as a
/// product.
pub const NO_CAP: f64 = 0.0;
/// Default distance from the expected price at which the limit is placed.
pub const DEFAULT_SLIPPAGE_BPS: f64 = 25.0;
/// Default shortfall ratio at which `reconcile_execution_step` halts.
pub const DEFAULT_RECONCILE_TOLERANCE: f64 = 0.02;
/// How long `retryFailedSteps` waits before re-placing a step the venue rejected.
/// A second is the shortest delay that lets a transient cause clear (a rate limit
/// window, a momentary balance lag) without turning a retry budget into a burst
/// against a venue that just said no.
pub const DEFAULT_RETRY_DELAY_MS: f64 = 1000.0;
/// The float-equality epsilon this class compares with. Not a business
/// tolerance — that is DEFAULT_RECONCILE_TOLERANCE. This one exists so that
/// "the fill matches the request" and "the value sits on the precision grid"
/// survive the last bits of floating-point arithmetic, and it must be the same
/// number in all six ports or a violation fires in one language and not another.
pub const TOLERANCE: f64 = 1e-9;
const DEFAULT_BASE_URL: &str = "https://docs.ccxt.com/router/api";
/// Human-readable text for each safety violation code. Carried in the violation
/// record itself so a caller logging one does not have to keep its own copy of
/// this table — and so all six ports emit the same sentence for the same code.
fn violation_message(code: &str) -> &'static str {
match code {
"empty_plan" => "the plan contains no steps",
"route_unroutable" => "the route carries an unroutableReason and must not be executed",
"partial_fill" => "the route does not fill completely at the requested size",
"unknown_symbol" => "the symbol is not listed on that venue",
"market_mismatch" => "the venue market trades a different pair than the route hop says it does",
"invalid_step" => "the step has a non-positive amount or price, or a side that is neither buy nor sell",
"amount_below_minimum" => "the amount is below the market minimum",
"amount_above_maximum" => "the amount is above the market maximum",
"cost_below_minimum" => "the notional is below the market minimum cost",
"price_out_of_range" => "the limit price falls outside the market price limits",
"notional_unvaluable" => "the step cannot be valued in USD, so the notional cap cannot be enforced",
"notional_exceeds_cap" => "the notional exceeds the per-trade USD cap",
"amount_precision" => "the amount does not sit on the market amount precision",
"price_precision" => "the limit price does not sit on the market price precision",
// The TypeScript reads this table with stringAt(.., code, code): an
// unknown code falls back to the code itself rather than to empty.
other => {
// `other` is a &str borrowed from the caller, but this function
// returns 'static. Every code the class emits is in the table above,
// so the fallback only fires for a code that does not exist yet.
let _ = other;
"unknown_violation"
}
}
}
const DEFAULT_TIMEOUT_MS: f64 = 30000.0;
/// The router accepts at most this many balance entries; the rest are dropped
/// smallest-first and reported.
const MAX_BALANCE_ENTRIES: usize = 64;
/// And at most this many characters in the rendered value.
const MAX_BALANCE_CHARS: usize = 4096;
/// How many executed plan ids the in-process idempotency ledger keeps. 1024 is chosen to
/// be far more executions than any one process performs in the window where a duplicate is
/// plausible (a retry loop, an operator re-running a plan, a redelivered message), while
/// bounding the ledger to a few tens of kilobytes so a router held open for the life of a
/// daemon cannot grow without limit.
///
/// THE TRADEOFF IS REAL AND IS NOT HIDDEN: eviction WEAKENS the guarantee. Once a plan id
/// has been pushed out by 1024 newer executions, re-executing that plan is no longer
/// refused in-process — it will be placed again, orders and all. The guard is therefore
/// "recent duplicates are refused", not "duplicates are impossible". A process that needs
/// the strong promise across restarts or beyond this window needs the durable ledger the
/// Known gaps entry calls for; until then, callers whose plans must never re-execute should
/// key idempotency at the venue themselves (a clientOrderId passed in options.orderParams, on
/// venues that honour one) rather than rely on this instance's memory.
pub const MAX_EXECUTED_PLAN_IDS: usize = 1024;
/// The bounded re-execution ledger: a FIFO queue of plan ids plus a set that answers
/// membership in O(1). Both are private to this type so they can never fall out of step.
#[derive(Debug)]
pub struct ExecutedPlanLedger {
order: std::collections::VecDeque<String>,
seen: std::collections::HashSet<String>,
}
impl ExecutedPlanLedger {
pub fn new() -> Self {
ExecutedPlanLedger {
order: std::collections::VecDeque::new(),
seen: std::collections::HashSet::new(),
}
}
/// A hash lookup, not a scan: the ledger is capped but still up to
/// MAX_EXECUTED_PLAN_IDS long, and this runs on every live execution.
pub fn contains(&self, plan_id: &str) -> bool {
self.seen.contains(plan_id)
}
pub fn len(&self) -> usize {
self.order.len()
}
pub fn is_empty(&self) -> bool {
self.order.is_empty()
}
/// The id at `index` in insertion order, oldest first.
pub fn at(&self, index: usize) -> Option<&String> {
self.order.get(index)
}
/// Records one plan id, evicting the oldest entry when the cap is reached.
pub fn record(&mut self, plan_id: String) {
if self.seen.contains(&plan_id) {
// Already recorded; re-recording it would move it in the FIFO order and let
// a repeatedly re-executed plan keep other ids alive or evict them out of turn.
return;
}
self.seen.insert(plan_id.clone());
self.order.push_back(plan_id);
while self.order.len() > MAX_EXECUTED_PLAN_IDS {
// FIFO: the OLDEST execution is the one whose duplicate is least likely still
// in flight. Evicting it drops the refusal for that plan — see the comment on
// MAX_EXECUTED_PLAN_IDS; this is a bounded memory promise, not a stronger
// idempotency one.
if let Some(evicted) = self.order.pop_front() {
self.seen.remove(&evicted);
}
}
}
}
impl Default for ExecutedPlanLedger {
fn default() -> Self {
Self::new()
}
}
/// The shape of the `onStep` hook: it is handed one event describing a finished
/// step and returns `"halt"` to stop the route. SYNCHRONOUS by design — it sits
/// between orders on the money path, so do no network I/O in it.
///
/// WHY THIS IS A FIELD AND NOT AN OPTIONS KEY, unlike the other five ports.
/// In TypeScript, Python, PHP, C# and Go the hook travels inside `options`,
/// because in those languages a dictionary value can be a function. Rust's
/// `options` is a `Value`, and `Value` is a closed, JSON-shaped enum that
/// derives `Debug`, `Clone` and `PartialEq` and answers `to_json` — none of
/// which a closure can. Adding a `Value::Fn` variant would mean answering
/// "what does it mean for two closures to be equal, and how does one
/// serialise" for every existing Value site in the crate, which is a redesign
/// of the value model to carry an observability callback. So the callback comes
/// in through the ONE side channel that can hold it — a field on the router,
/// set by `set_on_step` — and `call_on_step` still takes `options` so the six
/// implementations read line for line.
pub type OnStepHook = Arc<dyn Fn(&Value) -> String + Send + Sync>;
/// A client for the CCXT order-router service.
pub struct OrderRouter {
api_key: String,
/// Sent as the `User-Agent` header when non-empty, so the router service can
/// attribute traffic to the integration that made it.
user_agent: String,
base_url: String,
timeout_ms: f64,
max_notional_usd: f64,
/// The only clock this class reads. `None` means the real wall clock; a
/// test pins time by setting it. A field rather than an overridable method
/// because `OrderRouter` is a concrete struct, not a trait.
now_ms_override: Option<f64>,
/// In-process idempotency ledger: the identity of every plan this instance
/// has already executed live. Behind a mutex because `execute` takes `&self`.
/// TWO structures for one ledger, in every port: a FIFO deque that fixes the
/// eviction order, and a `HashSet` so the membership test is a hash lookup
/// rather than a scan whose cost grows with the ledger. They live under ONE
/// mutex because they are written and evicted together and must never disagree.
executed_plan_ids: std::sync::Mutex<ExecutedPlanLedger>,
/// The caller's `onStep` hook, or `None`. See `OnStepHook` for why this is a
/// field in this port and an options key in the other five. `execute` takes
/// `&self`, so this is only ever read, never written, during a run.
on_step: Option<OnStepHook>,
// The venues this router trades through, held once instead of passed to every call.
// Rust diverges from the other five ports HERE, and for the same reason it diverges
// on the onStep hook: `Value` is a closed enum and cannot carry a `Box<dyn RouterVenue>`,
// so they cannot arrive through the constructor config. The BEHAVIOUR is identical —
// fetch_route filters and funds on them, execute falls back to them — only the
// installation is a setter.
venues: std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
// The rendered balances string for `venues`, read once and reused. fetch_route is ONE
// HTTP request and must stay that way. Placing an order is what makes balances wrong,
// so a live execute drops it. A Mutex because fetch_route takes &self.
balances_cache: std::sync::Mutex<Option<String>>,
// bumped by every invalidation, so a wallet read that was already in flight when the
// cache was dropped cannot store its now-obsolete snapshot on the way back
balances_generation: std::sync::atomic::AtomicU64,
// Whether this router manages balances at all. TWO decisions used to ride on `venues`:
// where you can trade, and what you hold. The first is a filter - free, and it cannot go
// stale. The second costs an authenticated call per venue and made one bad key enough to
// kill a quote. So the filter is always on and the wallet reads are a mode you ask for.
track_balances: bool,
}
// ---------------------------------------------------------------------------
// container accessors
//
// Every port has these; they exist so the six implementations read line for
// line, and so a missing key is never a language-specific crash.
// ---------------------------------------------------------------------------
/// Plain container read: the field if the container is a dict and the field is
/// present and not null, `None` otherwise. Deliberately NOT `get_value_k`, which
/// also routes shared-order-book meta keys and live-client lookups — this class
/// reads inert JSON structures, and picking up those side effects would make the
/// accessors mean something the other five ports' accessors do not.
fn field<'a>(container: &'a Value, key: &str) -> Option<&'a Value> {
match container.as_map().and_then(|map| map.get(key)) {
Some(Value::Null) | None => None,
found => found,
}
}
impl OrderRouter {
/// The price a step is sent at, derived from `expectedPrice` when the
/// caller gave no `limitPrice`. 0 only when the step has neither field.
///
/// `build_execution_plan` always sets `limitPrice`, but a HAND-BUILT plan
/// need not: the manual documents it as optional, and the "execute your own
/// plans" path is the whole point of `execute` taking a plan rather than a
/// route. Reading it as 0 made every such plan fail three different ways —
/// a blocking `price_out_of_range` from `check_execution_plan_safety`, a
/// `rounded_to_zero` before any strategy branch in `place_step`, and a
/// buy-side balance requirement of `amount * 0` — so the documented example
/// could not place one order. `expectedPrice` is the honest fallback: it is
/// what the caller says the step is worth, and it is already guaranteed
/// positive by the `invalid_step` guard. A caller wanting a tighter or
/// looser bound sets `limitPrice` explicitly.
pub fn step_limit_price(&self, step: &Value) -> f64 {
let limit_price = self.number_at(step, "limitPrice", 0.0);
if limit_price > 0.0 {
return limit_price;
}
self.number_at(step, "expectedPrice", 0.0)
}
/// The step's quote-side value, derived from `amount` and `expectedPrice`
/// when absent.
///
/// Same reasoning as `step_limit_price`, and the same formula
/// `build_execution_plan` uses. Read as 0, a hand-built plan tripped the
/// BLOCKING `cost_below_minimum` on every market declaring a minimum cost.
pub fn step_notional_quote(&self, step: &Value) -> f64 {
let notional_quote = self.number_at(step, "notionalQuote", 0.0);
if notional_quote > 0.0 {
return notional_quote;
}
self.number_at(step, "amount", 0.0) * self.number_at(step, "expectedPrice", 0.0)
}
/// Reads a numeric field, with a default for missing, null and unparseable
/// values.
pub fn number_at(&self, container: &Value, key: &str, default_value: f64) -> f64 {
Self::number_of(field(container, key), default_value)
}
fn number_of(value: Option<&Value>, default_value: f64) -> f64 {
match value {
None | Some(Value::Null) => default_value,
// NaN and the infinities are not numbers this class will act on. An
// infinite tolerance silently disables the halt verdict and an
// infinite rate silently disables the cap, and "the default" is the
// only answer six languages can agree on for either.
Some(Value::Int(n)) => {
let as_float = *n as f64;
if Self::is_finite_number(as_float) { as_float } else { default_value }
}
Some(Value::Float(n)) => {
if Self::is_finite_number(*n) { *n } else { default_value }
}
Some(Value::Str(text)) => Self::parse_number_text(text, default_value),
_ => default_value,
}
}
/// Reports whether a double is a real number, i.e. neither NaN nor an
/// infinity.
pub fn is_finite_number(value: f64) -> bool {
// DIVERGENCE, and the only one in this method. The other five ports
// write `value !== value`, which their comment calls "the one NaN test
// that needs no library" — in Rust that is clippy::eq_op, denied by
// default, and CI compiles with it fatal. `is_nan()` is the identical
// predicate; only the spelling differs.
if value.is_nan() {
return false;
}
if value > 1.7976931348623157e308 || value < -1.7976931348623157e308 {
return false;
}
true
}
/// Reads the leading numeric prefix of a string exactly as JavaScript's
/// `parseFloat` does, returning the default when there is not one or when
/// the result is not finite.
pub fn parse_number(&self, text: &str, default_value: f64) -> f64 {
Self::parse_number_text(text, default_value)
}
fn parse_number_text(text: &str, default_value: f64) -> f64 {
// Hand-rolled rather than delegated to the language's own parser,
// because every language's own parser disagrees with the others
// somewhere: Python reads '1_000' as 1000 and '1,234.5' not at all, PHP
// and Go read '0x10' as 0 only by accident of their regex, C# trims
// Unicode whitespace JavaScript does not, and Rust's own `f64::from_str`
// accepts "inf"/"NaN" and rejects any trailing text at all. The grammar
// below is JavaScript's StrDecimalLiteral prefix over the ASCII
// whitespace set, and it is the SAME twenty lines in all six ports.
//
// Indexed over BYTES, not chars: every character the grammar accepts is
// ASCII, and a multi-byte character can only ever end the scan.
let bytes = text.as_bytes();
let mut cursor = 0usize;
while cursor < bytes.len() && Self::is_router_space(bytes[cursor]) {
cursor += 1;
}
let start = cursor;
if cursor < bytes.len() && (bytes[cursor] == b'+' || bytes[cursor] == b'-') {
cursor += 1;
}
let mut digits = 0usize;
while cursor < bytes.len() && bytes[cursor].is_ascii_digit() {
cursor += 1;
digits += 1;
}
if cursor < bytes.len() && bytes[cursor] == b'.' {
cursor += 1;
while cursor < bytes.len() && bytes[cursor].is_ascii_digit() {
cursor += 1;
digits += 1;
}
}
if digits == 0 {
// 'Infinity', 'inf', 'NaN', '' and '٠١' all land here, in all six.
return default_value;
}
let mut end = cursor;
if cursor < bytes.len() && (bytes[cursor] == b'e' || bytes[cursor] == b'E') {
let mut exponent = cursor + 1;
if exponent < bytes.len() && (bytes[exponent] == b'+' || bytes[exponent] == b'-') {
exponent += 1;
}
let mut exponent_digits = 0usize;
while exponent < bytes.len() && bytes[exponent].is_ascii_digit() {
exponent += 1;
exponent_digits += 1;
}
if exponent_digits > 0 {
// A trailing 'e' with no digits is not part of the number: JS
// reads '1e' as 1, and so does every port here.
end = exponent;
}
}
let slice = &text[start..end];
match slice.parse::<f64>() {
// '1e400' overflows to an infinity, which is not a number the cap or
// the tolerance may be built out of.
Ok(parsed) if Self::is_finite_number(parsed) => parsed,
_ => default_value,
}
}
/// Reports whether a byte is one of the six ASCII spaces the number grammar
/// skips.
fn is_router_space(character: u8) -> bool {
// Deliberately NOT the language's own is_whitespace: Python, PHP, C#,
// Go and Rust each draw the Unicode line in a different place, and a
// non-breaking space that parses in one language and not the others is
// drift.
character == b' '
|| character == b'\t'
|| character == b'\n'
|| character == b'\r'
|| character == 0x0c
|| character == 0x0b
}
/// Reads a string field, with a default for missing and null values.
pub fn string_at(&self, container: &Value, key: &str, default_value: &str) -> String {
match field(container, key) {
Some(Value::Str(text)) => text.to_string(),
_ => default_value.to_string(),
}
}
/// Reads a boolean field, with a default for missing and null values.
/// Whether the key holds the boolean `true` and nothing else. A config that
/// stringifies its booleans must not silently stop trading, so `"true"` is NOT true here.
pub fn is_exactly_true(&self, container: &Value, key: &str) -> bool {
matches!(field(container, key), Some(Value::Bool(true)))
}
pub fn bool_at(&self, container: &Value, key: &str, default_value: bool) -> bool {
match field(container, key) {
Some(Value::Bool(flag)) => *flag,
_ => default_value,
}
}
/// Reads an array field, returning an empty vector when absent. Never None,
/// for the same reason `listAt` never returns undefined.
pub fn list_at(&self, container: &Value, key: &str) -> Vec<Value> {
match field(container, key) {
Some(Value::Arr(items)) => items.as_ref().clone(),
_ => Vec::new(),
}
}
/// Reads a nested dictionary, returning an empty one when absent.
pub fn dict_at(&self, container: &Value, key: &str) -> Value {
match field(container, key) {
Some(Value::Dict(map)) => Value::Dict(Arc::clone(map)),
_ => Value::Map(HashMap::new()),
}
}
/// Formats a double as decimal text with no exponent, so that six languages
/// produce the same string.
pub fn format_number(&self, value: f64) -> RouterResult<String> {
// JavaScript prints 1e-7 where Python prints 1e-07 and Go prints 1e-07;
// a fixed 12-decimal rendering with the trailing zeros trimmed is the
// one spelling all six languages agree on for the magnitudes a balance
// or an amount can take.
if !Self::is_finite_number(value) {
return Ok("0".to_string());
}
if value.abs() >= 1e18 {
// JavaScript's toFixed switches to exponent notation at 1e21 while
// the other languages never do. Rather than let one language send a
// different string than the others, refuse — loudly, and at a
// magnitude no real amount reaches.
return Err(bad_request(
"OrderRouter: a number this large cannot be rendered identically in all six languages",
));
}
let mut text = Self::to_fixed_12(value);
if text.contains('.') {
while text.ends_with('0') {
text.pop();
}
if text.ends_with('.') {
text.pop();
}
}
if text.is_empty() || text == "-" || text == "-0" {
return Ok("0".to_string());
}
Ok(text)
}
/// Renders a finite f64 with exactly twelve decimals, from the exact binary
/// value and under JavaScript's toFixed tie rule.
///
/// The reference is TypeScript, and TypeScript's toFixed is ECMA-262's: the
/// sign is stripped BEFORE the digits are chosen, so a tie rounds AWAY FROM
/// ZERO on the magnitude and (-0.0001220703125).toFixed(12) is
/// -0.000122070313, not -...312. Rust's `{:.12}` rounds half to EVEN and
/// would answer ...312, so the balances query string this feeds would differ
/// per language on every value landing exactly on a half tick — 2^-13
/// included.
///
/// `{:.53}` is EXACT for every double whose expansion reaches the twelfth
/// decimal: a double is m * 2^-k and its expansion terminates at digit k, so
/// k <= 53 (|value| >= 2^-53) renders with no rounding at all, and anything
/// smaller is below 1e-16 — its digits 13 and 14 are both 0, so no carry
/// from digit 53 can reach the digit this rounds on.
fn to_fixed_12(value: f64) -> String {
let negative = value < 0.0;
// abs() rather than a negation, so a negative zero renders WITHOUT a
// sign: the digit walk below assumes every byte it reads is a digit.
let magnitude = value.abs();
let rendered = format!("{magnitude:.53}");
let dot = match rendered.find('.') {
Some(index) => index,
None => return rendered,
};
let mut integer_length = dot;
let digits: Vec<u8> = rendered
.bytes()
.filter(|byte| *byte != b'.')
.collect();
let keep = integer_length + 12;
// round half UP on the magnitude, reading the thirteenth decimal exactly
let round_up = digits[keep] >= b'5';
let mut kept: Vec<u8> = digits[..keep].to_vec();
if round_up {
let mut carry = 1u8;
let mut index = kept.len();
while index > 0 && carry == 1 {
index -= 1;
let digit = kept[index] - b'0' + carry;
carry = u8::from(digit >= 10);
kept[index] = (digit % 10) + b'0';
}
if carry == 1 {
kept.insert(0, b'1');
integer_length += 1;
}
}
let text = String::from_utf8_lossy(&kept).to_string();
let sign = if negative { "-" } else { "" };
format!("{}{}.{}", sign, &text[..integer_length], &text[integer_length..])
}
}
// ---------------------------------------------------------------------------
// construction
// ---------------------------------------------------------------------------
impl OrderRouter {
/// Creates a client for the CCXT order-router service.
///
/// `config` keys: `apiKey` (optional; the service rate-limits by IP), `baseUrl`, `timeoutMs`,
/// `maxNotionalUsd` (an OPT-IN per-trade USD cap, honoured exactly at
/// whatever value is given; 0 — the default — means NO CAP, and a negative
/// value is refused), `userAgent` (optional `User-Agent` header sent with every
/// router request so the service can attribute traffic, e.g.
/// `ccxt-mcp/1.2.3 (ccxt 4.5.6)`; empty — the default — keeps reqwest's default).
pub fn new(config: &Value) -> RouterResult<Self> {
// Constructed through a temporary so the accessors — which are methods,
// exactly as in the other five ports — are available while reading the
// config that builds the real one.
let reader = OrderRouter {
api_key: String::new(),
user_agent: String::new(),
base_url: String::new(),
timeout_ms: DEFAULT_TIMEOUT_MS,
max_notional_usd: NO_CAP,
now_ms_override: None,
executed_plan_ids: std::sync::Mutex::new(ExecutedPlanLedger::new()),
on_step: None,
venues: std::collections::BTreeMap::new(),
balances_cache: std::sync::Mutex::new(None),
balances_generation: std::sync::atomic::AtomicU64::new(0),
track_balances: false,
};
// The service dropped API keys in favour of per-IP rate limiting, so an empty key is
// the normal case and must not error. A key supplied anyway is CARRIED rather than
// ignored, so the same client works against both servers.
let api_key = reader.string_at(config, "apiKey", "");
let user_agent = reader.string_at(config, "userAgent", "");
let mut base_url = reader.string_at(config, "baseUrl", DEFAULT_BASE_URL);
while base_url.ends_with('/') {
base_url.pop();
}
let timeout_ms = reader.number_at(config, "timeoutMs", DEFAULT_TIMEOUT_MS);
let max_notional_usd = reader.number_at(config, "maxNotionalUsd", NO_CAP);
if max_notional_usd < 0.0 {
// A negative cap is a typo, not a policy, and silently ignoring it
// would leave the caller believing a guardrail is in place.
return Err(bad_request(
"OrderRouter maxNotionalUsd must not be negative; omit it, or pass 0, for no cap",
));
}
// 0 means NO CAP. Any positive value is honoured exactly — it is not
// clamped, because the caller is the one who knows the size of their own
// trade.
Ok(OrderRouter {
api_key,
user_agent,
base_url,
timeout_ms,
max_notional_usd,
now_ms_override: None,
executed_plan_ids: std::sync::Mutex::new(ExecutedPlanLedger::new()),
on_step: None,
venues: std::collections::BTreeMap::new(),
balances_cache: std::sync::Mutex::new(None),
balances_generation: std::sync::atomic::AtomicU64::new(0),
track_balances: false,
})
}
/// Installs the `onStep` hook: called after each step completes and
/// reconciles, never mid-order, with one event describing that step. Return
/// `"halt"` to stop the route cleanly (`haltReason` becomes
/// `halted_by_on_step`); any other value continues. It can only STOP a
/// route, never resume one already halted. Do NO network I/O here — it sits
/// between orders on the money path. A hook that PANICS is recorded as
/// `on_step_hook_failed` and the run continues, because losing the report
/// would destroy the only account of orders that are already live.
pub fn set_on_step(&mut self, hook: OnStepHook) {
self.on_step = Some(hook);
}
/// Installs the venues this router trades through. See the `venues` field for why this
/// is a setter in Rust and a constructor key everywhere else.
pub fn set_venues(&mut self, venues: std::collections::BTreeMap<String, Box<dyn RouterVenue>>) {
self.venues = venues;
}
/// Turns balance tracking on or off. Off (the default), fetch_route never touches a venue
/// and stays a single HTTP request; on, it routes on what you can actually fund.
pub fn set_track_balances(&mut self, track: bool) {
self.track_balances = track;
self.invalidate_balances();
}
/// Removes the stored venues, so fetch_route stops filtering and funding on them.
pub fn clear_venues(&mut self) {
self.venues = std::collections::BTreeMap::new();
}
/// The venues this router holds, empty when none were installed.
pub fn venues(&self) -> &std::collections::BTreeMap<String, Box<dyn RouterVenue>> {
&self.venues
}
/// Removes the `onStep` hook.
pub fn clear_on_step(&mut self) {
self.on_step = None;
}
/// Reports whether this instance has executed the given plan id recently enough for
/// the bounded ledger to still remember it.
pub fn has_executed_plan(&self, plan_id: &str) -> bool {
self.executed_plan_ids.lock().unwrap().contains(plan_id)
}
/// Records one plan id in the bounded ledger, evicting the oldest entry when full.
pub fn record_executed_plan(&self, plan_id: &str) {
self.executed_plan_ids.lock().unwrap().record(plan_id.to_string());
}
/// How many plan ids the ledger currently holds, and the id at one position in
/// insertion order. Both exist so the self-test can assert the bound and the
/// eviction order without reaching through the mutex itself.
pub fn executed_plan_count(&self) -> usize {
self.executed_plan_ids.lock().unwrap().len()
}
pub fn executed_plan_at(&self, index: usize) -> String {
let ledger = self.executed_plan_ids.lock().unwrap();
match ledger.at(index) {
Some(entry) => entry.clone(),
None => String::new(),
}
}
/// Pins the clock, for tests. Production never calls this.
pub fn set_now_ms(&mut self, now_ms: f64) {
self.now_ms_override = Some(now_ms);
}
/// The only clock this class reads.
fn now_ms(&self) -> f64 {
match self.now_ms_override {
Some(pinned) => pinned,
None => std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis() as f64)
.unwrap_or(0.0),
}
}
/// The per-trade USD notional cap this client will enforce, or `NO_CAP` when
/// the caller never asked for one.
pub fn max_notional_usd(&self) -> f64 {
self.max_notional_usd
}
/// The api key this client carries, empty when it has none. The service is
/// public and needs no key; one supplied anyway is sent as `x-api-key`, so a
/// deployment fronting the router with its own authentication still works.
pub fn api_key(&self) -> &str {
&self.api_key
}
/// The User-Agent this client sends, empty when it keeps the http client's default.
pub fn user_agent(&self) -> &str {
&self.user_agent
}
/// The router base url, with any trailing slashes removed.
pub fn base_url(&self) -> &str {
&self.base_url
}
/// The configured request timeout, in milliseconds.
pub fn timeout_ms(&self) -> f64 {
self.timeout_ms
}
}
// ---------------------------------------------------------------------------
// PURE: build_execution_plan
// ---------------------------------------------------------------------------
impl OrderRouter {
/// Refuses a route whose hops do not connect, or that does not run from the
/// asset the caller offered to the asset the caller wanted.
///
/// `build_execution_plan` used to copy `from`, `to`, `pair` and `side`
/// straight out of the server's JSON, and the safety checks only tested
/// internal consistency against whatever market that named — so a
/// compromised, or simply buggy, router response could steer real orders
/// into any real market and every check would pass it, under the 25 USD cap.
pub fn assert_route_chain_is_coherent(&self, route: &Value, hops: &[Value]) -> RouterResult<()> {
if hops.is_empty() {
return Ok(());
}
let mut carried = String::new();
for (index, hop) in hops.iter().enumerate() {
let side = self.string_at(hop, "side", "").to_lowercase();
let base_code = self.string_at(hop, "base", "").to_uppercase();
let quote = self.string_at(hop, "quote", "").to_uppercase();
if base_code.is_empty() || quote.is_empty() || (side != "buy" && side != "sell") {
return Err(exchange_error(&format!(
"OrderRouter: hop {index} does not name a market and a side"
)));
}
// A buy spends the quote to acquire the base; a sell is the reverse.
let spends = if side == "buy" { quote.clone() } else { base_code.clone() };
let produces = if side == "buy" { base_code } else { quote };
if index > 0 && spends != carried {
// Hop N+1 must spend exactly what hop N produced, or the plan
// strands the proceeds of one order and funds the next from a
// wallet nobody checked.
return Err(exchange_error(&format!(
"OrderRouter: hop {index} spends {spends} but the previous hop produced {carried}"
)));
}
if index == 0 {
let requested_from = self.string_at(route, "clientRequestedFrom", "");
if !requested_from.is_empty() && spends != requested_from {
return Err(exchange_error(&format!(
"OrderRouter: the route spends {spends}, not the requested {requested_from}"
)));
}
}
carried = produces;
}
let requested_to = self.string_at(route, "clientRequestedTo", "");
if !requested_to.is_empty() && carried != requested_to {
return Err(exchange_error(&format!(
"OrderRouter: the route produces {carried}, not the requested {requested_to}"
)));
}
Ok(())
}
/// Turns a RouteResult into an ordered list of concrete orders. PURE — no
/// I/O, and the same input produces the same output in all six languages.
///
/// `options` keys: `slippageBps` (default 25) and `reconcileToleranceRatio`
/// (default 0.02).
pub fn build_execution_plan(&self, route: &Value, options: &Value) -> RouterResult<Value> {
let slippage_bps = self.number_at(options, "slippageBps", DEFAULT_SLIPPAGE_BPS);
let tolerance = self.number_at(options, "reconcileToleranceRatio", DEFAULT_RECONCILE_TOLERANCE);
let hops = self.list_at(route, "hops");
self.assert_route_chain_is_coherent(route, &hops)?;
let mut steps: Vec<Value> = Vec::new();
let mut step_index = 0i64;
for (hop_index, hop) in hops.iter().enumerate() {
let symbol = self.string_at(hop, "pair", "");
let side = self.string_at(hop, "side", "");
let base_code = self.string_at(hop, "base", "");
let quote = self.string_at(hop, "quote", "");
let legs = self.list_at(hop, "legs");
for (leg_index, leg) in legs.iter().enumerate() {
// Leg amounts are always in BASE units, on both sides of the
// market — see the router's RoutingQuote.filledAmount contract.
let amount = self.number_at(leg, "amount", 0.0);
let expected_price = self.number_at(leg, "averagePrice", 0.0);
let effective_price = self.number_at(leg, "effectivePrice", expected_price);
// The limit sits on the side that costs you: above for a buy,
// below for a sell.
let limit_price = if side == "buy" {
expected_price * (1.0 + slippage_bps / 10000.0)
} else {
expected_price * (1.0 - slippage_bps / 10000.0)
};
let mut step = HashMap::new();
step.insert("stepIndex".into(), Value::Float(step_index as f64));
step.insert("hopIndex".into(), Value::Float(hop_index as f64));
step.insert("legIndex".into(), Value::Float(leg_index as f64));
step.insert("exchangeId".into(), Value::Str(self.string_at(leg, "exchangeId", "").into()));
step.insert("symbol".into(), Value::Str(symbol.clone().into()));
step.insert("side".into(), Value::Str(side.clone().into()));
step.insert("base".into(), Value::Str(base_code.clone().into()));
step.insert("quote".into(), Value::Str(quote.clone().into()));
step.insert("amount".into(), Value::Float(amount));
step.insert("expectedPrice".into(), Value::Float(expected_price));
step.insert("effectivePrice".into(), Value::Float(effective_price));
step.insert("limitPrice".into(), Value::Float(limit_price));
step.insert("notionalQuote".into(), Value::Float(amount * expected_price));
// The taker fee the ROUTER predicted for this leg, always denominated in
// the quote currency (the service's own RouteLeg.feeCost contract). Carried
// so step_expected_out can measure the expectation the same way execute
// measures the realised amount — see the note there. 0 on a hand-built plan,
// which is exactly the old behaviour.
step.insert(
"expectedFeeCost".into(),
Value::Float(self.number_at(leg, "feeCost", 0.0)),
);
// This leg was cut short by the WALLET, not by the book: more was on offer,
// the balances just could not pay for it. Size-capped and depth-capped look
// identical in the numbers and need different follow-up.
step.insert(
"balanceLimited".into(),
Value::Bool(self.bool_at(leg, "balanceLimited", false)),
);
steps.push(Value::Map(step));
step_index += 1;
}
}
let mut plan = HashMap::new();
plan.insert("requestId".into(), Value::Str(self.string_at(route, "requestId", "").into()));
plan.insert("calculatedAt".into(), Value::Float(self.number_at(route, "calculatedAt", 0.0)));
plan.insert("from".into(), Value::Str(self.string_at(route, "from", "").into()));
plan.insert("to".into(), Value::Str(self.string_at(route, "to", "").into()));
plan.insert("routingStrategy".into(), Value::Str(self.string_at(route, "strategy", "").into()));
plan.insert("exactSide".into(), Value::Str(self.string_at(route, "exactSide", "").into()));
plan.insert("amountIn".into(), Value::Float(self.number_at(route, "amountIn", 0.0)));
plan.insert("amountOut".into(), Value::Float(self.number_at(route, "amountOut", 0.0)));
plan.insert("fullyFillable".into(), Value::Bool(self.bool_at(route, "fullyFillable", false)));
plan.insert("fillRatio".into(), Value::Float(self.number_at(route, "fillRatio", 0.0)));
plan.insert("unroutableReason".into(), Value::Str(self.string_at(route, "unroutableReason", "").into()));
// WHICH hop could not be solved. -1 when the route is routable or the server did not
// say; 0 is a real answer and must not read as "unknown".
plan.insert(
"unroutableHopIndex".into(),
Value::Float(self.number_at(route, "unroutableHopIndex", -1.0)),
);
// What the CALLER asked for, stamped by fetch_route — not the server's echo.
plan.insert(
"requireFullFill".into(),
Value::Bool(self.bool_at(route, "clientRequestedRequireFullFill", false)),
);
plan.insert("hopCount".into(), Value::Float(hops.len() as f64));
plan.insert("stepCount".into(), Value::Float(steps.len() as f64));
plan.insert("slippageBps".into(), Value::Float(slippage_bps));
plan.insert("reconcileToleranceRatio".into(), Value::Float(tolerance));
plan.insert("steps".into(), Value::List(steps));
Ok(Value::Map(plan))
}
}
// ---------------------------------------------------------------------------
// the venue abstraction
// ---------------------------------------------------------------------------
/// What `execute` needs from an exchange, and nothing more.
///
/// The other five ports hand `execute` their language's exchange object
/// directly. Rust cannot: `ExchangeBase`'s methods return `impl Future`, which
/// is not object-safe, so a `HashMap<String, Box<dyn ExchangeBase>>` — the
/// shape every other port uses for `venues` — cannot exist. This trait is that
/// shape, narrowed to the operations the money path actually performs, and it
/// is what makes the venues map possible here at all.
///
/// It also buys something the other ports get for free from dynamic typing: a
/// test can implement this in twenty lines, so the execute-path invariants are
/// testable without a live exchange.
#[async_trait::async_trait]
pub trait RouterVenue: Send + Sync {
/// The venue's ccxt id, e.g. `binance`. Matched against a step's
/// `exchangeId`.
fn id(&self) -> String;
/// Snaps an amount to the market's precision, as text — the same contract
/// as ccxt's `amountToPrecision`.
fn amount_to_precision(&self, symbol: &str, amount: f64) -> String;
/// Snaps a price to the market's precision, as text.
fn price_to_precision(&self, symbol: &str, price: f64) -> String;
/// Whether this venue accepts an immediate-or-cancel time-in-force on a
/// limit order. A venue that does not gets a market order only when the
/// caller has explicitly opted in — see `execute`.
fn supports_ioc(&self) -> bool;
/// Places an order. `params` carries the time-in-force and any caller
/// extras.
async fn create_order(
&self,
symbol: &str,
order_type: &str,
side: &str,
amount: f64,
price: f64,
params: &Value,
) -> RouterResult<Value>;
/// Reads an order back. Used to re-read a venue that answered without a
/// `filled`, rather than assuming one.
async fn fetch_order(&self, id: &str, symbol: &str) -> RouterResult<Value>;
/// Cancels an order. Used by the protected-limit path when the poll expires.
async fn cancel_order(&self, id: &str, symbol: &str) -> RouterResult<Value>;
/// Reads the account's holdings, in ccxt's balance shape — `free` and
/// `total` maps of currency code to amount. Only `fetch_route_with_balances`
/// calls this; a venue used solely with `execute` can return an empty map.
async fn fetch_balance(&self) -> RouterResult<Value> {
Ok(Value::Map(HashMap::new()))
}
}
// ---------------------------------------------------------------------------
// PURE: check_execution_plan_safety
// ---------------------------------------------------------------------------
impl OrderRouter {
/// Builds one safety violation record.
fn violation(
&self,
step_index: f64,
exchange_id: &str,
symbol: &str,
code: &str,
blocking: bool,
actual: f64,
limit: f64,
) -> Value {
let mut entry = HashMap::new();
entry.insert("stepIndex".into(), Value::Float(step_index));
entry.insert("exchangeId".into(), Value::Str(exchange_id.to_string().into()));
entry.insert("symbol".into(), Value::Str(symbol.to_string().into()));
entry.insert("code".into(), Value::Str(code.to_string().into()));
entry.insert("blocking".into(), Value::Bool(blocking));
entry.insert("actual".into(), Value::Float(actual));
entry.insert("limit".into(), Value::Float(limit));
entry.insert("message".into(), Value::Str(violation_message(code).to_string().into()));
Value::Map(entry)
}
/// Resolves the USD price of a currency, treating USD itself as 1 and
/// assuming nothing about anything else.
fn usd_rate_for(&self, code: &str, usd_rates: &Value) -> f64 {
if code.is_empty() {
return 0.0;
}
if code == "USD" {
return 1.0;
}
// USDT and USDC are NOT assumed to be one dollar. A stablecoin peg is an
// empirical fact, not a definition, and the caller supplying rates is
// the one who knows today's.
let rate = self.number_at(usd_rates, code, 0.0);
if rate > 0.0 {
return rate;
}
0.0
}
/// The USD value of a step's notional, quote side first and base side as
/// the fallback — `amount * usd(base)` values the same trade.
fn notional_usd(&self, step: &Value, notional_quote: f64, usd_rates: &Value) -> f64 {
let quote = self.string_at(step, "quote", "");
let quote_rate = self.usd_rate_for("e, usd_rates);
if quote_rate > 0.0 {
return notional_quote * quote_rate;
}
let base_code = self.string_at(step, "base", "");
let base_rate = self.usd_rate_for(&base_code, usd_rates);
if base_rate > 0.0 {
return self.number_at(step, "amount", 0.0) * base_rate;
}
0.0
}
/// Reports whether a value fails to sit on a market's precision grid.
fn precision_violated(&self, value: f64, precision: f64, mode: &str) -> bool {
if precision <= 0.0 {
// Unknown or unconstrained precision is not a finding.
return false;
}
let rounded = if mode == "decimal_places" {
let factor = 10f64.powf(precision);
(value * factor).round() / factor
} else {
// The rounding mode is irrelevant here: a value exactly halfway
// between two ticks is off-grid whichever neighbour it snaps to, so
// the six languages' differing round() semantics cannot change this
// predicate's answer.
(value / precision).round() * precision
};
let allowed = value.abs() * TOLERANCE + 1e-15;
(rounded - value).abs() > allowed
}
/// Checks a plan against per-venue market rules and the hard per-trade USD
/// notional cap. PURE — no I/O. A step that cannot be valued in USD BLOCKS;
/// it is never skipped, because a cap that silently disappears when a rate
/// is missing is not a cap.
///
/// `markets` is `markets[exchangeId][symbol]`.
pub fn check_execution_plan_safety(
&self,
plan: &Value,
markets: &Value,
options: &Value,
) -> Vec<Value> {
let mut violations: Vec<Value> = Vec::new();
// Honoured exactly as given, per call or per client. No clamping: a
// caller trading thousands and a caller trading cents are both using
// this correctly.
let max_notional_usd = self.number_at(options, "maxNotionalUsd", self.max_notional_usd);
let cap_in_force = max_notional_usd > 0.0;
let usd_rates = self.dict_at(options, "usdRates");
let precision_mode = self.string_at(options, "precisionMode", "tick_size");
let steps = self.list_at(plan, "steps");
if steps.is_empty() {
// An empty plan passing an empty violation list would read as "safe".
violations.push(self.violation(-1.0, "", "", "empty_plan", true, 0.0, 0.0));
return violations;
}
let unroutable_reason = self.string_at(plan, "unroutableReason", "");
if !unroutable_reason.is_empty() {
violations.push(self.violation(-1.0, "", "", "route_unroutable", true, 0.0, 0.0));
}
if !self.bool_at(plan, "fullyFillable", false) {
violations.push(self.violation(
// BLOCKING when the caller asked for requireFullFill. That parameter is
// the one route flag that fails OPEN: a partial route in the same breath as
// the flag means the flag did not survive the trip.
-1.0,
"",
"",
"partial_fill",
self.bool_at(plan, "requireFullFill", false),
self.number_at(plan, "fillRatio", 0.0),
1.0,
));
}
for (i, step) in steps.iter().enumerate() {
let step_index = self.number_at(step, "stepIndex", i as f64);
let exchange_id = self.string_at(step, "exchangeId", "");
let symbol = self.string_at(step, "symbol", "");
let amount = self.number_at(step, "amount", 0.0);
let expected_price = self.number_at(step, "expectedPrice", 0.0);
let limit_price = self.step_limit_price(step);
let notional_quote = self.step_notional_quote(step);
let side = self.string_at(step, "side", "");
if amount <= 0.0 || expected_price <= 0.0 || (side != "buy" && side != "sell") {
violations.push(self.violation(
step_index, &exchange_id, &symbol, "invalid_step", true, amount, 0.0,
));
continue;
}
let venue_markets = self.dict_at(markets, &exchange_id);
let market = self.dict_at(&venue_markets, &symbol);
if market.as_map().map(|m| m.is_empty()).unwrap_or(true) {
violations.push(self.violation(
step_index, &exchange_id, &symbol, "unknown_symbol", true, 0.0, 0.0,
));
continue;
}
// The same symbol string on a different venue is not necessarily the
// same pair, and the USD valuation below trusts the step's quote
// currency — so disagreement is fatal, not cosmetic.
let market_base = self.string_at(&market, "base", "");
let market_quote = self.string_at(&market, "quote", "");
let step_base = self.string_at(step, "base", "");
let step_quote = self.string_at(step, "quote", "");
let base_disagrees =
!market_base.is_empty() && !step_base.is_empty() && market_base != step_base;
let quote_disagrees =
!market_quote.is_empty() && !step_quote.is_empty() && market_quote != step_quote;
if base_disagrees || quote_disagrees {
violations.push(self.violation(
step_index, &exchange_id, &symbol, "market_mismatch", true, 0.0, 0.0,
));
continue;
}
let limits = self.dict_at(&market, "limits");
let amount_limits = self.dict_at(&limits, "amount");
let price_limits = self.dict_at(&limits, "price");
let cost_limits = self.dict_at(&limits, "cost");
let min_amount = self.number_at(&amount_limits, "min", 0.0);
let max_amount = self.number_at(&amount_limits, "max", 0.0);
let min_price = self.number_at(&price_limits, "min", 0.0);
let max_price = self.number_at(&price_limits, "max", 0.0);
let min_cost = self.number_at(&cost_limits, "min", 0.0);
if min_amount > 0.0 && amount < min_amount {
violations.push(self.violation(
step_index, &exchange_id, &symbol, "amount_below_minimum", true, amount, min_amount,
));
}
if max_amount > 0.0 && amount > max_amount {
violations.push(self.violation(
step_index, &exchange_id, &symbol, "amount_above_maximum", true, amount, max_amount,
));
}
if min_cost > 0.0 && notional_quote < min_cost {
violations.push(self.violation(
step_index, &exchange_id, &symbol, "cost_below_minimum", true, notional_quote, min_cost,
));
}
if (min_price > 0.0 && limit_price < min_price)
|| (max_price > 0.0 && limit_price > max_price)
{
let bound = if limit_price < min_price { min_price } else { max_price };
violations.push(self.violation(
step_index, &exchange_id, &symbol, "price_out_of_range", true, limit_price, bound,
));
}
let precision = self.dict_at(&market, "precision");
let amount_precision = self.number_at(&precision, "amount", 0.0);
let price_precision = self.number_at(&precision, "price", 0.0);
// Precision findings are advisory: execute() snaps through the
// venue's own amountToPrecision/priceToPrecision before sending.
if self.precision_violated(amount, amount_precision, &precision_mode) {
violations.push(self.violation(
step_index, &exchange_id, &symbol, "amount_precision", false, amount, amount_precision,
));
}
if self.precision_violated(limit_price, price_precision, &precision_mode) {
violations.push(self.violation(
step_index, &exchange_id, &symbol, "price_precision", false, limit_price, price_precision,
));
}
// The notional cap. The worst case is the higher of the expected and
// the limit price, which is the buy side; a sell's limit sits below,
// so its expected price is the one that governs.
let mut worst_price = expected_price;
if limit_price > worst_price {
worst_price = limit_price;
}
if cap_in_force {
// Only when a cap is actually set. With no cap there is nothing
// to enforce, so a missing USD rate is not an error and the
// caller is not made to supply usdRates for a check they did not
// ask for.
let worst_notional = amount * worst_price;
let usd_value = self.notional_usd(step, worst_notional, &usd_rates);
if usd_value <= 0.0 {
// BLOCKING, and deliberately so. Skipping the cap for a step
// whose USD value is unknown defeats the cap the caller DID
// ask for.
violations.push(self.violation(
step_index, &exchange_id, &symbol, "notional_unvaluable", true,
worst_notional, max_notional_usd,
));
} else if usd_value > max_notional_usd * (1.0 + TOLERANCE) {
violations.push(self.violation(
step_index, &exchange_id, &symbol, "notional_exceeds_cap", true, usd_value,
max_notional_usd,
));
}
}
}
violations
}
}
// ---------------------------------------------------------------------------
// PURE: reconcile_execution_step
// ---------------------------------------------------------------------------
impl OrderRouter {
/// How much of its output asset a step is expected to produce, gross of
/// fees: base units for a buy, quote units for a sell.
pub fn step_expected_out(&self, step: &Value) -> f64 {
let amount = self.number_at(step, "amount", 0.0);
if self.string_at(step, "side", "") == "buy" {
// A buy produces BASE, and the router's predicted fee is quote-denominated,
// so it does not reduce what this step hands to the next one. A venue that
// charges its buy fee in the base asset really does deliver less, and the
// resize that follows from it is correct.
return amount;
}
// A SELL produces QUOTE, which is the currency the predicted fee is already in.
//
// This subtraction is what stops the fee being counted TWICE. execute reports
// realisedOut net of a fee charged in the asset the step produced, because that
// is what the wallet actually receives. The router, in turn, already sized the
// next hop from its own NET figure: in the shared fixture, hop 0 sells 500 DOGE
// at 0.089 for 44.5 gross, reports amountOut 44.47482324238088 after a
// 0.025176757619121304 USDT fee, and hop 1's amountIn is that net number to the
// last digit. Measuring the expectation gross against a realised amount that is
// net therefore reported a shortfall on a PERFECT fill and shrank the next hop by
// the fee a second time, stranding it in the bridge asset.
//
// Gross stays gross where gross is right: notionalQuote is what the order is
// worth to the venue and is untouched, as is the notional cap built on it.
let gross = amount * self.number_at(step, "expectedPrice", 0.0);
let expected_fee = self.number_at(step, "expectedFeeCost", 0.0);
if expected_fee <= 0.0 || expected_fee >= gross {
// a fee at or above the whole proceeds is not a fee this class will
// subtract: it would report an expectation of zero or less and turn every
// fill into a halt
return gross;
}
gross - expected_fee
}
/// Reports whether a field holds a usable number, as opposed to holding
/// zero or nothing at all.
///
/// "The venue said zero" and "the venue said nothing" are different facts
/// and used to produce the same number. Reuses `number_of` rather than
/// re-deriving the coercion: "the value is usable" and "the value is
/// present" must never disagree, and two copies of that rule is how they
/// would.
pub fn has_number_at(&self, container: &Value, key: &str) -> bool {
let probe = Self::number_of(field(container, key), f64::NAN);
Self::is_finite_number(probe)
}
/// Compares what a step actually produced against what the route predicted,
/// resizes every downstream hop, and returns the proceed-or-halt verdict.
/// PURE — no I/O.
///
/// The halt decision lives here rather than in the execution loop because it
/// is a money decision, and six separate loops is six chances to omit it.
pub fn reconcile_execution_step(
&self,
plan: &Value,
step_index: i64,
realised_out: f64,
) -> RouterResult<Value> {
let steps = self.list_at(plan, "steps");
if step_index < 0 || step_index as usize >= steps.len() {
return Err(bad_request("reconcileExecutionStep: stepIndex is out of range"));
}
let step = &steps[step_index as usize];
let hop_index = self.number_at(step, "hopIndex", 0.0);
let tolerance =
self.number_at(plan, "reconcileToleranceRatio", DEFAULT_RECONCILE_TOLERANCE);
let expected_out = self.step_expected_out(step);
let mut resized: Vec<Value> = Vec::new();
if expected_out <= 0.0 {
let mut verdict = HashMap::new();
verdict.insert("stepIndex".into(), Value::Float(step_index as f64));
verdict.insert("hopIndex".into(), Value::Float(hop_index));
verdict.insert("expectedOut".into(), Value::Float(0.0));
verdict.insert("realisedOut".into(), Value::Float(realised_out));
verdict.insert("shortfall".into(), Value::Float(0.0));
verdict.insert("shortfallRatio".into(), Value::Float(0.0));
verdict.insert("scale".into(), Value::Float(0.0));
verdict.insert("verdict".into(), Value::Str("halt".into()));
verdict.insert("reason".into(), Value::Str("zero_expected_output".into()));
verdict.insert("resizedSteps".into(), Value::List(resized));
return Ok(Value::Map(verdict));
}
let mut shortfall = expected_out - realised_out;
if shortfall < 0.0 {
shortfall = 0.0;
}
let shortfall_ratio = shortfall / expected_out;
// The downstream hops lost `shortfall` out of this hop's whole output,
// not out of this leg's, so the scale is measured against the hop.
let mut hop_expected_out = 0.0f64;
// Shortfall already reported by this hop's OTHER legs. Each leg used to
// compute a scale from the hop total and multiply the downstream amounts
// by it, so a second leg scaled an already-scaled number: 80% and 60%
// fills produced 0.9 x 0.8 = 0.72 of the next hop instead of the true
// 0.70, sizing it for more than the wallet actually received and
// inviting a spurious insufficient-funds halt on exactly the bridged
// routes this class exists for. Reproduced at 144 against a true 140
// before this changed.
let mut prior_shortfall = 0.0f64;
for other in steps.iter() {
if self.number_at(other, "hopIndex", 0.0) == hop_index {
hop_expected_out += self.step_expected_out(other);
if self.number_at(other, "stepIndex", -1.0) != step_index as f64
&& self.has_number_at(other, "realisedOut")
{
let mut leg_shortfall =
self.step_expected_out(other) - self.number_at(other, "realisedOut", 0.0);
if leg_shortfall < 0.0 {
leg_shortfall = 0.0;
}
prior_shortfall += leg_shortfall;
}
}
}
// scale_before is what the downstream amounts have ALREADY been
// multiplied by, so the factor applied here is the increment that takes
// them from that to the hop's true cumulative scale. With one leg per
// hop prior_shortfall is 0, scale_before is 1, and this is
// arithmetically identical to what it replaced.
let mut scale_before = 1.0f64;
let mut scale_after = 1.0f64;
if hop_expected_out > 0.0 {
scale_before = (hop_expected_out - prior_shortfall) / hop_expected_out;
scale_after = (hop_expected_out - prior_shortfall - shortfall) / hop_expected_out;
}
if scale_before <= 0.0 {
// The hop already produced nothing; there is nothing left to scale
// down.
scale_before = 1.0;
scale_after = 0.0;
}
let mut scale = scale_after / scale_before;
if scale > 1.0 {
// Never scale UP. An overfill is good news, but growing a downstream
// order past the size that passed the safety check would place an
// order nobody ever approved.
scale = 1.0;
}
if scale < 0.0 {
scale = 0.0;
}
for (i, other) in steps.iter().enumerate() {
if self.number_at(other, "hopIndex", 0.0) <= hop_index {
continue;
}
let previous_amount = self.number_at(other, "amount", 0.0);
let amount = previous_amount * scale;
let mut entry = HashMap::new();
entry.insert(
"stepIndex".into(),
Value::Float(self.number_at(other, "stepIndex", i as f64)),
);
entry.insert("previousAmount".into(), Value::Float(previous_amount));
entry.insert("amount".into(), Value::Float(amount));
entry.insert(
"notionalQuote".into(),
Value::Float(amount * self.number_at(other, "expectedPrice", 0.0)),
);
resized.push(Value::Map(entry));
}
let mut verdict_text = "proceed";
let mut reason = "within_tolerance";
if realised_out <= 0.0 {
verdict_text = "halt";
reason = "nothing_filled";
} else if shortfall_ratio > tolerance * (1.0 + TOLERANCE) {
verdict_text = "halt";
reason = "shortfall_exceeds_tolerance";
}
let mut verdict = HashMap::new();
verdict.insert("stepIndex".into(), Value::Float(step_index as f64));
verdict.insert("hopIndex".into(), Value::Float(hop_index));
verdict.insert("expectedOut".into(), Value::Float(expected_out));
verdict.insert("realisedOut".into(), Value::Float(realised_out));
verdict.insert("shortfall".into(), Value::Float(shortfall));
verdict.insert("shortfallRatio".into(), Value::Float(shortfall_ratio));
verdict.insert("scale".into(), Value::Float(scale));
verdict.insert("verdict".into(), Value::Str(verdict_text.into()));
verdict.insert("reason".into(), Value::Str(reason.into()));
verdict.insert("resizedSteps".into(), Value::List(resized));
Ok(Value::Map(verdict))
}
/// Writes a reconciliation's downstream resize back into the working steps.
///
/// Records what this leg actually produced BEFORE resizing anything.
/// `reconcile_execution_step` is pure and cannot remember across calls, so
/// the hop's cumulative shortfall has to live on the steps themselves —
/// this is what stops the next leg of the same hop compounding its scale
/// onto an already-scaled amount.
pub fn apply_resize(&self, steps: &mut [Value], reconciliation: &Value) {
let reconciled_step = self.number_at(reconciliation, "stepIndex", -1.0);
let realised_out = self.number_at(reconciliation, "realisedOut", 0.0);
for step in steps.iter_mut() {
if self.number_at(step, "stepIndex", -1.0) == reconciled_step {
Self::put(step, "realisedOut", Value::Float(realised_out));
break;
}
}
let resized = self.list_at(reconciliation, "resizedSteps");
for entry in &resized {
let target = self.number_at(entry, "stepIndex", -1.0);
let amount = self.number_at(entry, "amount", 0.0);
let notional = self.number_at(entry, "notionalQuote", 0.0);
for step in steps.iter_mut() {
if self.number_at(step, "stepIndex", -1.0) == target {
Self::put(step, "amount", Value::Float(amount));
Self::put(step, "notionalQuote", Value::Float(notional));
break;
}
}
}
}
/// Sets a key on a `Value::Dict` in place, through `Arc::make_mut` so the
/// copy-on-write only deep-copies when the map is actually shared.
///
/// Public because callers building a route by hand need it too — stamping
/// `clientRequestedFrom`/`clientRequestedTo` onto a route obtained by some
/// route other than `fetch_route`, for one. The other five ports get this
/// for free from assignment into a dictionary.
pub fn set_key(container: &mut Value, key: &str, value: Value) {
Self::put(container, key, value)
}
fn put(container: &mut Value, key: &str, value: Value) {
if let Value::Dict(map) = container {
Arc::make_mut(map).insert(key.to_string(), value);
}
}
}
// ---------------------------------------------------------------------------
// PURE: build_unwind_plan
// ---------------------------------------------------------------------------
impl OrderRouter {
/// Accumulates a signed amount into the (exchangeId, asset) position list,
/// appending in first-seen order.
///
/// `produced` is true when this step PRODUCED the asset, which is the only
/// kind of step an unwind can reverse.
fn add_position(
&self,
positions: &mut Vec<Value>,
exchange_id: &str,
asset: &str,
amount: f64,
source: &Value,
produced: bool,
) {
for position in positions.iter_mut() {
let same_venue = self.string_at(position, "exchangeId", "") == exchange_id;
let same_asset = self.string_at(position, "asset", "") == asset;
if same_venue && same_asset {
let running = self.number_at(position, "amount", 0.0) + amount;
Self::put(position, "amount", Value::Float(running));
let existing = self.dict_at(position, "source");
let empty = existing.as_map().map(|m| m.is_empty()).unwrap_or(true);
if produced && empty {
Self::put(position, "source", source.clone());
}
return;
}
}
// The source must be the step that PRODUCED the asset, never one that
// consumed it: reversing a step that spent your USDT would sell the
// wrong side of the wrong market. Walking the results backwards, the
// first producing step seen is the last one that ran, which is exactly
// the order an unwind undoes first.
let initial_source =
if produced { source.clone() } else { Value::Map(HashMap::new()) };
let mut entry = HashMap::new();
entry.insert("exchangeId".into(), Value::Str(exchange_id.to_string().into()));
entry.insert("asset".into(), Value::Str(asset.to_string().into()));
entry.insert("amount".into(), Value::Float(amount));
entry.insert("source".into(), initial_source);
positions.push(Value::Map(entry));
}
/// Given a halted execution report, computes the reverse orders that sell
/// each stranded residual back toward the original from-asset, on the venue
/// that actually holds it. PURE — no I/O.
///
/// NEVER automatic: the result carries `requiresConfirmation` and nothing in
/// this class executes it.
pub fn build_unwind_plan(&self, report: &Value) -> Value {
let from_asset = self.string_at(report, "from", "");
let to_asset = self.string_at(report, "to", "");
let slippage_bps = self.number_at(report, "slippageBps", DEFAULT_SLIPPAGE_BPS);
let results = self.list_at(report, "steps");
// Net position per (exchangeId, asset). Held in a VECTOR rather than a
// map because the output order must be identical in six languages and
// map iteration order is not.
let mut positions: Vec<Value> = Vec::new();
for result in results.iter().rev() {
let exchange_id = self.string_at(result, "exchangeId", "");
let out_asset = self.string_at(result, "outAsset", "");
let out_amount = self.number_at(result, "outAmount", 0.0);
if !out_asset.is_empty() && out_amount > 0.0 {
self.add_position(&mut positions, &exchange_id, &out_asset, out_amount, result, true);
}
let in_asset = self.string_at(result, "inAsset", "");
let in_amount = self.number_at(result, "inAmount", 0.0);
if !in_asset.is_empty() && in_amount > 0.0 {
// What a later hop consumed on this venue is not a residual.
// Netting is per venue: assets sitting on a venue the route
// never spent them on stay stranded, because this class never
// moves funds between venues.
self.add_position(&mut positions, &exchange_id, &in_asset, -in_amount, result, false);
}
}
let mut steps: Vec<Value> = Vec::new();
let mut unresolved: Vec<Value> = Vec::new();
let mut residual_count = 0i64;
for position in &positions {
let asset = self.string_at(position, "asset", "");
let amount = self.number_at(position, "amount", 0.0);
let exchange_id = self.string_at(position, "exchangeId", "");
if amount <= 0.0 {
continue;
}
if asset == from_asset {
// Already home.
continue;
}
residual_count += 1;
let source = self.dict_at(position, "source");
let symbol = self.string_at(&source, "symbol", "");
let source_side = self.string_at(&source, "side", "");
let mut price = self.number_at(&source, "averagePrice", 0.0);
if price <= 0.0 {
price = self.number_at(&source, "expectedPrice", 0.0);
}
if symbol.is_empty() || (source_side != "buy" && source_side != "sell") {
unresolved.push(Self::unresolved_entry(&exchange_id, &asset, amount, "no_source_market"));
continue;
}
if price <= 0.0 {
unresolved.push(Self::unresolved_entry(&exchange_id, &asset, amount, "no_price"));
continue;
}
// Reverse the order that created the residual: a buy left you
// holding base, so sell it back; a sell left you holding quote, so
// buy the base back with it.
//
// The counter asset is whatever the reversed order gives back, which
// is exactly what the original order spent.
let counter_asset = self.string_at(&source, "inAsset", "");
let side;
let unwind_amount;
let market_base;
let market_quote;
if source_side == "buy" {
side = "sell";
market_base = self.string_at(&source, "outAsset", "");
market_quote = self.string_at(&source, "inAsset", "");
} else {
side = "buy";
market_base = self.string_at(&source, "inAsset", "");
market_quote = self.string_at(&source, "outAsset", "");
}
// The limit price comes FIRST, because the buy below is sized on it.
let limit_price = if side == "buy" {
price * (1.0 + slippage_bps / 10000.0)
} else {
price * (1.0 - slippage_bps / 10000.0)
};
if side == "buy" {
// Size the buy on the price it is actually PLACED at, not on the
// expected price. A residual of 44.5 USDT sized at 0.089 is 500
// DOGE, but the order goes out at 0.0892225 and would need 44.61
// USDT to fill - 0.11 more than the venue holds. The venue rejects
// it for insufficient funds, or fills it partially and leaves the
// rest of the stranded money stranded. Dividing by limit_price
// spends at most the residual.
unwind_amount = amount / limit_price;
} else {
unwind_amount = amount;
}
let mut step = HashMap::new();
step.insert("stepIndex".into(), Value::Float(steps.len() as f64));
step.insert("exchangeId".into(), Value::Str(exchange_id.clone().into()));
step.insert("symbol".into(), Value::Str(symbol.into()));
step.insert("side".into(), Value::Str(side.to_string().into()));
// base and quote are carried so that an unwind plan can be fed
// straight back into check_execution_plan_safety: unwinding is
// trading, and it is subject to the same 25 USD cap.
step.insert("base".into(), Value::Str(market_base.into()));
step.insert("quote".into(), Value::Str(market_quote.into()));
step.insert("asset".into(), Value::Str(asset.clone().into()));
step.insert("counterAsset".into(), Value::Str(counter_asset.clone().into()));
step.insert("amount".into(), Value::Float(unwind_amount));
step.insert("expectedPrice".into(), Value::Float(price));
step.insert("limitPrice".into(), Value::Float(limit_price));
// Notional at the price the order is actually placed at: this plan is
// fed back into check_execution_plan_safety, and a cap that was
// checked against the expected price under-counts what the buy above
// really spends.
step.insert(
"notionalQuote".into(),
Value::Float(unwind_amount * limit_price),
);
step.insert("reachesFrom".into(), Value::Bool(counter_asset == from_asset));
step.insert("isDestination".into(), Value::Bool(asset == to_asset));
steps.push(Value::Map(step));
}
let mut plan = HashMap::new();
plan.insert("from".into(), Value::Str(from_asset.into()));
plan.insert("to".into(), Value::Str(to_asset.into()));
plan.insert("halted".into(), Value::Bool(self.bool_at(report, "halted", false)));
plan.insert("haltReason".into(), Value::Str(self.string_at(report, "haltReason", "").into()));
plan.insert("residualCount".into(), Value::Float(residual_count as f64));
plan.insert("requiresConfirmation".into(), Value::Bool(true));
plan.insert("automatic".into(), Value::Bool(false));
plan.insert("steps".into(), Value::List(steps));
plan.insert("unresolved".into(), Value::List(unresolved));
Value::Map(plan)
}
fn unresolved_entry(exchange_id: &str, asset: &str, amount: f64, reason: &str) -> Value {
let mut entry = HashMap::new();
entry.insert("exchangeId".into(), Value::Str(exchange_id.to_string().into()));
entry.insert("asset".into(), Value::Str(asset.to_string().into()));
entry.insert("amount".into(), Value::Float(amount));
entry.insert("reason".into(), Value::Str(reason.to_string().into()));
Value::Map(entry)
}
}
// ---------------------------------------------------------------------------
// I/O: the router HTTP client
// ---------------------------------------------------------------------------
/// The query keys forwarded to GET /route, in a fixed order so that two ports
/// build a byte-identical URL.
const ROUTE_QUERY_KEYS: [&str; 14] = [
"amountIn", "amountOut", "strategy", "maxVenues", "bridges", "exchanges", "balances",
"balanceMode", "includeQuotes", "includeFees", "certified", "requireFullFill",
"hopPenaltyBps", "minLegNotional",
];
impl OrderRouter {
/// Percent-encodes exactly what JavaScript's `encodeURIComponent` leaves
/// alone, so six ports produce the same URL byte for byte.
///
/// Deliberately not `urlencoding::encode`: that is `application/x-www-form-
/// urlencoded`, which escapes `!`, `'`, `(`, `)`, `*` and renders a space as
/// `+`. `encodeURIComponent` does neither. A route whose bridge list or
/// balances string contains any of those would sign a different URL here
/// than in the other five.
fn encode_uri_component(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for byte in text.as_bytes() {
let c = *byte;
let unreserved = c.is_ascii_alphanumeric()
|| matches!(c, b'-' | b'_' | b'.' | b'!' | b'~' | b'*' | b'\'' | b'(' | b')');
if unreserved {
out.push(c as char);
} else {
out.push_str(&format!("%{:02X}", c));
}
}
out
}
/// Renders one query parameter's value the way the other five ports do.
fn query_text(&self, value: &Value) -> RouterResult<String> {
Ok(match value {
Value::Bool(flag) => (if *flag { "true" } else { "false" }).to_string(),
Value::Int(n) => self.format_number(*n as f64)?,
Value::Float(n) => self.format_number(*n)?,
Value::Arr(items) => items
.iter()
.map(|item| match item {
Value::Str(s) => s.to_string(),
other => format!("{other:?}"),
})
.collect::<Vec<String>>()
.join(","),
Value::Str(s) => s.to_string(),
// REFUSED rather than debug-formatted. This used to end in `format!("{other:?}")`,
// which renders a map as Rust's own debug form and ships it: the server then
// rejects a value naming neither what was sent nor what was wanted. `balances` is
// the one param with a meaningful map form and it is rendered before it gets here.
other => {
return Err(bad_request(&format!(
"OrderRouter: a route parameter must be a string, number, boolean or list; got {other:?}"
)))
}
})
}
/// Refuses neither-or-both amounts before a byte reaches the wire.
///
/// Shared by `fetch_route` and `watch_route` because the service runs ONE parser
/// for both and they must not disagree about what is valid.
pub fn assert_route_amounts(params: &Value, method: &str) -> RouterResult<()> {
let has_amount_in = field(params, "amountIn").is_some();
let has_amount_out = field(params, "amountOut").is_some();
if has_amount_in == has_amount_out {
return Err(bad_request(&format!(
"{method} requires exactly one of amountIn or amountOut"
)));
}
Ok(())
}
/// Builds the wss url for `GET /stream/route`, refusing what the endpoint refuses.
pub fn stream_url(&self, from_asset: &str, to_asset: &str, params: &Value) -> RouterResult<String> {
if from_asset.is_empty() || to_asset.is_empty() {
return Err(arguments_required("watchRoute requires fromAsset and toAsset"));
}
Self::assert_route_amounts(params, "watchRoute")?;
// REFUSED HERE, not by the server closing the socket on us. A stream is held open
// for minutes and carries no channel to update the holdings it was opened with, so
// every frame after the first would price a portfolio the caller may already have
// traded away.
if field(params, "balances").is_some() {
return Err(bad_request(
"OrderRouter: /stream/route does not accept balances — a socket outlives the holdings it was opened with. Use fetch_route",
));
}
if field(params, "balanceMode").is_some() {
return Err(bad_request(
"OrderRouter: /stream/route does not accept balanceMode, because it does not accept balances. Use fetch_route",
));
}
// the same venue filter fetch_route applies. A router built with venues can only
// execute on those, so a stream that quoted the rest would hand back routes its own
// executor must refuse. The caller's own exchanges parameter still wins.
let scoped_params: Value;
let params = if !self.venues.is_empty() && field(params, "exchanges").is_none() {
let mut scoped = params.as_map().cloned().unwrap_or_default();
let stored_ids: Vec<String> = self.venues.keys().cloned().collect();
scoped.insert("exchanges".to_string(), Value::from(stored_ids.join(",")));
scoped_params = Value::map(scoped);
&scoped_params
} else {
params
};
// includeQuotes is deliberately NOT defaulted: the service defaults it to false on
// this endpoint and true on the REST one, and the query builder omits what the
// caller did not set.
let mut query = format!(
"from={}&to={}",
Self::encode_uri_component(&from_asset.to_uppercase()),
Self::encode_uri_component(&to_asset.to_uppercase())
);
for key in ROUTE_QUERY_KEYS.iter() {
let value = match field(params, key) {
Some(found) => found,
None => continue,
};
let text = self.query_text(value)?;
query.push('&');
query.push_str(key);
query.push('=');
query.push_str(&Self::encode_uri_component(&text));
}
let base = if let Some(rest) = self.base_url.strip_prefix("https://") {
format!("wss://{rest}")
} else if let Some(rest) = self.base_url.strip_prefix("http://") {
format!("ws://{rest}")
} else {
self.base_url.clone()
};
Ok(format!("{base}/stream/route?{query}"))
}
/// Maps a websocket close code onto the error the same refusal raises over REST.
/// `None` for an ordinary close.
pub fn stream_close_error(&self, code: u16, last_frame: &Value) -> Option<ExchangeError> {
if code == 1008 {
// the service sends ONE json frame carrying the same `error` string the REST
// endpoint would have answered a 400 with — including a bridged exact-out,
// which REST refuses as a 501. Same refusal, same error.
let message = self.string_at(last_frame, "error", "the router rejected the stream request");
return Some(bad_request(&format!("OrderRouter: {message}")));
}
if code == 1013 {
// try again later: the cache was cold when the socket was accepted. A stream
// carries no status codes once open, so this is the only way the service can say
// what a REST 503 says — and it is the same retry, not a fault.
let message = self.string_at(last_frame, "error", "the router cache is cold");
let cold = self.cold_cache_suffix(last_frame);
return Some(ExchangeError::new(
"ExchangeNotAvailable",
format!("OrderRouter: {message}{cold}"),
));
}
if code == 1000 || code == 1005 || code == 0 {
// a clean close, or one with no code, which is what a caller-requested stop
// looks like from here
return None;
}
Some(ExchangeError::new(
"ExchangeNotAvailable",
format!("OrderRouter: the route stream closed with code {code}"),
))
}
/// The same route as `fetch_route`, pushed over a websocket whenever any market it
/// depends on moves.
///
/// BLOCKS until the stream ends: `on_route` is how you read it. Return `"stop"` from the
/// hook to close the socket cleanly; the call then returns the last route it saw. Every
/// frame is stamped with the same client-side keys `fetch_route` stamps, so it can go
/// straight into `build_execution_plan`.
///
/// `balances` and `balanceMode` are refused — see `stream_url` for why — and
/// `includeQuotes` is left to the endpoint's own default, which is false here.
///
/// Unlike `execute`'s step hook, this one is a plain parameter rather than something
/// stored on the client: nothing here has to survive in a `Value`, so the closed-enum
/// workaround `set_on_step` needs does not apply.
pub async fn watch_route(
&self,
from_asset: &str,
to_asset: &str,
params: &Value,
on_route: &mut dyn FnMut(&Value) -> String,
) -> RouterResult<Value> {
use futures::StreamExt;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::Message;
// built BEFORE the socket, so a refusal this client can make itself costs no
// connection
let url = self.stream_url(from_asset, to_asset, params)?;
let mut request = url.as_str().into_client_request().map_err(|e| {
ExchangeError::new("ExchangeNotAvailable", format!("OrderRouter: {e}"))
})?;
{
let headers = request.headers_mut();
// omitted entirely when absent: an empty x-api-key reads as a malformed
// credential to a server that still authenticates, not as an anonymous caller
if !self.api_key.is_empty() {
let key = self.api_key.parse().map_err(|_| {
bad_request("OrderRouter: the apiKey cannot be sent as a header")
})?;
headers.insert("x-api-key", key);
}
let request_id = self.string_at(params, "requestId", "");
if !request_id.is_empty() && request_id.len() <= 200 {
if let Ok(value) = request_id.parse() {
headers.insert("x-request-id", value);
}
}
// a userAgent that is not a valid header value is skipped, like x-request-id
if !self.user_agent.is_empty() {
if let Ok(value) = self.user_agent.parse() {
headers.insert("user-agent", value);
}
}
}
let (socket, _response) = match tokio_tungstenite::connect_async(request).await {
Ok(pair) => pair,
Err(e) => return Err(self.stream_handshake_error(&e.to_string())),
};
let (_write, mut read) = socket.split();
let upper_from = from_asset.to_uppercase();
let upper_to = to_asset.to_uppercase();
let required_full_fill = self.bool_at(params, "requireFullFill", false);
let mut last_frame = Value::Map(HashMap::new());
let mut last_route = Value::Map(HashMap::new());
while let Some(next) = read.next().await {
let message = match next {
Ok(found) => found,
Err(_) => break,
};
match message {
Message::Close(frame) => {
let code = frame.map(|f| u16::from(f.code)).unwrap_or(0);
return match self.stream_close_error(code, &last_frame) {
Some(failure) => Err(failure),
None => Ok(last_route),
};
}
Message::Text(text) => {
let parsed: serde_json::Value = serde_json::from_str(&text)
.map_err(|_| exchange_error("OrderRouter stream sent a non-JSON frame"))?;
let mut frame = Value::from_json(&parsed);
// Held whether or not it looks like a route: a REFUSAL arrives as one
// ordinary frame and only the close code that follows says it was one.
last_frame = frame.clone();
if !self.string_at(&frame, "error", "").is_empty() {
// not a route — wait for the close code to say which refusal it is
continue;
}
// the same client-side stamps fetch_route applies, for the same reason:
// every frame is a route build_execution_plan may be handed
Self::put(&mut frame, "clientRequestedFrom", Value::Str(upper_from.clone().into()));
Self::put(&mut frame, "clientRequestedTo", Value::Str(upper_to.clone().into()));
Self::put(
&mut frame,
"clientRequestedRequireFullFill",
Value::Bool(required_full_fill),
);
last_route = frame.clone();
if on_route(&frame) == "stop" {
return Ok(last_route);
}
}
_ => {
// ping/pong/binary: tungstenite answers pings itself, and this endpoint
// sends nothing binary
}
}
}
// the stream ended without a close frame
match self.stream_close_error(0, &last_frame) {
Some(failure) => Err(failure),
None => Ok(last_route),
}
}
/// Maps a failed websocket upgrade onto the same error the REST path raises for that
/// status. 401, 429 and 503 happen BEFORE the upgrade, so they never arrive as close
/// codes, and the transport reports them only as text.
pub fn stream_handshake_error(&self, message: &str) -> ExchangeError {
if message.contains("401") {
return ExchangeError::new("AuthenticationError", "OrderRouter: unauthorized".to_string());
}
if message.contains("403") {
// same ipv4-only refusal as the REST path, and the same reason not to call it an
// authentication failure: this service has no credential to get wrong
return ExchangeError::new("PermissionDenied", "OrderRouter: the router resolved this client to a non-IPv4 address and refused it; reach it over IPv4".to_string());
}
if message.contains("429") {
return ExchangeError::new("RateLimitExceeded", "OrderRouter: rate limit exceeded".to_string());
}
ExchangeError::new("ExchangeNotAvailable", format!("OrderRouter: {message}"))
}
/// Builds the fully-formed `/route` url, including the query string.
///
/// Split out from `fetch_route` so the URL construction — the part that has
/// to be byte-identical across six languages — is testable without a
/// network.
pub fn build_route_url(
&self,
from_asset: &str,
to_asset: &str,
params: &Value,
) -> RouterResult<String> {
if from_asset.is_empty() || to_asset.is_empty() {
return Err(arguments_required("fetchRoute requires fromAsset and toAsset"));
}
Self::assert_route_amounts(params, "fetchRoute")?;
let mut query = format!(
"from={}&to={}",
Self::encode_uri_component(&from_asset.to_uppercase()),
Self::encode_uri_component(&to_asset.to_uppercase())
);
for key in ROUTE_QUERY_KEYS.iter() {
let value = match field(params, key) {
Some(found) => found,
None => continue,
};
let text = self.query_text(value)?;
query.push('&');
query.push_str(key);
query.push('=');
query.push_str(&Self::encode_uri_component(&text));
}
Ok(format!("{}/route?{}", self.base_url, query))
}
/// Builds the `POST /route` JSON body — the same fields as the query
/// string, by the same names.
///
/// HOLDINGS NEVER TRAVEL IN A URL. The service scrubs balances out of its
/// own logs, but a URL does not stay inside that process: the standard
/// deployment puts a reverse proxy in front, and nginx, an ALB and a CDN all
/// log the full request line by default. So do browser history and
/// client-side tracing, and a `Referer` carries it off-origin. None of that
/// is reachable from the router, and no amount of in-process redaction fixes
/// it — the fix is for the wallet not to be in the URL.
pub fn build_route_body(
&self,
from_asset: &str,
to_asset: &str,
params: &Value,
) -> RouterResult<Value> {
if from_asset.is_empty() || to_asset.is_empty() {
return Err(arguments_required("fetchRoute requires fromAsset and toAsset"));
}
Self::assert_route_amounts(params, "fetchRoute")?;
let mut body = Value::Dict(Arc::new(HashMap::new()));
Self::put(&mut body, "from", Value::Str(from_asset.to_uppercase().into()));
Self::put(&mut body, "to", Value::Str(to_asset.to_uppercase().into()));
for key in ROUTE_QUERY_KEYS.iter() {
let value = match field(params, key) {
Some(found) => found,
None => continue,
};
// numbers and booleans travel as themselves — the body is JSON and
// the service's own schema types amountIn as a number. Everything
// else uses the same text form the query string uses, so one handler
// reads both verbs.
// balances FIRST, before the number/boolean shortcut: a numeric balances is not
// a wallet, and letting it through as a JSON number sent it to the server to be
// refused there.
let encoded = if *key == "balances" {
Value::Str(self.render_balances(value)?.into())
} else {
match value {
Value::Bool(flag) => Value::Bool(*flag),
Value::Int(n) => Value::Int(*n),
Value::Float(n) => Value::Float(*n),
other => Value::Str(self.query_text(other)?.into()),
}
};
Self::put(&mut body, key, encoded);
}
Ok(body)
}
/// Asks the router how to convert one asset into another, over the venues
/// and bridges it has live books for.
///
/// An unroutable pair comes back as a RouteResult carrying an
/// `unroutableReason`, NOT as an error: refusing to quote is a deliberate
/// outcome, not a failure.
pub async fn fetch_route(
&self,
from_asset: &str,
to_asset: &str,
params: &Value,
) -> RouterResult<Value> {
// THE STORED VENUES ANSWER TWO QUESTIONS HERE, and a caller-supplied value wins both.
// `exchanges` is cheap and always right: a route naming a venue you hold no keys for
// is not a route you can take. `balances` reads every venue's wallet, so it happens
// only when venues were installed and the caller supplied none of their own.
let owned_params;
let params = if self.venues.is_empty() {
params
} else {
let mut map = match params.as_map() {
Some(existing) => existing.clone(),
None => HashMap::new(),
};
if field(params, "exchanges").is_none() {
let ids: Vec<String> = self.venues.keys().cloned().collect();
map.insert("exchanges".into(), Value::Str(ids.join(",").into()));
}
if self.track_balances && field(params, "balances").is_none() {
map.insert("balances".into(), Value::Str(self.load_balances(false).await?.into()));
}
owned_params = Value::Map(map);
&owned_params
};
// A request carrying no holdings still goes as a GET: cacheable,
// linkable, and what every existing caller already uses. One that
// carries them is POSTed — see build_route_body for why.
let sends_balances = field(params, "balances").is_some();
// an audit id the caller chose, so their log and the router's decision log can be
// joined. The service mints one when this is absent, and echoes whichever it used.
let request_id = self.string_at(params, "requestId", "");
let mut route = if sends_balances {
let body = self.build_route_body(from_asset, to_asset, params)?;
self.request(&format!("{}/route", self.base_url), "POST", &body, &request_id).await?
} else {
let url = self.build_route_url(from_asset, to_asset, params)?;
self.request(&url, "GET", &Value::Null, &request_id).await?
};
if sends_balances {
// CHECKED HERE, not only in fetch_route_with_balances. `balances` is a
// documented parameter of this method, and a caller who passes it directly was
// getting no verification at all — the same silent failure, one call lower down.
self.assert_balances_applied(&route, params)?;
}
// What THIS CLIENT asked for, stamped client-side so check_execution_plan_safety can
// tell a flag that was honoured from one that was lost in transit. requireFullFill is
// the one route parameter that fails OPEN.
Self::put(
&mut route,
"clientRequestedRequireFullFill",
Value::Bool(self.bool_at(params, "requireFullFill", false)),
);
// Stamp what THIS CLIENT asked for, client-side, so build_execution_plan
// can check the answer against the question. Everything else in the
// response — from, to, pair, side — is the server's word for it, and the
// plan used to trust all of it: a compromised or simply buggy router
// could name any real market and the safety checks, which only test
// internal consistency against that market, would pass it under the
// 25 USD cap.
Self::put(&mut route, "clientRequestedFrom", Value::Str(from_asset.to_uppercase().into()));
Self::put(&mut route, "clientRequestedTo", Value::Str(to_asset.to_uppercase().into()));
Ok(route)
}
/// Errors unless the router confirmed it read the holdings that were sent.
pub fn assert_balances_applied(&self, route: &Value, params: &Value) -> RouterResult<()> {
if !self.bool_at(params, "requireBalancesApplied", true) {
// the caller opted out, with their eyes open
return Ok(());
}
// /route declares its query without a JSON schema, so a router that predates the
// balances feature IGNORES them and answers byte-identically to one that never
// received any.
if !self.string_at(route, "balancesApplied", "").is_empty() {
return Ok(());
}
// An EMPTY echo is ambiguous on its own: "" is also the honest answer to `balances=`
// meaning "I hold nothing". balanceEntryCount disambiguates by PRESENCE, not by
// value — a current server sends 0, a server that never heard of the feature sends
// nothing at all. This is the case the old check skipped outright.
if self.number_at(route, "balanceEntryCount", -1.0) >= 0.0 {
return Ok(());
}
Err(exchange_error(
"OrderRouter did not echo balancesApplied: the balances were ignored, so this route is not funded-aware",
))
}
/// Renders a retry interval as a message suffix, empty when the service sent
/// none.
fn retry_suffix(retry_after: &str) -> String {
if retry_after.is_empty() {
return String::new();
}
format!(", retry after {retry_after}s")
}
/// Renders the book counts a `cache_cold` refusal carries, so a caller can
/// log why it was refused.
fn cold_cache_suffix(&self, body: &Value) -> String {
let total = self.number_at(body, "bookCount", 0.0);
if total <= 0.0 {
return String::new();
}
let fresh = self.number_at(body, "freshCount", 0.0);
let needed = self.number_at(body, "minFreshBooksForReady", 0.0);
match (
self.format_number(fresh),
self.format_number(total),
self.format_number(needed),
) {
(Ok(fresh_text), Ok(total_text), Ok(needed_text)) => {
format!(" ({fresh_text} of {total_text} books fresh, {needed_text} needed)")
}
// a count this class cannot render is a count it will not guess at:
// the suffix is dropped whole rather than reporting a number that
// differs from what the other five ports would print
_ => String::new(),
}
}
/// Performs the authenticated call and maps router status codes onto ccxt
/// error kinds.
pub async fn request(
&self,
url: &str,
method: &str,
request_body: &Value,
request_id: &str,
) -> RouterResult<Value> {
let client = reqwest::Client::builder()
.timeout(std::time::Duration::from_millis(self.timeout_ms.max(0.0) as u64))
.build()
.map_err(|e| ExchangeError::new("ExchangeNotAvailable", format!("OrderRouter could not build an http client: {e}")))?;
let mut builder = if method == "POST" {
client
.post(url)
.header("Content-Type", "application/json")
.body(request_body.to_json().to_string())
} else {
client.get(url)
};
builder = builder.header("Accept", "application/json");
if !self.api_key.is_empty() {
builder = builder.header("x-api-key", &self.api_key);
}
if !request_id.is_empty() && request_id.len() <= 200 {
// the service caps this at 200 characters and mints its own when absent, so a
// longer one is dropped rather than sent and rejected
builder = builder.header("x-request-id", request_id);
}
if !self.user_agent.is_empty() {
// only when configured: an empty value keeps reqwest's own default rather than
// sending a blank one. (Browsers forbid setting User-Agent, so the TS port silently
// drops it there; no such restriction applies here.)
builder = builder.header("User-Agent", &self.user_agent);
}
let response = builder.send().await;
let response = match response {
Ok(found) => found,
Err(e) => {
if e.is_timeout() {
return Err(ExchangeError::new(
"RequestTimeout",
format!("OrderRouter request timed out after {}ms", self.timeout_ms),
));
}
return Err(ExchangeError::new(
"ExchangeNotAvailable",
format!("OrderRouter request failed: {e}"),
));
}
};
let status = response.status().as_u16();
// READ BEFORE THE BODY. On a 429 or a 503 this is the only number that
// says how long to wait, and a caller told "unavailable" with no
// interval retries blind.
//
// The two headers are NOT interchangeable and are kept apart on purpose.
// retry-after answers "how long until this particular refusal clears";
// x-ratelimit-reset answers "how long until the rate-limit window rolls
// over", which is the same question ONLY on a 429. Using the window as a
// fallback for a cold cache would tell a caller to wait a full minute for
// a cache that repopulates in seconds.
let header_text = |name: &str| -> String {
response
.headers()
.get(name)
.and_then(|value| value.to_str().ok())
.unwrap_or("")
.to_string()
};
let retry_after = header_text("retry-after");
let rate_limit_reset = header_text("x-ratelimit-reset");
let text = response.text().await.map_err(|e| {
ExchangeError::new("ExchangeNotAvailable", format!("OrderRouter request failed: {e}"))
})?;
let parsed: serde_json::Value = serde_json::from_str(&text)
.map_err(|_| exchange_error("OrderRouter returned a non-JSON body"))?;
let body = Value::from_json(&parsed);
if (200..300).contains(&status) {
return Ok(body);
}
// 404 and 501 carry a complete RouteResult explaining the refusal —
// `no_market` and `exact_out_multi_hop_unsupported` are routing
// outcomes, and turning them into errors would make the caller parse an
// error string to recover a structure it already has.
if (status == 404 || status == 501) && !self.string_at(&body, "unroutableReason", "").is_empty() {
return Ok(body);
}
let message = self.string_at(&body, "error", &format!("http status {status}"));
if status == 503 {
// /ready answers 503 WITH ITS ANSWER: a Readiness body saying
// not_ready and why. That is the result of the probe, not a failure
// of it — erroring would hide the very counts the caller asked for.
// Distinguished by shape, exactly as 404 and 501 are above.
if !self.string_at(&body, "status", "").is_empty() {
return Ok(body);
}
// Every other 503 is cache_cold: the router is alive but has too few
// fresh books to rank on, typically for a few seconds after a restart
// while the connectors repopulate. It is a RETRY, and the generic
// ExchangeError this used to raise made it indistinguishable from a
// permanent server fault.
let cold = self.cold_cache_suffix(&body);
let retry = Self::retry_suffix(&retry_after);
return Err(ExchangeError::new(
"ExchangeNotAvailable",
format!("OrderRouter: {message}{cold}{retry}"),
));
}
if status == 429 {
// the window rollover IS the retry interval here, so it stands in when
// the service sent no retry-after
let limit_interval = if retry_after.is_empty() { &rate_limit_reset } else { &retry_after };
let retry = Self::retry_suffix(limit_interval);
return Err(ExchangeError::new(
"RateLimitExceeded",
format!("OrderRouter: {message}{retry}"),
));
}
if status == 403 {
// NOT an authentication failure. The service has no API key; its only 403 is the
// ipv4-only refusal, raised before rate limiting when the resolved client address
// is not a dotted quad. Calling it an auth error sends the caller looking for a
// credential that exists for nobody, while the real remedy goes unsaid.
return Err(ExchangeError::new(
"PermissionDenied",
format!("OrderRouter: {message} — the router resolved this client to a non-IPv4 address and refused it; reach it over IPv4"),
));
}
let kind = match status {
400 => "BadRequest",
401 => "AuthenticationError",
408 | 504 => "RequestTimeout",
_ => "ExchangeError",
};
Err(ExchangeError::new(kind, format!("OrderRouter: {message}")))
}
/// Liveness only — the service answers 200 from the first millisecond of
/// boot, before a single venue has connected. Use `fetch_readiness` to decide
/// whether the router can actually price anything.
pub async fn fetch_health(&self) -> RouterResult<Value> {
self.request(&format!("{}/health", self.base_url), "GET", &Value::Null, "").await
}
/// Whether the router has enough fresh books to rank on, measured with the
/// same staleness cutoff `/route` uses.
///
/// NOT_READY IS A NORMAL ANSWER: the service replies 503 with the same body
/// it returns on 200, and this method returns it rather than erroring,
/// because a caller asking "are you ready" needs the counts that say why not.
pub async fn fetch_readiness(&self) -> RouterResult<Value> {
self.request(&format!("{}/ready", self.base_url), "GET", &Value::Null, "").await
}
/// Build provenance of the running process. This is what a deploy pipeline
/// asserts against — `/health` answers 200 from the OLD process just as
/// happily when a deploy silently no-ops, and `commit` is the only field that
/// tells the two apart.
pub async fn fetch_version(&self) -> RouterResult<Value> {
self.request(&format!("{}/version", self.base_url), "GET", &Value::Null, "").await
}
/// The unified symbols the router currently holds a cached book for. A pair
/// absent from this list cannot be routed no matter how it is spelled.
pub async fn fetch_symbols(&self) -> RouterResult<Vec<Value>> {
let response = self.request(&format!("{}/symbols", self.base_url), "GET", &Value::Null, "").await?;
Ok(self.list_at(&response, "symbols"))
}
/// Per-venue connection health. A venue can hold an open socket while its
/// subscription is silently dead, so read the per-venue update age and not
/// only the connected flag.
pub async fn fetch_exchanges_status(&self) -> RouterResult<Vec<Value>> {
let response = self
.request(&format!("{}/exchanges/status", self.base_url), "GET", &Value::Null, "")
.await?;
Ok(self.list_at(&response, "exchanges"))
}
/// The router's own cached L2 book for one venue and symbol — the exact depth
/// a route was ranked on, which is what makes a surprising route auditable.
pub async fn fetch_cached_order_book(&self, exchange_id: &str, symbol: &str) -> RouterResult<Value> {
if exchange_id.is_empty() || symbol.is_empty() {
return Err(arguments_required("fetchCachedOrderBook requires an exchangeId and a symbol"));
}
// the symbol carries a slash and travels as ONE path segment, so it is
// encoded rather than interpolated: BTC/USDT unencoded would read as two
// segments and reach a route that does not exist
let url = format!(
"{}/orderbook/{}/{}",
self.base_url,
Self::encode_uri_component(exchange_id),
Self::encode_uri_component(symbol)
);
self.request(&url, "GET", &Value::Null, "").await
}
}
// ---------------------------------------------------------------------------
// IMPURE: execute
// ---------------------------------------------------------------------------
/// The strategies `execute` accepts. Anything else is refused before a venue is
/// touched, rather than silently falling through to a default.
// HOW the orders go out, and nothing else. Whether they go out at all is `dryRun`.
const KNOWN_STRATEGIES: [&str; 5] = [
"sequential", "parallel_within_hop", "limit_protected", "best_effort", "atomic_ish",
];
impl OrderRouter {
/// The stable identity of an execution, used for the re-execution guard.
///
/// A caller-supplied `idempotencyKey` WINS over the plan's own `requestId`:
/// passing one is a deliberate statement about what this execution is, and it
/// is the only identity a hand-assembled plan can have — `execute` takes any
/// dictionary of the plan shape, not only the output of `build_execution_plan`,
/// and a plan a user built themselves never went through a routing request and
/// so never had a `requestId`. Nothing is invented when both are absent: a
/// generated identity would be either random, which defeats the guard that
/// depends on it, or a fingerprint of the plan's contents, which makes two
/// plans that happen to agree indistinguishable.
pub fn plan_identity(&self, plan: &Value, options: &Value) -> String {
let idempotency_key = self.string_at(options, "idempotencyKey", "");
if !idempotency_key.is_empty() {
return idempotency_key;
}
self.string_at(plan, "requestId", "")
}
/// Counts the distinct hops a step list spans, which is the only authority
/// on whether a plan is multi-hop.
fn hop_count_of(&self, steps: &[Value]) -> usize {
// A vector rather than a set, so the count is the same in six languages
// and does not depend on hash iteration order.
let mut seen: Vec<f64> = Vec::new();
for step in steps {
let hop_index = self.number_at(step, "hopIndex", 0.0);
if !seen.iter().any(|s| *s == hop_index) {
seen.push(hop_index);
}
}
seen.len()
}
/// A deep-enough copy of the plan's steps that resizing them cannot reach
/// back into the caller's plan.
fn clone_steps(&self, plan: &Value) -> Vec<Value> {
let mut copied = Vec::new();
let steps = self.list_at(plan, "steps");
for (i, step) in steps.iter().enumerate() {
// NORMALISE, do not shallow-copy. This used to clone the incoming map field
// for field, which is fine for a plan build_execution_plan produced and wrong
// for every other plan the Manual says execute accepts: a hand-assembled one,
// one that travelled through JSON, or the rebuilt tail of a halted route.
//
// A step carrying no stepIndex then stayed absent, apply_resize reads it as
// -1.0, and reconcile_execution_step only ever names targets >= 0 — so the
// downstream resize matched nothing and silently applied NOTHING. Later hops
// went to the venue at their original unshrunk size, sized for money the
// bridge asset never received, and realisedOut was never written back, so a
// multi-leg hop compounded its scale instead of accumulating the shortfall.
//
// The other five ports have always rebuilt the step here; this is Rust
// catching up to them, field for field.
let mut fresh = HashMap::new();
fresh.insert("stepIndex".into(), Value::Float(self.number_at(step, "stepIndex", i as f64)));
fresh.insert("hopIndex".into(), Value::Float(self.number_at(step, "hopIndex", 0.0)));
fresh.insert("legIndex".into(), Value::Float(self.number_at(step, "legIndex", 0.0)));
fresh.insert("exchangeId".into(), Value::Str(self.string_at(step, "exchangeId", "").into()));
fresh.insert("symbol".into(), Value::Str(self.string_at(step, "symbol", "").into()));
fresh.insert("side".into(), Value::Str(self.string_at(step, "side", "").into()));
fresh.insert("base".into(), Value::Str(self.string_at(step, "base", "").into()));
fresh.insert("quote".into(), Value::Str(self.string_at(step, "quote", "").into()));
fresh.insert("amount".into(), Value::Float(self.number_at(step, "amount", 0.0)));
fresh.insert("expectedPrice".into(), Value::Float(self.number_at(step, "expectedPrice", 0.0)));
fresh.insert("effectivePrice".into(), Value::Float(self.number_at(step, "effectivePrice", 0.0)));
fresh.insert("limitPrice".into(), Value::Float(self.step_limit_price(step)));
fresh.insert("notionalQuote".into(), Value::Float(self.step_notional_quote(step)));
// carried through the clone because execute reconciles against THESE steps,
// not the plan's: without it the fee netting would be measured against a
// gross expectation on every live run
fresh.insert("expectedFeeCost".into(), Value::Float(self.number_at(step, "expectedFeeCost", 0.0)));
copied.push(Value::Map(fresh));
}
copied
}
/// The report skeleton, with one planned result per step.
fn empty_report(
&self,
plan: &Value,
strategy: &str,
dry_run: bool,
steps: &[Value],
) -> Value {
let mut results = Vec::new();
for step in steps {
let mut result = HashMap::new();
result.insert("stepIndex".into(), Value::Float(self.number_at(step, "stepIndex", -1.0)));
result.insert("hopIndex".into(), Value::Float(self.number_at(step, "hopIndex", 0.0)));
result.insert("legIndex".into(), Value::Float(self.number_at(step, "legIndex", 0.0)));
result.insert("exchangeId".into(), Value::Str(self.string_at(step, "exchangeId", "").into()));
result.insert("symbol".into(), Value::Str(self.string_at(step, "symbol", "").into()));
result.insert("side".into(), Value::Str(self.string_at(step, "side", "").into()));
result.insert("status".into(), Value::Str("planned".into()));
result.insert("requestedAmount".into(), Value::Float(self.number_at(step, "amount", 0.0)));
result.insert("filledAmount".into(), Value::Float(0.0));
result.insert("averagePrice".into(), Value::Float(0.0));
result.insert("cost".into(), Value::Float(0.0));
result.insert("inAsset".into(), Value::Str(Cow::Borrowed("")));
result.insert("inAmount".into(), Value::Float(0.0));
result.insert("outAsset".into(), Value::Str(Cow::Borrowed("")));
result.insert("outAmount".into(), Value::Float(0.0));
result.insert("orderId".into(), Value::Str(Cow::Borrowed("")));
result.insert("clientOrderId".into(), Value::Str(Cow::Borrowed("")));
result.insert("errorCode".into(), Value::Str(Cow::Borrowed("")));
// which retry produced this result; 0 unless retryFailedSteps re-placed it
result.insert("attempt".into(), Value::Float(0.0));
// False until an order is actually dispatched — a failure before
// dispatch cannot have left anything resting on a venue.
result.insert("placementAttempted".into(), Value::Bool(false));
results.push(Value::Map(result));
}
let mut report = HashMap::new();
// A placeholder: execute resolves the real identity from the plan AND the
// options and overwrites it before anything reads this field.
report.insert("planId".into(), Value::Str(Cow::Borrowed("")));
report.insert("strategy".into(), Value::Str(strategy.to_string().into()));
report.insert("dryRun".into(), Value::Bool(dry_run));
report.insert("live".into(), Value::Bool(!dry_run));
report.insert("from".into(), Value::Str(self.string_at(plan, "from", "").into()));
report.insert("to".into(), Value::Str(self.string_at(plan, "to", "").into()));
report.insert("slippageBps".into(), Value::Float(self.number_at(plan, "slippageBps", DEFAULT_SLIPPAGE_BPS)));
report.insert(
"reconcileToleranceRatio".into(),
Value::Float(self.number_at(plan, "reconcileToleranceRatio", DEFAULT_RECONCILE_TOLERANCE)),
);
report.insert("stepCount".into(), Value::Float(steps.len() as f64));
report.insert("wouldPlaceOrders".into(), Value::Float(0.0));
report.insert("ordersPlaced".into(), Value::Float(0.0));
report.insert("halted".into(), Value::Bool(false));
report.insert("haltReason".into(), Value::Str(Cow::Borrowed("")));
report.insert("haltStepIndex".into(), Value::Float(-1.0));
report.insert("filledIn".into(), Value::Float(0.0));
report.insert("filledOut".into(), Value::Float(0.0));
report.insert("steps".into(), Value::List(results));
report.insert("openOrders".into(), Value::List(Vec::new()));
report.insert("errors".into(), Value::List(Vec::new()));
report.insert("reconciliations".into(), Value::List(Vec::new()));
Value::Map(report)
}
/// Appends one entry to a list-valued field of a container.
fn append_to(container: &mut Value, key: &str, entry: Value) {
let mut items = match container.as_map().and_then(|m| m.get(key)) {
Some(Value::Arr(existing)) => existing.as_ref().clone(),
_ => Vec::new(),
};
items.push(entry);
Self::put(container, key, Value::List(items));
}
/// Records an error against the report.
fn record_error(&self, report: &mut Value, step_index: f64, exchange_id: &str, symbol: &str, code: &str) {
let mut entry = HashMap::new();
entry.insert("stepIndex".into(), Value::Float(step_index));
entry.insert("exchangeId".into(), Value::Str(exchange_id.to_string().into()));
entry.insert("symbol".into(), Value::Str(symbol.to_string().into()));
entry.insert("code".into(), Value::Str(code.to_string().into()));
Self::append_to(report, "errors", Value::Map(entry));
}
/// Records an order that may still be resting on a venue.
fn record_open_order(&self, report: &mut Value, exchange_id: &str, symbol: &str, order_id: &str, reason: &str) {
let mut entry = HashMap::new();
entry.insert("exchangeId".into(), Value::Str(exchange_id.to_string().into()));
entry.insert("symbol".into(), Value::Str(symbol.to_string().into()));
entry.insert("orderId".into(), Value::Str(order_id.to_string().into()));
entry.insert("reason".into(), Value::Str(reason.to_string().into()));
Self::append_to(report, "openOrders", Value::Map(entry));
}
/// Records a placement whose outcome is genuinely unknown — the request may
/// or may not have reached the venue, so an order may or may not exist.
fn record_unconfirmed_placement(&self, report: &mut Value, exchange_id: &str, symbol: &str, reason: &str) {
// No order id, because there is none to record: that is the whole
// problem. It goes on openOrders regardless, because the one thing a
// caller must not conclude is that nothing was placed.
self.record_open_order(report, exchange_id, symbol, "", reason);
}
/// Reports whether a thrown error leaves a placement's outcome genuinely
/// unknown.
fn is_outcome_unknown_error(&self, error: &ExchangeError) -> bool {
// Seven names, matched exactly — the same list the other five ports use.
//
// NOT `error.is("NetworkError")`: that walks the hierarchy, and in
// ccxt's tree DDoSProtection, RateLimitExceeded and InvalidNonce are
// all children of NetworkError. Those are the venue ANSWERING — a
// rate-limit rejection is a definite "no order was placed" — so the
// walk reported every throttled request as a possibly-live order,
// halting a route the other five ports complete and sending an
// operator hunting for an order that never existed.
//
// OperationFailed, BadResponse and NullResponse are the other
// direction of the same mistake: the call came back with NO usable
// answer, so an order may well be live. binance maps -1006 — "An
// unexpected response was received from the message bus. Execution
// status unknown." — to OperationFailed on one endpoint and
// BadResponse on another, and both were read as a definite rejection
// and RETRIED under retryFailedSteps.
matches!(
error.kind.as_str(),
"RequestTimeout"
| "ExchangeNotAvailable"
| "NetworkError"
| "OnMaintenance"
| "OperationFailed"
| "BadResponse"
| "NullResponse"
)
}
/// Marks every step from an index onwards as skipped after a halt.
fn mark_remaining_skipped(&self, report: &mut Value, start: usize) {
let mut results = self.list_at(report, "steps");
for result in results.iter_mut().skip(start) {
if self.string_at(result, "status", "") == "planned" {
Self::put(result, "status", Value::Str("skipped".into()));
}
}
Self::put(report, "steps", Value::List(results));
}
/// Totals the report's fills once the loops are done.
fn summarise_report(&self, report: &mut Value, steps: &[Value]) {
let results = self.list_at(report, "steps");
// filledIn is denominated in the route's FROM asset and filledOut in its
// TO asset, which is only true if each is summed over one hop: the first
// and the last. Summing inAmount and outAmount across every step, as
// this port did, adds USDT to BTC to ETH and reports the total as one
// number — meaningless on any route longer than a single hop, and
// meaningless in a way that reads like a figure.
let mut last_hop = 0.0;
for step in steps {
let hop_index = self.number_at(step, "hopIndex", 0.0);
if hop_index > last_hop {
last_hop = hop_index;
}
}
let mut filled_in = 0.0;
let mut filled_out = 0.0;
for result in &results {
let hop_index = self.number_at(result, "hopIndex", 0.0);
if hop_index == 0.0 {
filled_in += self.number_at(result, "inAmount", 0.0);
}
if hop_index == last_hop {
filled_out += self.number_at(result, "outAmount", 0.0);
}
}
// ordersPlaced is NOT recomputed here. It is incremented as each order is
// placed, so it counts an outcome_unknown step too — a status-derived
// recount silently dropped exactly those, which are the placements an
// operator most needs to know about.
Self::put(report, "filledIn", Value::Float(filled_in));
Self::put(report, "filledOut", Value::Float(filled_out));
Self::put(report, "stepCount", Value::Float(steps.len() as f64));
}
}
impl OrderRouter {
/// Sums the fees an order charged in one asset, ignoring any other currency.
fn order_fee_in_asset(&self, order: &Value, asset: &str) -> f64 {
if asset.is_empty() {
return 0.0;
}
let mut total = 0.0;
// ccxt reports the same cut in up to three places, so this is a strict
// THREE-TIER PRECEDENCE and never a sum across tiers: the `fees` list wins
// outright; if it named no entry in this asset, the single `fee` is read;
// only if that named nothing either are the per-trade fees totalled.
// `saw_in_list` is what makes each tier exclusive of the ones below it —
// safeOrder fills `fee` and `fees` from the same charge, and the per-trade
// fees are usually that same charge again, so adding tiers together would
// double- or triple-count. Within ONE tier every matching entry IS summed.
let fees = self.list_at(order, "fees");
let mut saw_in_list = false;
for entry in &fees {
if self.string_at(entry, "currency", "").to_uppercase() == asset.to_uppercase() {
total += self.number_at(entry, "cost", 0.0);
saw_in_list = true;
}
}
if !saw_in_list {
let single = self.dict_at(order, "fee");
if self.string_at(&single, "currency", "").to_uppercase() == asset.to_uppercase() {
total += self.number_at(&single, "cost", 0.0);
saw_in_list = true;
}
}
if !saw_in_list {
// Last resort: a venue that reports its cut only per trade. The Go
// port has no `fees` list on its typed Order at all, so this
// fallback is what lets all six ports read the same fee off the same
// order — and reading NOTHING here is the dangerous direction, not
// the safe one: an unread fee leaves out_amount GROSS, which sizes
// the next hop on money the venue already took.
let trades = self.list_at(order, "trades");
for trade in &trades {
let trade_fee = self.dict_at(trade, "fee");
if self.string_at(&trade_fee, "currency", "").to_uppercase() == asset.to_uppercase() {
total += self.number_at(&trade_fee, "cost", 0.0);
}
}
}
if !Self::is_finite_number(total) || total < 0.0 {
return 0.0;
}
total
}
/// One re-read of an order the venue answered incompletely, falling back to
/// what we already had rather than losing the placement record.
async fn refetch_order(
&self,
venue: &dyn RouterVenue,
order_id: &str,
symbol: &str,
fallback: Value,
) -> Value {
match venue.fetch_order(order_id, symbol).await {
Ok(reread) => reread,
// The caller marks the fill unknown; a failure here must not lose
// the placement record.
Err(_) => fallback,
}
}
/// Re-checks the notional cap immediately before a placement, and does
/// nothing at all when the caller never asked for one.
fn assert_under_cap(
&self,
step: &Value,
amount: f64,
price: f64,
usd_rates: &Value,
options: &Value,
) -> RouterResult<()> {
let cap = self.number_at(options, "maxNotionalUsd", self.max_notional_usd);
if cap <= 0.0 {
// No cap set, so there is nothing to enforce here.
return Ok(());
}
// A PROBE, not the step: `amount` here is the venue-SNAPPED size actually being
// sent, and the step still carries the unsnapped plan amount. notional_usd's
// base-side fallback values the order off `amount`, so passing the step valued the
// wrong quantity — the other five ports have always built this probe.
let mut probe = HashMap::new();
probe.insert("base".to_string(), Value::Str(self.string_at(step, "base", "").into()));
probe.insert("quote".to_string(), Value::Str(self.string_at(step, "quote", "").into()));
probe.insert("amount".to_string(), Value::Float(amount));
let usd_value = self.notional_usd(&Value::Map(probe), amount * price, usd_rates);
if usd_value <= 0.0 {
return Err(exchange_error(
"OrderRouter: refusing to place an order that cannot be valued in USD",
));
}
if usd_value > cap * (1.0 + TOLERANCE) {
return Err(exchange_error(
"OrderRouter: refusing to place an order above the per-trade USD notional cap",
));
}
Ok(())
}
/// Places one order for one step and never returns an error, so that a
/// sibling leg's failure cannot abandon an in-flight order.
async fn place_step(
&self,
step: &Value,
venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
options: &Value,
usd_rates: &Value,
strategy: &str,
report: &mut Value,
) -> Value {
let step_index = self.number_at(step, "stepIndex", -1.0);
let exchange_id = self.string_at(step, "exchangeId", "");
let symbol = self.string_at(step, "symbol", "");
let side = self.string_at(step, "side", "");
let mut result = HashMap::new();
result.insert("stepIndex".into(), Value::Float(step_index));
// Carried from the step, not derived. Without them every result read as
// hopIndex 0, which is what let summarise_report sum a two-hop route's
// spends together — and it is also how a caller tells which hop a result
// belongs to at all.
result.insert("hopIndex".into(), Value::Float(self.number_at(step, "hopIndex", 0.0)));
result.insert("legIndex".into(), Value::Float(self.number_at(step, "legIndex", 0.0)));
result.insert("exchangeId".into(), Value::Str(exchange_id.clone().into()));
result.insert("symbol".into(), Value::Str(symbol.clone().into()));
result.insert("side".into(), Value::Str(side.clone().into()));
result.insert("status".into(), Value::Str("failed".into()));
result.insert("requestedAmount".into(), Value::Float(self.number_at(step, "amount", 0.0)));
result.insert("filledAmount".into(), Value::Float(0.0));
result.insert("averagePrice".into(), Value::Float(0.0));
result.insert("cost".into(), Value::Float(0.0));
result.insert("inAsset".into(), Value::Str(Cow::Borrowed("")));
result.insert("inAmount".into(), Value::Float(0.0));
result.insert("outAsset".into(), Value::Str(Cow::Borrowed("")));
result.insert("outAmount".into(), Value::Float(0.0));
result.insert("orderId".into(), Value::Str(Cow::Borrowed("")));
result.insert("clientOrderId".into(), Value::Str(Cow::Borrowed("")));
result.insert("errorCode".into(), Value::Str(Cow::Borrowed("")));
result.insert("placementAttempted".into(), Value::Bool(false));
let mut result = Value::Map(result);
let venue = match venues.get(&exchange_id) {
Some(found) => found,
None => {
Self::put(&mut result, "errorCode", Value::Str("venue_missing".into()));
self.record_error(report, step_index, &exchange_id, &symbol, "venue_missing");
return result;
}
};
let amount = self.parse_number(&venue.amount_to_precision(&symbol, self.number_at(step, "amount", 0.0)), 0.0);
let price = self.parse_number(&venue.price_to_precision(&symbol, self.step_limit_price(step)), 0.0);
if !(amount > 0.0) || !(price > 0.0) {
Self::put(&mut result, "errorCode", Value::Str("rounded_to_zero".into()));
self.record_error(report, step_index, &exchange_id, &symbol, "rounded_to_zero");
return result;
}
// CLAUDE.md: compute the notional before EVERY createOrder. The
// plan-level check already ran, but the plan can have been resized by a
// reconciliation since, and the snapped price is not the one that was
// checked.
if let Err(e) = self.assert_under_cap(step, amount, price, usd_rates, options) {
// the exception's own class name, exactly as the other five ports record it.
// A hardcoded "over_cap" was wrong twice over: it did not match the five, and
// it labelled the "cannot be valued in USD" refusal — which is not a cap
// breach at all — as though the notional had exceeded the cap.
Self::put(&mut result, "errorCode", Value::Str(e.kind.clone().into()));
self.record_error(report, step_index, &exchange_id, &symbol, &e.kind);
return result;
}
let order_params = self.dict_at(options, "orderParams");
// No clientOrderId is set here. Whatever the caller put in options.orderParams
// travels as-is, and each exchange's create_order keeps sending whatever
// identifier it generates on its own; the id the venue reports back is
// recorded on the result once the order returns. (An id derived from the
// plan identity used to be forced onto every step, but venues disagree on
// its length and charset, so it was rejected exactly where it mattered.)
// The attempt is still recorded: retryFailedSteps re-places a step the venue
// definitively rejected, and the report should say which try produced the result.
let attempt = self.number_at(step, "attempt", 0.0);
Self::put(&mut result, "attempt", Value::Float(attempt));
// Dispatch. `placementAttempted` is set immediately before the call and
// not a line earlier: everything above this point is a refusal that
// cannot have reached a venue.
let order = if strategy == "limit_protected" {
self.place_protected_limit(
venue.as_ref(), step, &symbol, &side, amount, price, &order_params, options,
report, &mut result,
)
.await
} else {
self.place_immediate_order(
venue.as_ref(), &symbol, &side, amount, price, &order_params, options, &mut result,
)
.await
};
let order = match order {
Ok(placed) => {
Self::put(&mut result, "clientOrderId", Value::Str(self.string_at(&placed, "clientOrderId", "").into()));
placed
}
Err(e) => {
Self::put(&mut result, "errorCode", Value::Str(e.kind.clone().into()));
self.record_error(report, step_index, &exchange_id, &symbol, &e.kind);
// createOrder may already have succeeded: every path between it and the final
// read — a poll that times out, a network drop, a cap re-check — leaves a real
// order on a real venue. Reporting the id is the difference between an operator
// who can go cancel it and one who never learns it exists. (This branch was
// missing from the Rust port: a limit_protected order whose poll threw was
// reported as a plain failure with no id anywhere in the report.)
let known_id = self.string_at(&result, "orderId", "");
if !known_id.is_empty() {
// "failed" would read as "nothing happened" while openOrders says the
// opposite, and one report must not carry both readings. Having an id means
// create_order RETURNED — the venue accepted something — so whatever threw
// afterwards left a real order behind whose fill is simply unknown to us.
Self::put(&mut result, "status", Value::Str("outcome_unknown".into()));
self.record_open_order(report, &exchange_id, &symbol, &known_id, "outcome_unknown");
return result;
}
if self.bool_at(&result, "placementAttempted", false) && self.is_outcome_unknown_error(&e) {
// The request may or may not have reached the venue. Halting
// on an unknown quantity is recoverable; concluding that
// nothing was placed is not.
Self::put(&mut result, "status", Value::Str("outcome_unknown".into()));
self.record_unconfirmed_placement(report, &exchange_id, &symbol, "placement_unconfirmed");
}
return result;
}
};
self.settle_order_into_result(&order, step, &mut result, venue.as_ref(), &symbol, &exchange_id, amount, price, report, strategy).await;
result
}
}
impl OrderRouter {
/// Places an immediate-or-cancel limit order, or — only with explicit
/// opt-in — a market order on a venue that cannot do IOC.
async fn place_immediate_order(
&self,
venue: &dyn RouterVenue,
symbol: &str,
side: &str,
amount: f64,
price: f64,
order_params: &Value,
options: &Value,
result: &mut Value,
) -> RouterResult<Value> {
if venue.supports_ioc() {
let mut params = order_params.clone();
Self::put(&mut params, "timeInForce", Value::Str("IOC".into()));
// Set immediately before the call that can leave a real order on a
// real venue, and never reset. Anything that fails before this point
// — a missing venue, a size that rounds to zero, the notional cap, a
// venue that cannot do IOC — dispatched nothing, and recording an
// unconfirmed placement for it would be a false alarm.
Self::put(result, "placementAttempted", Value::Bool(true));
let order = venue.create_order(symbol, "limit", side, amount, price, ¶ms).await?;
Self::put(result, "orderId", Value::Str(self.string_at(&order, "id", "").into()));
return Ok(order);
}
if !self.bool_at(options, "allowMarketOrders", false) {
// A market order is an unbounded price, and switching to one on a
// caller's behalf is exactly the decision they did not delegate.
return Err(ExchangeError::new(
"NotSupported",
"OrderRouter: venue cannot do IOC and allowMarketOrders was not set",
));
}
// A market order and a notional cap cannot both be honoured. assertUnderCap valued this order
// at the plan's LIMIT price, and the call below sends no price at all: the venue fills wherever
// the book is, which is the one thing the cap exists to bound. Passing the check and then
// removing the price it was computed from is a cap that silently disappears, which by this
// file's own rule is not a cap. So the two options are refused together.
if self.number_at(options, "maxNotionalUsd", self.max_notional_usd) > 0.0 {
return Err(ExchangeError::new("NotSupported", "OrderRouter: allowMarketOrders cannot be honoured under a maxNotionalUsd cap, because a market order has no price to check"));
}
Self::put(result, "placementAttempted", Value::Bool(true));
// Price 0 stands for "no price", which is what a market order carries.
let order = venue.create_order(symbol, "market", side, amount, 0.0, order_params).await?;
Self::put(result, "orderId", Value::Str(self.string_at(&order, "id", "").into()));
Ok(order)
}
/// Rests a limit order, then cancels it on timeout and ALWAYS re-reads it,
/// because a cancel and a fill can cross.
#[allow(clippy::too_many_arguments)]
async fn place_protected_limit(
&self,
venue: &dyn RouterVenue,
step: &Value,
symbol: &str,
side: &str,
amount: f64,
price: f64,
order_params: &Value,
options: &Value,
report: &mut Value,
result: &mut Value,
) -> RouterResult<Value> {
let timeout_ms = self.number_at(options, "orderTimeoutMs", 20000.0);
let poll_interval_ms = self.number_at(options, "pollIntervalMs", 1000.0);
Self::put(result, "placementAttempted", Value::Bool(true));
let mut order = venue.create_order(symbol, "limit", side, amount, price, order_params).await?;
let order_id = self.string_at(&order, "id", "");
// Before the first poll, the first sleep and the first thing that can go
// wrong: from here on the caller can always name what is resting.
Self::put(result, "orderId", Value::Str(order_id.clone().into()));
let mut waited = 0.0;
while waited < timeout_ms {
let status = self.string_at(&order, "status", "");
if status == "closed" || status == "canceled" {
return Ok(order);
}
tokio::time::sleep(std::time::Duration::from_millis(poll_interval_ms.max(0.0) as u64)).await;
waited += poll_interval_ms;
order = venue.fetch_order(&order_id, symbol).await?;
}
let final_status = self.string_at(&order, "status", "");
if final_status == "closed" || final_status == "canceled" {
// The venue ended it on the last poll — an expiry, a self-trade
// prevention, a post-only rejection of the remainder. Cancelling an
// order the venue already closed throws, and the partial fill this
// order carries is real: dropping it would hide a live position from
// the report AND from the unwind plan built out of it.
return Ok(order);
}
if venue.cancel_order(&order_id, symbol).await.is_err() {
// The order may still be live. Reporting a fill we did not observe
// would be a lie, and continuing to the next hop on top of an
// unknown position is worse.
self.record_open_order(report, &self.string_at(step, "exchangeId", ""), symbol, &order_id, "cancel_failed");
return Err(exchange_error(
"OrderRouter: cancelOrder failed and an order is left OPEN, refusing to proceed",
));
}
// ALWAYS re-read after a cancel: the cancel and the fill can cross, and
// the observed order is the only authority on what actually happened.
venue.fetch_order(&order_id, symbol).await
}
/// Reads a placed order into the step result: the fill, the direction, the
/// fee netting and the status.
#[allow(clippy::too_many_arguments)]
async fn settle_order_into_result(
&self,
order: &Value,
step: &Value,
result: &mut Value,
venue: &dyn RouterVenue,
symbol: &str,
exchange_id: &str,
amount: f64,
price: f64,
report: &mut Value,
strategy: &str,
) {
let mut order = order.clone();
// "The venue said zero" and "the venue said nothing" are different facts
// and used to produce the same number. A venue that omits `filled`
// yielded 0, reconciliation read that as nothing_filled and halted the
// route — while a real position sat on a real venue. So presence is
// tested, not the value.
let order_id = self.string_at(result, "orderId", "");
if !self.has_number_at(&order, "filled") && !order_id.is_empty() {
// One re-read, exactly as place_protected_limit already does after
// its poll. The immediate path never did, so it could only ever
// fabricate.
order = self.refetch_order(venue, &order_id, symbol, order.clone()).await;
}
// An order the venue explicitly calls open is RESTING, and on this path
// it must not be: place_immediate_order asked for immediate-or-cancel, so
// a venue that silently dropped the timeInForce param has left a plain
// limit order sitting on the book. Recording it and walking on was not
// enough — the next hop then trades on top of a position that keeps
// growing behind it, is sized from a fill that is already out of date, and
// the leftover order is still live after the route has ended and nobody is
// watching it. So it is cancelled and re-read here, exactly as
// place_protected_limit does on its timeout path.
let mut resting_cancel_failed = false;
if strategy != "limit_protected" && self.string_at(&order, "status", "") == "open" && !order_id.is_empty() {
if venue.cancel_order(&order_id, symbol).await.is_err() {
// The order may still be live and its fill can still move, so
// whatever this step reports below is a snapshot that is already
// stale. The status is downgraded after the amounts are filled in,
// not here: a cost the venue DID report is a fact, and
// build_unwind_plan subtracts it.
resting_cancel_failed = true;
} else {
// ALWAYS re-read after a cancel: the cancel and the fill can
// cross, and the observed order is the only authority on what
// actually happened.
order = self.refetch_order(venue, &order_id, symbol, order.clone()).await;
}
}
let filled_known = self.has_number_at(&order, "filled");
let filled = self.number_at(&order, "filled", 0.0);
let average_known = self.has_number_at(&order, "average") || self.has_number_at(&order, "price");
let mut average = self.number_at(&order, "average", 0.0);
if average <= 0.0 {
average = self.number_at(&order, "price", 0.0);
}
if average <= 0.0 {
average = price;
}
let cost_known = self.has_number_at(&order, "cost");
let mut cost = self.number_at(&order, "cost", 0.0);
if cost <= 0.0 {
cost = filled * average;
}
let side = self.string_at(step, "side", "");
Self::put(result, "filledAmount", Value::Float(filled));
Self::put(result, "averagePrice", Value::Float(average));
Self::put(result, "cost", Value::Float(cost));
// Companion flags, per the file's own "was it known" rule. A false here
// means the number beside it is this class's best guess, not the venue's
// answer. This port omitted all three, so a caller reading a Rust report
// could not tell a venue's figure from a fallback.
Self::put(result, "filledKnown", Value::Bool(filled_known));
Self::put(result, "averageKnown", Value::Bool(average_known));
Self::put(result, "costKnown", Value::Bool(cost_known));
if side == "buy" {
Self::put(result, "inAsset", Value::Str(self.string_at(step, "quote", "").into()));
Self::put(result, "inAmount", Value::Float(cost));
Self::put(result, "outAsset", Value::Str(self.string_at(step, "base", "").into()));
Self::put(result, "outAmount", Value::Float(filled));
} else {
Self::put(result, "inAsset", Value::Str(self.string_at(step, "base", "").into()));
Self::put(result, "inAmount", Value::Float(filled));
Self::put(result, "outAsset", Value::Str(self.string_at(step, "quote", "").into()));
Self::put(result, "outAmount", Value::Float(cost));
}
// Net the taker fee out of what is actually CARRIED FORWARD, when the
// venue charged it in the asset this step produced. filled and cost are
// gross of fees — the manual says so — so a venue taking its cut in the
// acquired asset credits less than `filled`, and sizing the next hop (or
// an unwind) on the gross figure orders more than the wallet holds. Fees
// in any OTHER currency are left alone: they do not reduce what this hop
// hands to the next one.
let out_asset = self.string_at(result, "outAsset", "");
let fee_cost = self.order_fee_in_asset(&order, &out_asset);
Self::put(result, "feeCost", Value::Float(fee_cost));
Self::put(result, "feeCurrency", Value::Str(out_asset.into()));
if fee_cost > 0.0 {
let gross = self.number_at(result, "outAmount", 0.0);
let mut net = gross - fee_cost;
if net < 0.0 {
net = 0.0;
}
Self::put(result, "grossOutAmount", Value::Float(gross));
Self::put(result, "outAmount", Value::Float(net));
}
if !filled_known {
// Refuse to reconcile on a fabricated fill: halting on an unknown
// quantity is recoverable, sizing the next hop from an invented
// number is not.
Self::put(result, "status", Value::Str("outcome_unknown".into()));
self.record_open_order(report, exchange_id, symbol, &self.string_at(result, "orderId", ""), "fill_unconfirmed");
// An order WAS placed, and this is exactly the path where knowing
// that matters most. Counted here, as in the other five ports.
Self::put(report, "ordersPlaced", Value::Float(self.number_at(report, "ordersPlaced", 0.0) + 1.0));
return;
}
// No halt on an unknown PRICE. This port had an extra `price_unconfirmed`
// branch that no other has: a fill whose average or cost the venue did
// not report falls back to the order's `price`, then to the limit price,
// and is flagged above rather than stopping the route. The reference
// halts on an unknown FILL — an invented quantity is what makes the next
// hop unsafe — and reports an estimated price as an estimate.
if filled <= 0.0 {
Self::put(result, "status", Value::Str("unfilled".into()));
} else if filled >= amount * (1.0 - TOLERANCE) {
Self::put(result, "status", Value::Str("filled".into()));
} else {
Self::put(result, "status", Value::Str("partial".into()));
}
if resting_cancel_failed {
// A resting order this class could not cancel is the worst outcome
// there is: it can still fill, in full, after the route has returned.
// Sizing the next hop on the fill recorded above would trade against a
// position that is still moving, so the step is marked unknown and
// execute_sequential stops here.
Self::put(result, "status", Value::Str("outcome_unknown".into()));
self.record_open_order(report, exchange_id, symbol, &self.string_at(result, "orderId", ""), "cancel_failed");
} else if self.string_at(&order, "status", "") == "open" {
// Cancelled — or on the limit_protected path, cancelled by
// place_protected_limit — and the venue STILL calls it open. The order
// is live whatever this class asked for, so the same rule applies:
// report it, and refuse to size anything downstream from a fill that
// can still grow.
Self::put(result, "status", Value::Str("outcome_unknown".into()));
self.record_open_order(report, exchange_id, symbol, &self.string_at(result, "orderId", ""), "still_open");
}
Self::put(report, "ordersPlaced", Value::Float(self.number_at(report, "ordersPlaced", 0.0) + 1.0));
}
}
impl OrderRouter {
/// Places one step, re-placing it up to `options["retryFailedSteps"]` times
/// when — and ONLY when — the venue definitively rejected it.
async fn place_step_with_retry(
&self,
step: &Value,
venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
options: &Value,
usd_rates: &Value,
strategy: &str,
report: &mut Value,
) -> Value {
let max_retries = self.number_at(options, "retryFailedSteps", 0.0);
let retry_delay_ms = self.number_at(options, "retryDelayMs", DEFAULT_RETRY_DELAY_MS);
let mut attempt = 0.0f64;
loop {
let mut attempted = step.clone();
Self::put(&mut attempted, "attempt", Value::Float(attempt));
let result = self.place_step(&attempted, venues, options, usd_rates, strategy, report).await;
let status = self.string_at(&result, "status", "");
// "failed" is the ONLY retryable outcome, and the distinction is the whole safety
// argument. A failed step was refused by the venue: nothing was placed, so placing
// it again cannot double-fill. An "outcome_unknown" step may ALREADY be a live
// position that simply could not be read back, and re-placing that is precisely the
// double-fill this class exists to prevent. It is never retried, at any setting.
if status != "failed" || attempt >= max_retries {
return result;
}
attempt += 1.0;
if retry_delay_ms > 0.0 {
tokio::time::sleep(std::time::Duration::from_millis(retry_delay_ms.max(0.0) as u64)).await;
}
}
}
/// Hands the caller's `onStep` hook one finished step and returns its
/// verdict, treating any failure of the hook as "no opinion".
///
/// `options` is taken, and deliberately unused, so that this method reads
/// the same as the other five ports at every call site. In THIS port the
/// hook itself lives on the router (see `OnStepHook`), because `Value`
/// cannot carry a closure.
fn call_on_step(
&self,
options: &Value,
report: &mut Value,
result: &Value,
reconciliation: &Value,
step_index: usize,
steps_total: usize,
) -> String {
let _ = options;
let hook = match &self.on_step {
Some(found) => Arc::clone(found),
None => return String::new(),
};
let mut event = HashMap::new();
event.insert("planId".to_string(), Value::Str(self.string_at(report, "planId", "").into()));
event.insert("stepIndex".to_string(), Value::Float(step_index as f64));
event.insert("hopIndex".to_string(), Value::Float(self.number_at(result, "hopIndex", 0.0)));
event.insert("legIndex".to_string(), Value::Float(self.number_at(result, "legIndex", 0.0)));
event.insert("exchangeId".to_string(), Value::Str(self.string_at(result, "exchangeId", "").into()));
event.insert("symbol".to_string(), Value::Str(self.string_at(result, "symbol", "").into()));
event.insert("side".to_string(), Value::Str(self.string_at(result, "side", "").into()));
event.insert("status".to_string(), Value::Str(self.string_at(result, "status", "").into()));
event.insert("requestedAmount".to_string(), Value::Float(self.number_at(result, "requestedAmount", 0.0)));
event.insert("filledAmount".to_string(), Value::Float(self.number_at(result, "filledAmount", 0.0)));
event.insert("outAsset".to_string(), Value::Str(self.string_at(result, "outAsset", "").into()));
event.insert("outAmount".to_string(), Value::Float(self.number_at(result, "outAmount", 0.0)));
event.insert("orderId".to_string(), Value::Str(self.string_at(result, "orderId", "").into()));
event.insert("clientOrderId".to_string(), Value::Str(self.string_at(result, "clientOrderId", "").into()));
event.insert("errorCode".to_string(), Value::Str(self.string_at(result, "errorCode", "").into()));
event.insert("attempt".to_string(), Value::Float(self.number_at(result, "attempt", 0.0)));
event.insert("reconciliation".to_string(), reconciliation.clone());
event.insert("ordersPlaced".to_string(), Value::Float(self.number_at(report, "ordersPlaced", 0.0)));
event.insert("halted".to_string(), Value::Bool(self.bool_at(report, "halted", false)));
event.insert("haltReason".to_string(), Value::Str(self.string_at(report, "haltReason", "").into()));
event.insert("stepsTotal".to_string(), Value::Float(steps_total as f64));
event.insert("stepsRemaining".to_string(), Value::Float((steps_total - (step_index + 1)) as f64));
let event = Value::Map(event);
// A hook that PANICS must NOT take the run with it — the Rust form of the try/catch
// the other ports use, and of Go's defer/recover. Everything placed so far is recorded
// in this report, and losing it to a panic raised by observability code would destroy
// the only account of orders that are already live. `catch_unwind` is the right tool
// here and only here: the hook is caller code we make no assumptions about, it is
// handed an owned event and shares no mutable state with the router (hence
// `AssertUnwindSafe`), and the run continues afterwards as if it had no opinion.
// It does NOT contain an abort — a panic=abort profile takes the process down, which
// no language-level construct in any of the six ports can prevent.
let verdict = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| hook(&event)));
match verdict {
Ok(spoken) => {
if spoken == "halt" {
return "halt".to_string();
}
String::new()
}
Err(_) => {
// Rust panics carry no error TYPE to name, unlike the class name the other
// five ports report, so the code is a fixed "panic".
self.record_error(
report,
step_index as f64,
&self.string_at(result, "exchangeId", ""),
&self.string_at(result, "symbol", ""),
"on_step_hook_failed:panic",
);
String::new()
}
}
}
}
impl OrderRouter {
/// Places one order at a time in plan order, reconciling after each and
/// obeying the halt verdict.
async fn execute_sequential(
&self,
report: &mut Value,
steps: &mut Vec<Value>,
venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
options: &Value,
usd_rates: &Value,
strategy: &str,
) {
for i in 0..steps.len() {
let step = steps[i].clone();
let result = self.place_step_with_retry(&step, venues, options, usd_rates, strategy, report).await;
let mut results = self.list_at(report, "steps");
results[i] = result.clone();
Self::put(report, "steps", Value::List(results));
let status = self.string_at(&result, "status", "");
if status == "failed" || status == "outcome_unknown" {
Self::put(report, "halted", Value::Bool(true));
// An unknown outcome must NOT fall through to reconciliation:
// reconciling reads outAmount, which is 0 because nothing was
// observed, and reports the halt as "nothing_filled" — asserting
// the one thing we do not know.
let reason = if status == "failed" { "order_failed" } else { "outcome_unknown" };
Self::put(report, "haltReason", Value::Str(reason.into()));
Self::put(report, "haltStepIndex", Value::Float(i as f64));
// the hook is told about a halt it did not cause, and cannot undo it
self.call_on_step(options, report, &result, &Value::Map(HashMap::new()), i, steps.len());
self.mark_remaining_skipped(report, i + 1);
return;
}
let mut reconcile_plan = HashMap::new();
reconcile_plan.insert("steps".to_string(), Value::List(steps.clone()));
reconcile_plan.insert(
"reconcileToleranceRatio".to_string(),
Value::Float(self.number_at(report, "reconcileToleranceRatio", DEFAULT_RECONCILE_TOLERANCE)),
);
let reconciliation = match self.reconcile_execution_step(
&Value::Map(reconcile_plan), i as i64, self.number_at(&result, "outAmount", 0.0),
) {
Ok(verdict) => verdict,
Err(_) => return,
};
Self::append_to(report, "reconciliations", reconciliation.clone());
if strategy != "atomic_ish" {
// atomic_ish is pre-funded end to end, so a hop's shortfall does
// not shrink the next hop's order — the money for it was already
// there before the first order went out.
self.apply_resize(steps, &reconciliation);
}
if self.string_at(&reconciliation, "verdict", "") == "halt" {
Self::put(report, "halted", Value::Bool(true));
Self::put(report, "haltReason", Value::Str(self.string_at(&reconciliation, "reason", "").into()));
Self::put(report, "haltStepIndex", Value::Float(i as f64));
self.call_on_step(options, report, &result, &reconciliation, i, steps.len());
self.mark_remaining_skipped(report, i + 1);
return;
}
// the caller's own verdict, consulted only once the route is otherwise sound. It
// can stop the route; it cannot restart one the reconciliation above already
// stopped.
if self.call_on_step(options, report, &result, &reconciliation, i, steps.len()) == "halt" {
Self::put(report, "halted", Value::Bool(true));
Self::put(report, "haltReason", Value::Str("halted_by_on_step".into()));
Self::put(report, "haltStepIndex", Value::Float(i as f64));
self.mark_remaining_skipped(report, i + 1);
return;
}
}
}
/// Runs the legs of one hop concurrently ACROSS venues and serially WITHIN
/// a venue, and the hops strictly in order.
async fn execute_parallel_within_hop(
&self,
report: &mut Value,
steps: &mut Vec<Value>,
venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
options: &Value,
usd_rates: &Value,
) {
let mut cursor = 0usize;
while cursor < steps.len() {
let hop_index = self.number_at(&steps[cursor], "hopIndex", 0.0);
let mut end = cursor;
while end < steps.len() && self.number_at(&steps[end], "hopIndex", 0.0) == hop_index {
end += 1;
}
// THE CONTRACT: concurrent ACROSS venues, serialised WITHIN a venue.
// It is an ordering guarantee, not a performance promise, which is
// what lets six very different runtimes honour the same words. Two
// legs of one hop that land on the SAME venue must never have two
// orders in flight against that venue's throttle and nonce state.
//
// DIVERGENCE, recorded rather than hidden: TypeScript, Python, C#
// and Go run the venue groups concurrently. This port runs them one
// after another. `place_step` takes `&mut Value` for the report, so
// concurrent groups would need the report behind a lock, and a lock
// around every record_error/record_open_order is a great deal of
// machinery to buy back parallelism the contract does not promise.
// Serialising everything satisfies the ordering guarantee strictly
// more than grouping does — it is what the PHP port does, for the
// same reason — so the report is identical either way.
let mut group_ids: Vec<String> = Vec::new();
for i in cursor..end {
let exchange_id = self.string_at(&steps[i], "exchangeId", "");
if !group_ids.contains(&exchange_id) {
group_ids.push(exchange_id);
}
}
for group in &group_ids {
for i in cursor..end {
if self.string_at(&steps[i], "exchangeId", "") != *group {
continue;
}
let step = steps[i].clone();
let result = self
.place_step_with_retry(&step, venues, options, usd_rates, "parallel_within_hop", report)
.await;
let mut results = self.list_at(report, "steps");
results[i] = result;
Self::put(report, "steps", Value::List(results));
}
}
for i in cursor..end {
let results = self.list_at(report, "steps");
let result = results[i].clone();
let status = self.string_at(&result, "status", "");
if status == "failed" || status == "outcome_unknown" {
Self::put(report, "halted", Value::Bool(true));
let reason = if status == "failed" { "order_failed" } else { "outcome_unknown" };
Self::put(report, "haltReason", Value::Str(reason.into()));
Self::put(report, "haltStepIndex", Value::Float(i as f64));
self.call_on_step(options, report, &result, &Value::Map(HashMap::new()), i, steps.len());
self.mark_remaining_skipped(report, end);
return;
}
let mut reconcile_plan = HashMap::new();
reconcile_plan.insert("steps".to_string(), Value::List(steps.clone()));
reconcile_plan.insert(
"reconcileToleranceRatio".to_string(),
Value::Float(self.number_at(report, "reconcileToleranceRatio", DEFAULT_RECONCILE_TOLERANCE)),
);
let reconciliation = match self.reconcile_execution_step(
&Value::Map(reconcile_plan), i as i64, self.number_at(&result, "outAmount", 0.0),
) {
Ok(verdict) => verdict,
Err(_) => return,
};
Self::append_to(report, "reconciliations", reconciliation.clone());
self.apply_resize(steps, &reconciliation);
if self.string_at(&reconciliation, "verdict", "") == "halt" {
Self::put(report, "halted", Value::Bool(true));
Self::put(report, "haltReason", Value::Str(self.string_at(&reconciliation, "reason", "").into()));
Self::put(report, "haltStepIndex", Value::Float(i as f64));
self.call_on_step(options, report, &result, &reconciliation, i, steps.len());
self.mark_remaining_skipped(report, end);
return;
}
if self.call_on_step(options, report, &result, &reconciliation, i, steps.len()) == "halt" {
Self::put(report, "halted", Value::Bool(true));
Self::put(report, "haltReason", Value::Str("halted_by_on_step".into()));
Self::put(report, "haltStepIndex", Value::Float(i as f64));
self.mark_remaining_skipped(report, end);
return;
}
}
cursor = end;
}
}
/// Places what it can and never halts, on a single hop only, up to
/// maxOrders.
async fn execute_best_effort(
&self,
report: &mut Value,
steps: &mut [Value],
venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
options: &Value,
usd_rates: &Value,
) {
let max_orders = self.number_at(options, "maxOrders", 0.0);
let mut placed = 0.0;
for i in 0..steps.len() {
let mut results = self.list_at(report, "steps");
if placed >= max_orders {
Self::put(&mut results[i], "status", Value::Str("skipped".into()));
Self::put(&mut results[i], "errorCode", Value::Str("max_orders_reached".into()));
Self::put(report, "steps", Value::List(results));
continue;
}
let step = steps[i].clone();
let result = self.place_step_with_retry(&step, venues, options, usd_rates, "best_effort", report).await;
let mut results = self.list_at(report, "steps");
results[i] = result.clone();
Self::put(report, "steps", Value::List(results));
placed += 1.0;
// No reconciliation and no halt: that is the whole point of the strategy, and why
// it is refused on anything but a single hop. The hook is still offered every step,
// and stopping early is the one thing it may do here — that is a smaller commitment
// than the strategy's own contract, never a larger one.
if self.call_on_step(options, report, &result, &Value::Map(HashMap::new()), i, steps.len()) == "halt" {
Self::put(report, "halted", Value::Bool(true));
Self::put(report, "haltReason", Value::Str("halted_by_on_step".into()));
Self::put(report, "haltStepIndex", Value::Float(i as f64));
self.mark_remaining_skipped(report, i + 1);
return;
}
}
}
/// Executes a plan against live venues. THE ONLY IMPURE METHOD.
///
/// `dry_run` is the default, and `options.live != true` forces `dry_run`
/// regardless of the strategy requested, so a call that looks live but
/// forgot the flag places nothing.
///
/// `plan` is a plan from `build_execution_plan`, OR a caller-assembled plan of
/// the same shape — this method never assumes the plan came from the routing
/// service. `options.idempotencyKey` is the identity of this execution,
/// required when the plan carries no `requestId`; it keys the re-execution
/// guard and overrides the plan's `requestId` when both are given.
/// `options.allowReexecution` must be exactly true to run a plan this instance
/// has already executed live; the DEFAULT is refusal.
///
/// `options.retryFailedSteps` is how many times to re-place a step the venue
/// DEFINITIVELY REJECTED, default 0. An `outcome_unknown` step is never
/// retried at any setting: it may already be a live position, and re-placing
/// it is the double-fill this class exists to prevent. `options.retryDelayMs`
/// is how long to wait before a retry, default `DEFAULT_RETRY_DELAY_MS` (1000).
///
/// The third option the other five ports read out of `options` — `onStep` —
/// is set on the router instead, by `set_on_step`; `Value` cannot carry a
/// closure. See `OnStepHook`.
pub async fn execute(
&self,
plan: &Value,
venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
options: &Value,
) -> RouterResult<Value> {
// the argument wins; the router's own venues are the fallback. Nothing is ever
// CONSTRUCTED here - this is the money path.
let venues = if venues.is_empty() { &self.venues } else { venues };
// plan-shaping options cannot be honoured once the plan exists
if !self.list_at(plan, "steps").is_empty() {
self.assert_no_plan_shaping_options(options)?;
}
// A ROUTE is accepted here as well as a plan. buildExecutionPlan is pure and derives
// entirely from the route, so requiring the caller to run it first was ceremony: two
// calls that can only ever happen in that order, with nothing to do in between unless
// you actually want to inspect the plan. Told apart by shape rather than by a flag - a
// route carries `hops`, a plan carries `steps`, and nothing carries both.
let built_from_route;
let plan = if self.list_at(plan, "steps").is_empty() && !self.list_at(plan, "hops").is_empty() {
built_from_route = self.build_execution_plan(plan, options)?;
&built_from_route
} else {
plan
};
let requested_strategy = self.string_at(options, "strategy", "sequential");
if !KNOWN_STRATEGIES.contains(&requested_strategy.as_str()) {
return Err(bad_request(&format!(
"OrderRouter: unknown execution strategy {requested_strategy}"
)));
}
// PLACING IS THE DEFAULT, and ONE knob decides it: `strategy` says only HOW,
// `dryRun` says only WHETHER. The guardrails that do the work all still run
// BEFORE anything is sent.
let strategy = requested_strategy.clone();
// REFUSED, not ignored. `live` was the old knob and it is gone; `live: false` meant
// "place nothing" and now means nothing at all, so ignoring it silently would send
// the orders while the caller believed they had opted out.
if field(options, "live").is_some() {
return Err(bad_request(
"OrderRouter: options.live is gone — execute places orders, and a rehearsal is asked for with dryRun. Remove live, or pass dryRun to place nothing",
));
}
let dry_run = self.is_exactly_true(options, "dryRun");
let mut steps = self.clone_steps(plan);
let mut report = self.empty_report(plan, &strategy, dry_run, &steps);
// Resolved from BOTH the plan and the options, so a hand-assembled plan can
// carry an identity too; reported on every report, rehearsals included.
let plan_id = self.plan_identity(plan, options);
Self::put(&mut report, "planId", Value::Str(plan_id.clone().into()));
// How old the prices in this plan are. ALWAYS reported, even when nothing is enforced: a plan
// is a snapshot of a book, and how stale that snapshot is decides whether any number in it
// means anything. -1 when the route carried no calculatedAt, which is not the same as "fresh"
// and must not read like it. Enforced only if asked for, at whatever value is asked for — the
// same shape as maxNotionalUsd, and for the same reason. But an age that cannot be determined
// BLOCKS under an active limit: a freshness check that silently passes when the timestamp is
// missing is not a freshness check.
let calculated_at = self.number_at(plan, "calculatedAt", 0.0);
let plan_age_ms = if calculated_at > 0.0 { self.now_ms() - calculated_at } else { -1.0 };
Self::put(&mut report, "planAgeMs", Value::Float(plan_age_ms));
let max_plan_age_ms = self.number_at(options, "maxPlanAgeMs", 0.0);
if !dry_run && max_plan_age_ms > 0.0 {
if plan_age_ms < 0.0 {
return Err(exchange_error("OrderRouter: refusing to execute, the plan carries no calculatedAt and maxPlanAgeMs was set"));
}
if plan_age_ms > max_plan_age_ms {
return Err(exchange_error("OrderRouter: refusing to execute a plan older than maxPlanAgeMs, recompute the route"));
}
}
if dry_run {
// Not one call is made against a venue on this path, not even a read.
Self::put(&mut report, "wouldPlaceOrders", Value::Float(steps.len() as f64));
return Ok(report);
}
if venues.is_empty() {
return Err(arguments_required(
"OrderRouter.execute requires a venues dictionary when live",
));
}
// IDEMPOTENCY, half one: a plan this instance has already run live is
// REFUSED, and refused here — before a single read reaches a venue. The
// ledger is consulted now and written only once the plan is about to be
// dispatched, so a caller error that placed nothing does not burn the plan.
// dry_run never reaches this line and never consumes a plan, because a
// rehearsal places nothing.
if plan_id.is_empty() {
// No identity means no idempotency: the ledger below cannot key on it,
// so a re-run of this plan would be indistinguishable from a first run.
return Err(bad_request("OrderRouter: refusing to execute live without an identity, the plan carries no requestId — pass options.idempotencyKey"));
}
if !self.bool_at(options, "allowReexecution", false) {
let ledger = self.executed_plan_ids.lock().unwrap();
if ledger.contains(&plan_id) {
return Err(bad_request("OrderRouter: refusing to re-execute a plan this instance already executed, pass allowReexecution to override"));
}
}
// Derived from the steps about to be executed, NEVER read off the plan:
// a plan that travelled through JSON, a persisted step list or a
// hand-rebuilt tail of a halted route can be missing hopCount, and a
// refusal that a missing key switches off is not a refusal.
let hop_count = self.hop_count_of(&steps);
if strategy == "best_effort" {
if hop_count > 1 {
// Best-effort multi-hop is the most reliable way to strand money
// in a bridge asset.
return Err(ExchangeError::new(
"NotSupported",
"OrderRouter: best_effort refuses multi-hop routes",
));
}
if !self.bool_at(options, "acknowledgeDispersion", false) {
return Err(bad_request("OrderRouter: best_effort requires acknowledgeDispersion"));
}
if self.number_at(options, "maxOrders", 0.0) <= 0.0 {
return Err(bad_request("OrderRouter: best_effort requires a positive maxOrders"));
}
}
if strategy == "limit_protected" {
// Refused HERE, before a single order is placed, because the alternative is worse than a
// bad interval: the poll loop advances its clock by this value, so a zero or negative one
// never reaches the timeout. It spins on fetchOrder forever with a real order resting on a
// real venue, and the timeout that exists to cancel that order never arrives.
if self.has_number_at(options, "pollIntervalMs")
&& self.number_at(options, "pollIntervalMs", 0.0) <= 0.0
{
return Err(bad_request("OrderRouter: pollIntervalMs must be positive, a resting order is polled on that clock"));
}
}
// Markets are needed for the safety check and for precision snapping.
// The caller supplies them: unlike the other five ports, this one cannot
// call loadMarkets() through the venue trait — adding it there would put
// a method on the trait that only this line uses, and every implementor
// would have to write it.
let markets = self.dict_at(options, "markets");
let usd_rates = self.dict_at(options, "usdRates");
let mut safety_options = HashMap::new();
safety_options.insert("usdRates".to_string(), usd_rates.clone());
safety_options.insert(
"maxNotionalUsd".to_string(),
Value::Float(self.number_at(options, "maxNotionalUsd", self.max_notional_usd)),
);
safety_options.insert(
"precisionMode".to_string(),
Value::Str(self.string_at(options, "precisionMode", "tick_size").into()),
);
let violations = self.check_execution_plan_safety(plan, &markets, &Value::Map(safety_options));
let mut blockers: Vec<String> = Vec::new();
for violation in &violations {
if self.bool_at(violation, "blocking", false) {
blockers.push(self.string_at(violation, "code", ""));
}
}
if !blockers.is_empty() {
// Returned as an error, not reported. A refusal a caller can forget
// to read is not a refusal.
return Err(exchange_error(&format!(
"OrderRouter: refusing to execute, blocking safety violations: {}{}",
blockers.join(", "),
// notional_unvaluable gets its CAUSE named rather than its symptom: the cap
// and the rates are one guardrail in two parts, and a caller who set
// maxNotionalUsd believes they are protected.
if blockers.iter().any(|code| code == "notional_unvaluable")
&& usd_rates.as_map().map(|m| m.is_empty()).unwrap_or(true)
{
" - maxNotionalUsd is set but options.usdRates is empty, and the cap cannot be evaluated without a USD price for the quote currency"
} else {
""
}
)));
}
if strategy == "atomic_ish" {
// The check the strategy is NAMED for. Without it this port accepted
// atomic_ish, skipped the downstream resize that every other strategy
// performs — on the strength of the route being pre-funded end to
// end — and then never established that it was. A short hop would
// have sized the next one off proceeds it did not have.
self.assert_prefunded(&steps, venues).await?;
}
// The ledger is written BEFORE the first order goes out, never after: a run
// that fails half way through has still placed orders, and a guard that only
// recorded completed runs would wave through exactly the retry that
// double-fills.
{
let mut ledger = self.executed_plan_ids.lock().unwrap();
ledger.record(plan_id.clone());
}
// From here orders go out, so whatever balances were cached are about to be
// wrong. Dropped BEFORE dispatch, for the same reason the ledger is written
// here: a run that fails half way through has still moved money.
self.invalidate_balances();
if strategy == "parallel_within_hop" {
self.execute_parallel_within_hop(&mut report, &mut steps, venues, options, &usd_rates).await;
} else if strategy == "best_effort" {
self.execute_best_effort(&mut report, &mut steps, venues, options, &usd_rates).await;
} else {
// sequential, limit_protected and atomic_ish all walk the plan one
// order at a time; they differ in how a single order is placed and in
// whether they lean on the previous hop's proceeds.
self.execute_sequential(&mut report, &mut steps, venues, options, &usd_rates, &strategy).await;
}
// and AGAIN on the way out: a quote issued while the orders were in flight
// repopulates the cache from wallets that had not settled yet.
self.invalidate_balances();
self.summarise_report(&mut report, &steps);
Ok(report)
}
}
impl OrderRouter {
/// Verifies every step's input is already sitting on its venue, which is what
/// `atomic_ish` actually requires. There is no cross-venue atomicity and there
/// cannot be, so the strategy names its own hedge: pre-fund the whole route,
/// and no hop then depends on the previous one settling.
///
/// Most routes fail this, and that is the correct outcome.
async fn assert_prefunded(
&self,
steps: &[Value],
venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
) -> RouterResult<()> {
// Built as a Vec, not a map, so the first shortfall reported is the same
// one in all six languages.
let mut required: Vec<(String, String, f64)> = Vec::new();
for step in steps {
let exchange_id = self.string_at(step, "exchangeId", "");
let amount = self.number_at(step, "amount", 0.0);
let (asset, needed) = if self.string_at(step, "side", "") == "buy" {
(self.string_at(step, "quote", ""), amount * self.step_limit_price(step))
} else {
(self.string_at(step, "base", ""), amount)
};
let mut found = false;
for entry in required.iter_mut() {
if entry.0 == exchange_id && entry.1 == asset {
entry.2 += needed;
found = true;
break;
}
}
if !found {
required.push((exchange_id, asset, needed));
}
}
// One fetch_balance per venue, cached: a route with four hops on one
// exchange must not cost four balance calls.
let mut balances: HashMap<String, Value> = HashMap::new();
for (exchange_id, asset, needed) in &required {
if !balances.contains_key(exchange_id) {
let venue = match venues.get(exchange_id) {
Some(found) => found,
None => {
return Err(exchange_error(&format!(
"OrderRouter: atomic_ish cannot check funding, no venue was passed for {exchange_id}"
)))
}
};
balances.insert(exchange_id.clone(), venue.fetch_balance().await?);
}
let balance = balances.get(exchange_id).expect("just inserted");
let free = self.dict_at(balance, "free");
let available = self.number_at(&free, asset, 0.0);
if available < *needed {
return Err(insufficient_funds(&format!(
"OrderRouter: atomic_ish requires the whole route pre-funded, and {exchange_id} is short of {asset}"
)));
}
}
Ok(())
}
// NO markets_of HERE, and it is not an omission. The other five ports offer one because
// their venues expose their markets; `RouterVenue` deliberately does not — it is narrowed
// to the operations the money path performs — so Rust's execute reads `options.markets`
// and the caller assembles that dict either way. A helper taking venues would have
// nothing to read.
/// Refuses plan-shaping options alongside an already-built plan, where they cannot apply.
pub fn assert_no_plan_shaping_options(&self, options: &Value) -> RouterResult<()> {
for key in ["slippageBps", "reconcileToleranceRatio"] {
if field(options, key).is_some() {
return Err(bad_request(&format!(
"OrderRouter: {key} shapes a plan and this plan is already built, so it cannot be applied - pass it to build_execution_plan, or hand execute the route instead of the plan"
)));
}
}
Ok(())
}
/// Turns whatever a caller wrote for `balances` into the router's wire form: the rendered
/// string itself, a list of entries, a per-venue wallet, or a flat single-venue wallet.
pub fn render_balances(&self, value: &Value) -> RouterResult<String> {
if let Value::Str(text) = value {
return Ok(text.to_string());
}
if let Value::Arr(_) = value {
return self.query_text(value);
}
match value.as_map() {
Some(map) => {
// Two shapes, told apart by what the values are: a per-venue wallet nests one
// level, a flat wallet does not. Zero holdings are dropped.
let mut outer_keys: Vec<String> = map.keys().cloned().collect();
outer_keys.sort();
let mut entries: Vec<Value> = Vec::new();
for outer in outer_keys.iter() {
let inner = map.get(outer);
let nested = match inner {
Some(found) => found.as_map(),
None => None,
};
if let Some(wallet) = nested {
let mut codes: Vec<String> = wallet.keys().cloned().collect();
codes.sort();
for code in codes.iter() {
let amount = self.number_at(inner.unwrap(), code, 0.0);
if amount > 0.0 {
let mut entry = HashMap::new();
entry.insert("exchangeId".to_string(), Value::Str(outer.clone().into()));
entry.insert("asset".to_string(), Value::Str(code.clone().into()));
entry.insert("amount".to_string(), Value::Float(amount));
entries.push(Value::Map(entry));
}
}
continue;
}
let amount = self.number_at(value, outer, 0.0);
if amount > 0.0 {
// no venue: a bare ASSET:amount means "wherever you hold it"
let mut entry = HashMap::new();
entry.insert("exchangeId".to_string(), Value::Str(Cow::Borrowed("")));
entry.insert("asset".to_string(), Value::Str(outer.clone().into()));
entry.insert("amount".to_string(), Value::Float(amount));
entries.push(Value::Map(entry));
}
}
self.join_balances(&entries)
}
None => Err(bad_request(
"OrderRouter: balances must be \"[exchangeId.]ASSET:amount\" entries, or a wallet like {\"mexc\": {\"USDT\": 100}} or {\"USDT\": 100}",
)),
}
}
pub(crate) fn join_balances(&self, entries: &[Value]) -> RouterResult<String> {
let mut text = String::new();
for (i, entry) in entries.iter().enumerate() {
if i > 0 {
text.push(',');
}
// a bare ASSET:amount, with no venue, means "wherever you hold it"
let venue_prefix = self.string_at(entry, "exchangeId", "");
if !venue_prefix.is_empty() {
text.push_str(&venue_prefix);
text.push('.');
}
text.push_str(&self.string_at(entry, "asset", ""));
text.push(':');
text.push_str(&self.format_number(self.number_at(entry, "amount", 0.0))?);
}
Ok(text)
}
/// Reads the live balances of the supplied venues, sends them to the router,
/// and returns a route you can actually fund.
///
/// The returned route carries two client-side additions: `balancesUsed`,
/// the exact string sent, and `balancesDropped`, everything that did not fit
/// and why.
/// Reads the venues' wallets once and caches the result, so a quote stays a single HTTP
/// request. Called for you by `fetch_route`; call it yourself to prime the cache at
/// start-up, or with `reload` to refresh it.
pub async fn load_balances(&self, reload: bool) -> RouterResult<String> {
if !self.track_balances || self.venues.is_empty() {
// not this router's job: it was not asked to manage balances
return Ok(String::new());
}
if !reload {
if let Ok(guard) = self.balances_cache.lock() {
if let Some(cached) = guard.as_ref() {
return Ok(cached.clone());
}
}
}
let generation = self
.balances_generation
.load(std::sync::atomic::Ordering::SeqCst);
let (balances, _dropped) = self.collect_balances(&self.venues).await?;
// an invalidation landed while these wallets were being read, which means money
// moved under this snapshot. It is still the right answer for THIS caller, but it
// must not become the cache the next quote trusts.
if generation
== self
.balances_generation
.load(std::sync::atomic::Ordering::SeqCst)
{
if let Ok(mut guard) = self.balances_cache.lock() {
*guard = Some(balances.clone());
}
}
Ok(balances)
}
/// Drops the cached balances, so the next quote re-reads the wallets.
pub fn invalidate_balances(&self) {
self.balances_generation
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
if let Ok(mut guard) = self.balances_cache.lock() {
*guard = None;
}
}
/// Reports whether a balances snapshot is currently cached.
pub fn balances_are_loaded(&self) -> bool {
match self.balances_cache.lock() {
Ok(guard) => guard.is_some(),
Err(_) => false,
}
}
/// Reads every supplied venue's wallet and renders it as the router's balances string,
/// trimmed to the router's caps. Returns the string and the entries that did not fit.
pub async fn collect_balances(
&self,
venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
) -> RouterResult<(String, Vec<Value>)> {
let mut entries: Vec<Value> = Vec::new();
let mut dropped: Vec<Value> = Vec::new();
// BTreeMap iterates in key order, which is the sort the other five ports
// do explicitly — six languages must build the same string from the same
// wallet.
for (exchange_id, venue) in venues.iter() {
let balance = venue.fetch_balance().await?;
let mut holdings = self.dict_at(&balance, "free");
if holdings.as_map().map(|m| m.is_empty()).unwrap_or(true) {
holdings = self.dict_at(&balance, "total");
}
let mut codes: Vec<String> = match holdings.as_map() {
Some(map) => map.keys().cloned().collect(),
None => Vec::new(),
};
codes.sort();
for code in &codes {
let amount = self.number_at(&holdings, code, 0.0);
if amount <= 0.0 {
// A zero holding is not information, and it costs one of the
// router's 64 entries.
continue;
}
let mut entry = HashMap::new();
entry.insert("exchangeId".to_string(), Value::Str(exchange_id.clone().into()));
entry.insert("asset".to_string(), Value::Str(code.clone().into()));
entry.insert("amount".to_string(), Value::Float(amount));
if amount >= 1e18 {
// Beyond fixed-point rendering; reported rather than sent,
// because a silently reshaped amount is worse than a missing
// one.
entry.insert("reason".to_string(), Value::Str("amount_out_of_range".to_string().into()));
dropped.push(Value::Map(entry));
continue;
}
entries.push(Value::Map(entry));
}
}
// Largest first, so trimming to the router's caps drops the smallest
// holdings. Ties break on exchangeId then asset so six languages produce
// the same list from the same wallet.
entries.sort_by(|a, b| {
let amount_a = self.number_at(a, "amount", 0.0);
let amount_b = self.number_at(b, "amount", 0.0);
if amount_a != amount_b {
// Descending. partial_cmp cannot be None here: number_at only
// ever returns a finite number.
return amount_b.partial_cmp(&amount_a).unwrap_or(std::cmp::Ordering::Equal);
}
let id_a = self.string_at(a, "exchangeId", "");
let id_b = self.string_at(b, "exchangeId", "");
if id_a != id_b {
return id_a.cmp(&id_b);
}
self.string_at(a, "asset", "").cmp(&self.string_at(b, "asset", ""))
});
while entries.len() > MAX_BALANCE_ENTRIES {
let mut removed = entries.pop().expect("entries is non-empty inside this loop");
Self::put(&mut removed, "reason", Value::Str("entry_cap".to_string().into()));
dropped.push(removed);
}
let mut balances = self.join_balances(&entries)?;
while balances.len() > MAX_BALANCE_CHARS && !entries.is_empty() {
let mut removed = entries.pop().expect("entries is non-empty inside this loop");
Self::put(&mut removed, "reason", Value::Str("char_cap".to_string().into()));
dropped.push(removed);
balances = self.join_balances(&entries)?;
}
Ok((balances, dropped))
}
pub async fn fetch_route_with_balances(
&self,
from_asset: &str,
to_asset: &str,
venues: &std::collections::BTreeMap<String, Box<dyn RouterVenue>>,
params: &Value,
) -> RouterResult<Value> {
let require_applied = self.bool_at(params, "requireBalancesApplied", true);
let venues = if venues.is_empty() { &self.venues } else { venues };
let (balances, dropped) = self.collect_balances(venues).await?;
let mut route_params = HashMap::new();
if let Some(map) = params.as_map() {
for (key, value) in map.iter() {
route_params.insert(key.clone(), value.clone());
}
}
route_params.insert("balances".to_string(), Value::Str(balances.clone().into()));
let mut route = self.fetch_route(from_asset, to_asset, &Value::Map(route_params)).await?;
if require_applied && !balances.is_empty() && self.string_at(&route, "balancesApplied", "").is_empty() {
// /route declares its query without a JSON schema, so a router that
// predates the balances feature answers byte-identically to one that
// never received it. Executing a plan computed against a portfolio
// the server never saw is the case worth failing on.
return Err(exchange_error(
"OrderRouter did not echo balancesApplied: the balances were ignored, so this route is not funded-aware",
));
}
Self::put(&mut route, "balancesUsed", Value::Str(balances.into()));
Self::put(&mut route, "balancesDropped", Value::List(dropped));
Ok(route)
}
}