of_execution_algos 0.1.0

Parent/child execution algorithm primitives for Orderflow
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
//! Parent/child execution algorithm primitives for Orderflow.
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]

use std::error::Error;
use std::fmt;

use of_execution_core::{
    AccountId, ClientOrderId, ExecutionCoreError, ExecutionEvent, ExecutionId, ExecutionSymbol,
    ExecutionText, ExecutionType, FixedAscii, OrderPrice, OrderQty, OrderRequest, OrderSide,
    OrderStatus, OrderType, RiskRejectReason, RouteId, StrategyId, TimeInForce, VenueOrderId,
};

/// Default maximum number of actions retained in an [`AlgoDecision`].
pub const DEFAULT_ALGO_DECISION_CAPACITY: usize = 16;
/// Default maximum number of retained violations in an [`AlgoRiskReport`].
pub const DEFAULT_ALGO_RISK_VIOLATION_CAPACITY: usize = 16;
/// Current algorithm checkpoint schema version.
pub const ALGO_CHECKPOINT_SCHEMA_VERSION: u16 = 1;

const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;

/// Algorithm parent-order identifier.
pub type ParentOrderId = FixedAscii<40>;
/// Algorithm child-order identifier.
pub type ChildOrderId = FixedAscii<40>;
/// Strategy intent identifier.
pub type AlgoIntentId = FixedAscii<40>;
/// Running algorithm instance identifier.
pub type AlgoInstanceId = FixedAscii<40>;

/// Execution-algorithm status for a parent order.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ParentOrderStatus {
    /// Parent order has been accepted locally but is not yet active.
    Pending = 1,
    /// Parent order is actively releasing child orders.
    Active = 2,
    /// Parent order is paused by policy, operator, or market condition.
    Paused = 3,
    /// Parent order completed its target quantity.
    Completed = 4,
    /// Parent order was cancelled before completion.
    Cancelled = 5,
    /// Parent order was rejected before activation.
    Rejected = 6,
    /// Parent order expired before completion.
    Expired = 7,
    /// Parent order failed and requires operator or recovery action.
    Failed = 8,
    /// Parent order is being recovered from journal/checkpoint state.
    Recovering = 9,
}

impl ParentOrderStatus {
    /// Returns true when no further child-order release is expected.
    pub const fn is_terminal(self) -> bool {
        matches!(
            self,
            Self::Completed | Self::Cancelled | Self::Rejected | Self::Expired | Self::Failed
        )
    }
}

/// Execution-algorithm status for a child order.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ChildOrderStatus {
    /// Child order is planned but not yet submitted to the OMS.
    Planned = 1,
    /// Child order was submitted to the OMS.
    Submitted = 2,
    /// Child order was accepted by the venue.
    Accepted = 3,
    /// Child order is partially filled.
    PartiallyFilled = 4,
    /// Child order is fully filled.
    Filled = 5,
    /// Child cancel is pending.
    PendingCancel = 6,
    /// Child order was cancelled.
    Cancelled = 7,
    /// Child replace is pending.
    PendingReplace = 8,
    /// Child order was rejected.
    Rejected = 9,
    /// Child order expired.
    Expired = 10,
    /// Child order state is unknown after recovery/reconciliation.
    Unknown = 11,
}

impl ChildOrderStatus {
    /// Maps a canonical OMS order status into a child-order status.
    pub const fn from_order_status(status: OrderStatus) -> Self {
        match status {
            OrderStatus::PendingNew => Self::Submitted,
            OrderStatus::New => Self::Accepted,
            OrderStatus::PartiallyFilled => Self::PartiallyFilled,
            OrderStatus::Filled => Self::Filled,
            OrderStatus::PendingCancel => Self::PendingCancel,
            OrderStatus::Cancelled => Self::Cancelled,
            OrderStatus::PendingReplace | OrderStatus::Replaced => Self::PendingReplace,
            OrderStatus::Rejected => Self::Rejected,
            OrderStatus::Expired => Self::Expired,
            OrderStatus::Suspended | OrderStatus::Unknown => Self::Unknown,
        }
    }

    /// Returns true when no further venue activity is expected.
    pub const fn is_terminal(self) -> bool {
        matches!(
            self,
            Self::Filled | Self::Cancelled | Self::Rejected | Self::Expired
        )
    }
}

/// Execution-algorithm error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AlgoError {
    /// Core execution-domain validation failed.
    Core(ExecutionCoreError),
    /// Parent start time must be strictly before end time.
    InvalidTimeWindow,
    /// Slice interval must be positive.
    InvalidSliceInterval,
    /// Minimum clip must be positive and no larger than maximum clip.
    InvalidClipBounds,
    /// Parent order is terminal and cannot release more child orders.
    ParentTerminal,
    /// Progress quantities are internally inconsistent.
    InvalidProgress,
    /// Algorithm risk limits or context are invalid.
    InvalidRiskParameters,
    /// Algorithm checkpoint or recovery state is invalid.
    InvalidRecoveryState,
    /// Algorithm simulation inputs are invalid.
    InvalidSimulationParameters,
    /// Algorithm metrics or benchmark inputs are invalid.
    InvalidMetricsParameters,
    /// Algorithm configuration is invalid.
    InvalidConfigParameters,
    /// Fixed-capacity decision buffer is full.
    DecisionFull {
        /// Configured decision capacity.
        capacity: usize,
    },
    /// Deterministic replay generated an identifier that exceeded capacity.
    GeneratedIdentifierTooLong,
    /// Participation rate must be positive and no greater than the cap.
    InvalidParticipationRate,
    /// VWAP volume profile is empty, non-monotonic, or has zero total weight.
    InvalidVolumeProfile,
    /// Iceberg display quantity or replenish threshold is invalid.
    InvalidDisplayQuantity,
    /// Passive queue configuration or market context is invalid.
    InvalidPassiveQueueParameters,
    /// Smart-order-router configuration or route candidate is invalid.
    InvalidSorParameters,
    /// Liquidity-seeking configuration or candidate is invalid.
    InvalidLiquiditySeekingParameters,
    /// Sweep/aggressive-take configuration or candidate is invalid.
    InvalidSweepParameters,
    /// Basket or spread leg configuration is invalid.
    InvalidBasketParameters,
    /// Pairs/spread configuration or quote context is invalid.
    InvalidSpreadParameters,
    /// Market-making configuration or quote context is invalid.
    InvalidMarketMakingParameters,
    /// Implementation shortfall configuration or market context is invalid.
    InvalidShortfallParameters,
}

impl fmt::Display for AlgoError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Core(err) => write!(f, "{err}"),
            Self::InvalidTimeWindow => write!(f, "parent start time must be before end time"),
            Self::InvalidSliceInterval => write!(f, "slice interval must be positive"),
            Self::InvalidClipBounds => {
                write!(f, "minimum clip must be positive and <= maximum clip")
            }
            Self::ParentTerminal => write!(f, "terminal parent cannot release child orders"),
            Self::InvalidProgress => write!(f, "algorithm progress is inconsistent"),
            Self::InvalidRiskParameters => write!(f, "invalid algorithm risk parameters"),
            Self::InvalidRecoveryState => write!(f, "invalid algorithm recovery state"),
            Self::InvalidSimulationParameters => {
                write!(f, "invalid algorithm simulation parameters")
            }
            Self::InvalidMetricsParameters => write!(f, "invalid algorithm metrics parameters"),
            Self::InvalidConfigParameters => write!(f, "invalid algorithm config parameters"),
            Self::DecisionFull { capacity } => {
                write!(f, "algorithm decision capacity {capacity} is full")
            }
            Self::GeneratedIdentifierTooLong => write!(f, "generated identifier is too long"),
            Self::InvalidParticipationRate => {
                write!(f, "participation rate must be positive and <= cap")
            }
            Self::InvalidVolumeProfile => write!(f, "invalid VWAP volume profile"),
            Self::InvalidDisplayQuantity => write!(f, "invalid iceberg display quantity"),
            Self::InvalidPassiveQueueParameters => {
                write!(f, "invalid passive queue parameters")
            }
            Self::InvalidSorParameters => write!(f, "invalid SOR parameters"),
            Self::InvalidLiquiditySeekingParameters => {
                write!(f, "invalid liquidity-seeking parameters")
            }
            Self::InvalidSweepParameters => write!(f, "invalid sweep parameters"),
            Self::InvalidBasketParameters => write!(f, "invalid basket parameters"),
            Self::InvalidSpreadParameters => write!(f, "invalid spread parameters"),
            Self::InvalidMarketMakingParameters => {
                write!(f, "invalid market-making parameters")
            }
            Self::InvalidShortfallParameters => {
                write!(f, "invalid implementation shortfall parameters")
            }
        }
    }
}

impl Error for AlgoError {}

impl From<ExecutionCoreError> for AlgoError {
    fn from(value: ExecutionCoreError) -> Self {
        Self::Core(value)
    }
}

/// Parent order controlled by an execution algorithm.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParentOrder {
    id: ParentOrderId,
    account_id: AccountId,
    route_id: RouteId,
    strategy_id: StrategyId,
    symbol: ExecutionSymbol,
    side: OrderSide,
    order_type: OrderType,
    time_in_force: TimeInForce,
    total_qty: OrderQty,
    limit_price: OrderPrice,
    stop_price: OrderPrice,
    start_ns: u64,
    end_ns: u64,
    min_clip: OrderQty,
    max_clip: OrderQty,
    participation_cap_bps: u16,
    status: ParentOrderStatus,
}

impl ParentOrder {
    /// Creates an active parent order.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when order shape, schedule, or clip bounds are
    /// invalid.
    #[allow(
        clippy::too_many_arguments,
        reason = "flat constructor mirrors order ticket fields"
    )]
    pub fn new(
        id: ParentOrderId,
        account_id: AccountId,
        route_id: RouteId,
        strategy_id: StrategyId,
        symbol: ExecutionSymbol,
        side: OrderSide,
        order_type: OrderType,
        time_in_force: TimeInForce,
        total_qty: OrderQty,
        limit_price: OrderPrice,
        stop_price: OrderPrice,
        start_ns: u64,
        end_ns: u64,
        min_clip: OrderQty,
        max_clip: OrderQty,
        participation_cap_bps: u16,
    ) -> Result<Self, AlgoError> {
        let parent = Self {
            id,
            account_id,
            route_id,
            strategy_id,
            symbol,
            side,
            order_type,
            time_in_force,
            total_qty,
            limit_price,
            stop_price,
            start_ns,
            end_ns,
            min_clip,
            max_clip,
            participation_cap_bps,
            status: ParentOrderStatus::Active,
        };
        parent.validate()?;
        Ok(parent)
    }

    /// Validates parent order shape and schedule.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when order shape, schedule, or clip bounds are
    /// invalid.
    pub fn validate(&self) -> Result<(), AlgoError> {
        if self.start_ns >= self.end_ns {
            return Err(AlgoError::InvalidTimeWindow);
        }
        if self.min_clip.0 <= 0 || self.max_clip.0 <= 0 || self.min_clip.0 > self.max_clip.0 {
            return Err(AlgoError::InvalidClipBounds);
        }
        let request = self.build_order_request(ClientOrderId::empty(), self.total_qty, 0);
        request.validate()?;
        Ok(())
    }

    /// Returns the parent identifier.
    pub const fn id(&self) -> ParentOrderId {
        self.id
    }

    /// Returns the account identifier.
    pub const fn account_id(&self) -> AccountId {
        self.account_id
    }

    /// Returns the default route identifier for child orders.
    pub const fn route_id(&self) -> RouteId {
        self.route_id
    }

    /// Returns the strategy attribution identifier.
    pub const fn strategy_id(&self) -> StrategyId {
        self.strategy_id
    }

    /// Returns the execution symbol.
    pub const fn symbol(&self) -> ExecutionSymbol {
        self.symbol
    }

    /// Returns the order side.
    pub const fn side(&self) -> OrderSide {
        self.side
    }

    /// Returns the child order type.
    pub const fn order_type(&self) -> OrderType {
        self.order_type
    }

    /// Returns the child time-in-force.
    pub const fn time_in_force(&self) -> TimeInForce {
        self.time_in_force
    }

    /// Returns the target total quantity.
    pub const fn total_qty(&self) -> OrderQty {
        self.total_qty
    }

    /// Returns the parent limit price.
    pub const fn limit_price(&self) -> OrderPrice {
        self.limit_price
    }

    /// Returns the parent stop price.
    pub const fn stop_price(&self) -> OrderPrice {
        self.stop_price
    }

    /// Returns the algorithm start timestamp.
    pub const fn start_ns(&self) -> u64 {
        self.start_ns
    }

    /// Returns the algorithm end timestamp.
    pub const fn end_ns(&self) -> u64 {
        self.end_ns
    }

    /// Returns the minimum child clip.
    pub const fn min_clip(&self) -> OrderQty {
        self.min_clip
    }

    /// Returns the maximum child clip.
    pub const fn max_clip(&self) -> OrderQty {
        self.max_clip
    }

    /// Returns the optional participation cap in basis points, or zero when
    /// unset.
    pub const fn participation_cap_bps(&self) -> u16 {
        self.participation_cap_bps
    }

    /// Returns the parent lifecycle status.
    pub const fn status(&self) -> ParentOrderStatus {
        self.status
    }

    /// Returns a copy with a different lifecycle status.
    pub const fn with_status(mut self, status: ParentOrderStatus) -> Self {
        self.status = status;
        self
    }

    fn build_order_request(
        &self,
        client_order_id: ClientOrderId,
        quantity: OrderQty,
        ts_recv_ns: u64,
    ) -> OrderRequest {
        self.build_order_request_at_price(client_order_id, quantity, self.limit_price, ts_recv_ns)
    }

    fn build_order_request_at_price(
        &self,
        client_order_id: ClientOrderId,
        quantity: OrderQty,
        limit_price: OrderPrice,
        ts_recv_ns: u64,
    ) -> OrderRequest {
        self.build_order_request_for_route_at_price(
            self.route_id,
            client_order_id,
            quantity,
            limit_price,
            ts_recv_ns,
        )
    }

    fn build_order_request_for_route_at_price(
        &self,
        route_id: RouteId,
        client_order_id: ClientOrderId,
        quantity: OrderQty,
        limit_price: OrderPrice,
        ts_recv_ns: u64,
    ) -> OrderRequest {
        OrderRequest {
            client_order_id,
            account_id: self.account_id,
            route_id,
            strategy_id: self.strategy_id,
            symbol: self.symbol,
            side: self.side,
            order_type: self.order_type,
            time_in_force: self.time_in_force,
            quantity,
            limit_price,
            stop_price: self.stop_price,
            ts_exchange_ns: 0,
            ts_recv_ns,
        }
    }

    fn build_order_request_for_side_at_price(
        &self,
        side: OrderSide,
        client_order_id: ClientOrderId,
        quantity: OrderQty,
        limit_price: OrderPrice,
        ts_recv_ns: u64,
    ) -> OrderRequest {
        OrderRequest {
            client_order_id,
            account_id: self.account_id,
            route_id: self.route_id,
            strategy_id: self.strategy_id,
            symbol: self.symbol,
            side,
            order_type: self.order_type,
            time_in_force: self.time_in_force,
            quantity,
            limit_price,
            stop_price: self.stop_price,
            ts_exchange_ns: 0,
            ts_recv_ns,
        }
    }
}

/// Planned child order generated by an execution algorithm.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChildOrderPlan {
    child_id: ChildOrderId,
    parent_id: ParentOrderId,
    request: OrderRequest,
    due_ns: u64,
    status: ChildOrderStatus,
}

impl ChildOrderPlan {
    /// Creates a planned child order.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when the generated OMS request is invalid.
    pub fn new(
        child_id: ChildOrderId,
        parent_id: ParentOrderId,
        request: OrderRequest,
        due_ns: u64,
    ) -> Result<Self, AlgoError> {
        request.validate()?;
        Ok(Self {
            child_id,
            parent_id,
            request,
            due_ns,
            status: ChildOrderStatus::Planned,
        })
    }

    /// Returns the child identifier.
    pub const fn child_id(&self) -> ChildOrderId {
        self.child_id
    }

    /// Returns the parent identifier.
    pub const fn parent_id(&self) -> ParentOrderId {
        self.parent_id
    }

    /// Returns the canonical OMS order request.
    pub const fn request(&self) -> &OrderRequest {
        &self.request
    }

    /// Returns the planned release timestamp.
    pub const fn due_ns(&self) -> u64 {
        self.due_ns
    }

    /// Returns the child lifecycle status.
    pub const fn status(&self) -> ChildOrderStatus {
        self.status
    }

    /// Returns a copy with a different lifecycle status.
    pub const fn with_status(mut self, status: ChildOrderStatus) -> Self {
        self.status = status;
        self
    }
}

/// Aggregate parent execution progress.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoProgress {
    parent_id: ParentOrderId,
    target_qty: OrderQty,
    released_qty: OrderQty,
    completed_qty: OrderQty,
    open_qty: OrderQty,
    rejected_children: u64,
    terminal_children: u64,
}

impl AlgoProgress {
    /// Creates empty progress for a parent order.
    pub const fn new(parent_id: ParentOrderId, target_qty: OrderQty) -> Self {
        Self {
            parent_id,
            target_qty,
            released_qty: OrderQty(0),
            completed_qty: OrderQty(0),
            open_qty: OrderQty(0),
            rejected_children: 0,
            terminal_children: 0,
        }
    }

    /// Returns the parent identifier.
    pub const fn parent_id(&self) -> ParentOrderId {
        self.parent_id
    }

    /// Returns target parent quantity.
    pub const fn target_qty(&self) -> OrderQty {
        self.target_qty
    }

    /// Returns quantity released as child orders.
    pub const fn released_qty(&self) -> OrderQty {
        self.released_qty
    }

    /// Returns quantity fully executed.
    pub const fn completed_qty(&self) -> OrderQty {
        self.completed_qty
    }

    /// Returns currently open child quantity estimate.
    pub const fn open_qty(&self) -> OrderQty {
        self.open_qty
    }

    /// Returns rejected child count.
    pub const fn rejected_children(&self) -> u64 {
        self.rejected_children
    }

    /// Returns terminal child count.
    pub const fn terminal_children(&self) -> u64 {
        self.terminal_children
    }

    /// Returns unreleased target quantity.
    pub const fn unreleased_qty(&self) -> OrderQty {
        OrderQty(self.target_qty.0.saturating_sub(self.released_qty.0))
    }

    /// Returns true when completed quantity reached target quantity.
    pub const fn is_complete(&self) -> bool {
        self.completed_qty.0 >= self.target_qty.0
    }

    /// Records a planned child release.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidProgress`] when the release would exceed the
    /// parent target quantity.
    pub fn on_child_released(&mut self, plan: &ChildOrderPlan) -> Result<(), AlgoError> {
        if plan.parent_id != self.parent_id {
            return Err(AlgoError::InvalidProgress);
        }
        let qty = plan.request.quantity.0;
        let released = self.released_qty.0.saturating_add(qty);
        if released > self.target_qty.0 {
            return Err(AlgoError::InvalidProgress);
        }
        self.released_qty = OrderQty(released);
        self.open_qty = OrderQty(self.open_qty.0.saturating_add(qty));
        Ok(())
    }

    /// Folds a canonical OMS execution event into parent progress.
    pub fn on_execution_event(&mut self, event: &ExecutionEvent) {
        if event.last_qty.0 > 0 {
            self.completed_qty = OrderQty(
                self.completed_qty
                    .0
                    .saturating_add(event.last_qty.0)
                    .min(self.target_qty.0),
            );
            self.open_qty = OrderQty(self.open_qty.0.saturating_sub(event.last_qty.0));
        }
        if event.order_status.is_terminal() {
            self.terminal_children = self.terminal_children.saturating_add(1);
            if matches!(event.order_status, OrderStatus::Rejected) {
                self.rejected_children = self.rejected_children.saturating_add(1);
            }
            self.open_qty = OrderQty(self.open_qty.0.min(event.leaves_qty.0.max(0)));
        }
    }
}

/// Execution-algorithm action.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
#[allow(
    clippy::large_enum_variant,
    reason = "SubmitChild intentionally keeps the action Copy and allocation-free"
)]
pub enum AlgoAction {
    /// Submit a planned child order through the OMS.
    SubmitChild(ChildOrderPlan),
    /// Pause the parent order.
    PauseParent {
        /// Parent to pause.
        parent_id: ParentOrderId,
    },
    /// Mark the parent order complete.
    CompleteParent {
        /// Parent to complete.
        parent_id: ParentOrderId,
    },
    /// Escalate the parent for risk or operator handling.
    EscalateRisk {
        /// Parent requiring attention.
        parent_id: ParentOrderId,
    },
}

/// Fixed-capacity algorithm decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoDecision<const N: usize = DEFAULT_ALGO_DECISION_CAPACITY> {
    decision_seq: u64,
    actions: [Option<AlgoAction>; N],
    len: usize,
}

impl<const N: usize> AlgoDecision<N> {
    /// Creates an empty decision.
    pub const fn new(decision_seq: u64) -> Self {
        Self {
            decision_seq,
            actions: [None; N],
            len: 0,
        }
    }

    /// Returns the monotonic decision sequence assigned by the caller.
    pub const fn decision_seq(&self) -> u64 {
        self.decision_seq
    }

    /// Returns the number of retained actions.
    pub const fn len(&self) -> usize {
        self.len
    }

    /// Returns true when no actions are present.
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Adds an action to the fixed-capacity decision.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::DecisionFull`] when capacity is exhausted.
    pub fn push(&mut self, action: AlgoAction) -> Result<(), AlgoError> {
        if self.len == N {
            return Err(AlgoError::DecisionFull { capacity: N });
        }
        self.actions[self.len] = Some(action);
        self.len += 1;
        Ok(())
    }

    /// Returns actions in insertion order.
    pub fn actions(&self) -> impl Iterator<Item = &AlgoAction> {
        self.actions[..self.len].iter().filter_map(Option::as_ref)
    }
}

impl<const N: usize> Default for AlgoDecision<N> {
    fn default() -> Self {
        Self::new(0)
    }
}

/// Algorithm risk-policy outcome.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AlgoRiskOutcome {
    /// All configured checks passed.
    Allow = 1,
    /// One or more configured limits blocked submission.
    Block = 2,
    /// Kill switch or operator pause requires immediate halt semantics.
    KillSwitch = 3,
}

/// Algorithm risk violation category.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AlgoRiskViolationKind {
    /// Kill switch is active.
    KillSwitchActive = 1,
    /// Operator pause is active.
    OperatorPaused = 2,
    /// Parent order is terminal.
    ParentTerminal = 3,
    /// Parent/progress/child relationship is inconsistent.
    InvalidProgress = 4,
    /// Market data is stale.
    StaleMarketData = 5,
    /// Route is degraded.
    RouteDegraded = 6,
    /// Persistence/journaling path is degraded.
    PersistenceDegraded = 7,
    /// Parent quantity exceeds configured maximum.
    ParentQuantityExceeded = 8,
    /// Child quantity exceeds configured maximum.
    ChildQuantityExceeded = 9,
    /// Child notional exceeds configured maximum.
    ChildNotionalExceeded = 10,
    /// Child price is outside configured collar.
    PriceCollarExceeded = 11,
    /// Child would exceed configured participation cap.
    ParticipationExceeded = 12,
    /// Open child quantity would exceed configured limit.
    OpenQuantityExceeded = 13,
    /// Decision contains too many child submissions.
    ChildrenPerDecisionExceeded = 14,
    /// Caller-reported child order rate exceeds configured limit.
    ChildOrderRateExceeded = 15,
    /// Generated child request failed canonical OMS validation.
    InvalidChildPlan = 16,
}

/// One algorithm risk violation retained in a report.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoRiskViolation {
    kind: AlgoRiskViolationKind,
    child_id: Option<ChildOrderId>,
    measured: u128,
    limit: u128,
}

impl AlgoRiskViolation {
    /// Creates a violation.
    pub const fn new(
        kind: AlgoRiskViolationKind,
        child_id: Option<ChildOrderId>,
        measured: u128,
        limit: u128,
    ) -> Self {
        Self {
            kind,
            child_id,
            measured,
            limit,
        }
    }

    /// Returns violation category.
    pub const fn kind(&self) -> AlgoRiskViolationKind {
        self.kind
    }

    /// Returns associated child identifier when the violation is child-specific.
    pub const fn child_id(&self) -> Option<ChildOrderId> {
        self.child_id
    }

    /// Returns measured value.
    pub const fn measured(&self) -> u128 {
        self.measured
    }

    /// Returns configured limit.
    pub const fn limit(&self) -> u128 {
        self.limit
    }
}

/// Algorithm risk limits.
///
/// Zero-valued limits are disabled, except basis-point limits where `10_000`
/// means 100 percent. This keeps one struct usable for schedule-driven and
/// latency-sensitive planners without forcing all hosts to configure every
/// possible control.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoRiskLimits {
    max_parent_qty: OrderQty,
    max_child_qty: OrderQty,
    max_child_notional: u128,
    max_participation_bps: u16,
    price_collar_bps: u16,
    max_open_qty: OrderQty,
    max_children_per_decision: u16,
    max_child_orders_in_window: u32,
}

impl AlgoRiskLimits {
    /// Creates algorithm risk limits.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidRiskParameters`] when quantities are
    /// negative or basis-point limits exceed `10_000`.
    #[allow(
        clippy::too_many_arguments,
        reason = "flat risk limit constructor keeps every limit explicit"
    )]
    pub const fn new(
        max_parent_qty: OrderQty,
        max_child_qty: OrderQty,
        max_child_notional: u128,
        max_participation_bps: u16,
        price_collar_bps: u16,
        max_open_qty: OrderQty,
        max_children_per_decision: u16,
        max_child_orders_in_window: u32,
    ) -> Result<Self, AlgoError> {
        if max_parent_qty.0 < 0
            || max_child_qty.0 < 0
            || max_open_qty.0 < 0
            || max_participation_bps > 10_000
            || price_collar_bps > 10_000
        {
            return Err(AlgoError::InvalidRiskParameters);
        }
        Ok(Self {
            max_parent_qty,
            max_child_qty,
            max_child_notional,
            max_participation_bps,
            price_collar_bps,
            max_open_qty,
            max_children_per_decision,
            max_child_orders_in_window,
        })
    }

    /// Returns a policy with all optional limits disabled.
    pub const fn unbounded() -> Self {
        Self {
            max_parent_qty: OrderQty(0),
            max_child_qty: OrderQty(0),
            max_child_notional: 0,
            max_participation_bps: 0,
            price_collar_bps: 0,
            max_open_qty: OrderQty(0),
            max_children_per_decision: 0,
            max_child_orders_in_window: 0,
        }
    }

    /// Returns maximum parent quantity, or zero when disabled.
    pub const fn max_parent_qty(&self) -> OrderQty {
        self.max_parent_qty
    }

    /// Returns maximum child quantity, or zero when disabled.
    pub const fn max_child_qty(&self) -> OrderQty {
        self.max_child_qty
    }

    /// Returns maximum child notional, or zero when disabled.
    pub const fn max_child_notional(&self) -> u128 {
        self.max_child_notional
    }

    /// Returns maximum participation in basis points, or zero when disabled.
    pub const fn max_participation_bps(&self) -> u16 {
        self.max_participation_bps
    }

    /// Returns price collar in basis points, or zero when disabled.
    pub const fn price_collar_bps(&self) -> u16 {
        self.price_collar_bps
    }

    /// Returns maximum open child quantity, or zero when disabled.
    pub const fn max_open_qty(&self) -> OrderQty {
        self.max_open_qty
    }

    /// Returns maximum child submissions per decision, or zero when disabled.
    pub const fn max_children_per_decision(&self) -> u16 {
        self.max_children_per_decision
    }

    /// Returns maximum child submissions in the caller's rate window, or zero
    /// when disabled.
    pub const fn max_child_orders_in_window(&self) -> u32 {
        self.max_child_orders_in_window
    }
}

impl Default for AlgoRiskLimits {
    fn default() -> Self {
        Self::unbounded()
    }
}

/// Host-supplied risk context for one algorithm decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoRiskContext {
    reference_price: OrderPrice,
    observed_market_volume: OrderQty,
    open_child_orders: u32,
    child_orders_in_window: u32,
    stale_market_data: bool,
    route_degraded: bool,
    persistence_degraded: bool,
    kill_switch_active: bool,
    operator_paused: bool,
}

impl AlgoRiskContext {
    /// Creates risk context around a positive reference price.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidRiskParameters`] when the reference price is
    /// not positive.
    pub const fn new(reference_price: OrderPrice) -> Result<Self, AlgoError> {
        if reference_price.0 <= 0 {
            return Err(AlgoError::InvalidRiskParameters);
        }
        Ok(Self {
            reference_price,
            observed_market_volume: OrderQty(0),
            open_child_orders: 0,
            child_orders_in_window: 0,
            stale_market_data: false,
            route_degraded: false,
            persistence_degraded: false,
            kill_switch_active: false,
            operator_paused: false,
        })
    }

    /// Returns the reference price used for collar checks.
    pub const fn reference_price(&self) -> OrderPrice {
        self.reference_price
    }

    /// Returns observed market volume used for participation checks.
    pub const fn observed_market_volume(&self) -> OrderQty {
        self.observed_market_volume
    }

    /// Returns currently open child order count supplied by the host.
    pub const fn open_child_orders(&self) -> u32 {
        self.open_child_orders
    }

    /// Returns child order count in the caller's rate-limit window.
    pub const fn child_orders_in_window(&self) -> u32 {
        self.child_orders_in_window
    }

    /// Returns true when market data should block child release.
    pub const fn stale_market_data(&self) -> bool {
        self.stale_market_data
    }

    /// Returns true when route degradation should block child release.
    pub const fn route_degraded(&self) -> bool {
        self.route_degraded
    }

    /// Returns true when persistence degradation should block child release.
    pub const fn persistence_degraded(&self) -> bool {
        self.persistence_degraded
    }

    /// Returns true when kill switch is active.
    pub const fn kill_switch_active(&self) -> bool {
        self.kill_switch_active
    }

    /// Returns true when operator pause is active.
    pub const fn operator_paused(&self) -> bool {
        self.operator_paused
    }

    /// Returns a copy with observed market volume.
    pub const fn with_observed_market_volume(mut self, volume: OrderQty) -> Self {
        self.observed_market_volume = volume;
        self
    }

    /// Returns a copy with currently open child order count.
    pub const fn with_open_child_orders(mut self, count: u32) -> Self {
        self.open_child_orders = count;
        self
    }

    /// Returns a copy with child order count in the caller's rate window.
    pub const fn with_child_orders_in_window(mut self, count: u32) -> Self {
        self.child_orders_in_window = count;
        self
    }

    /// Returns a copy with stale market-data flag.
    pub const fn with_stale_market_data(mut self, value: bool) -> Self {
        self.stale_market_data = value;
        self
    }

    /// Returns a copy with route-degraded flag.
    pub const fn with_route_degraded(mut self, value: bool) -> Self {
        self.route_degraded = value;
        self
    }

    /// Returns a copy with persistence-degraded flag.
    pub const fn with_persistence_degraded(mut self, value: bool) -> Self {
        self.persistence_degraded = value;
        self
    }

    /// Returns a copy with kill-switch flag.
    pub const fn with_kill_switch_active(mut self, value: bool) -> Self {
        self.kill_switch_active = value;
        self
    }

    /// Returns a copy with operator-pause flag.
    pub const fn with_operator_paused(mut self, value: bool) -> Self {
        self.operator_paused = value;
        self
    }
}

/// Fixed-capacity risk report.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoRiskReport<const N: usize = DEFAULT_ALGO_RISK_VIOLATION_CAPACITY> {
    outcome: AlgoRiskOutcome,
    violations: [Option<AlgoRiskViolation>; N],
    len: usize,
    truncated: bool,
}

impl<const N: usize> AlgoRiskReport<N> {
    /// Creates an empty allow report.
    pub const fn new() -> Self {
        Self {
            outcome: AlgoRiskOutcome::Allow,
            violations: [None; N],
            len: 0,
            truncated: false,
        }
    }

    /// Returns risk outcome.
    pub const fn outcome(&self) -> AlgoRiskOutcome {
        self.outcome
    }

    /// Returns true when submission is allowed.
    pub const fn is_allowed(&self) -> bool {
        matches!(self.outcome, AlgoRiskOutcome::Allow)
    }

    /// Returns retained violation count.
    pub const fn len(&self) -> usize {
        self.len
    }

    /// Returns true when no retained violations are present.
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns true when more violations occurred than the report retained.
    pub const fn truncated(&self) -> bool {
        self.truncated
    }

    /// Returns retained violations in insertion order.
    pub fn violations(&self) -> impl Iterator<Item = &AlgoRiskViolation> {
        self.violations[..self.len]
            .iter()
            .filter_map(Option::as_ref)
    }

    /// Returns first retained violation.
    pub fn first_violation(&self) -> Option<&AlgoRiskViolation> {
        self.violations().next()
    }

    fn push(&mut self, violation: AlgoRiskViolation) {
        if self.len == N {
            self.truncated = true;
            self.outcome = stronger_risk_outcome(self.outcome, violation.kind());
            return;
        }
        self.outcome = stronger_risk_outcome(self.outcome, violation.kind());
        self.violations[self.len] = Some(violation);
        self.len += 1;
    }
}

impl<const N: usize> Default for AlgoRiskReport<N> {
    fn default() -> Self {
        Self::new()
    }
}

/// Additive algorithm risk policy for validating child plans before OMS submit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoRiskPolicy {
    limits: AlgoRiskLimits,
}

impl AlgoRiskPolicy {
    /// Creates a policy from limits.
    pub const fn new(limits: AlgoRiskLimits) -> Self {
        Self { limits }
    }

    /// Returns configured limits.
    pub const fn limits(&self) -> AlgoRiskLimits {
        self.limits
    }

    /// Evaluates one planned child order.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when parent, progress, or child state is invalid.
    pub fn evaluate_child<const N: usize>(
        &self,
        parent: &ParentOrder,
        progress: AlgoProgress,
        child: &ChildOrderPlan,
        context: AlgoRiskContext,
    ) -> Result<AlgoRiskReport<N>, AlgoError> {
        parent.validate()?;
        let mut report = AlgoRiskReport::new();
        self.check_static_context(&mut report, parent, progress)?;
        self.check_dynamic_context(&mut report, context);
        self.check_child(&mut report, parent, progress, child, context, 1)?;
        Ok(report)
    }

    /// Evaluates all child submissions inside one [`AlgoDecision`].
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when parent, progress, or child state is invalid.
    pub fn evaluate_decision<const REPORT_N: usize, const DECISION_N: usize>(
        &self,
        parent: &ParentOrder,
        progress: AlgoProgress,
        decision: &AlgoDecision<DECISION_N>,
        context: AlgoRiskContext,
    ) -> Result<AlgoRiskReport<REPORT_N>, AlgoError> {
        parent.validate()?;
        let mut report = AlgoRiskReport::new();
        self.check_static_context(&mut report, parent, progress)?;
        self.check_dynamic_context(&mut report, context);

        let mut child_count = 0_u16;
        let mut planned_open_qty = progress.open_qty().0;
        for action in decision.actions() {
            if let AlgoAction::SubmitChild(child) = action {
                child_count = child_count.saturating_add(1);
                self.check_child(&mut report, parent, progress, child, context, child_count)?;
                planned_open_qty = planned_open_qty.saturating_add(child.request().quantity.0);
            }
        }

        self.check_open_qty(&mut report, planned_open_qty, None);
        Ok(report)
    }

    fn check_static_context<const N: usize>(
        &self,
        report: &mut AlgoRiskReport<N>,
        parent: &ParentOrder,
        progress: AlgoProgress,
    ) -> Result<(), AlgoError> {
        if progress.parent_id() != parent.id() || progress.target_qty() != parent.total_qty() {
            report.push(AlgoRiskViolation::new(
                AlgoRiskViolationKind::InvalidProgress,
                None,
                1,
                0,
            ));
            return Err(AlgoError::InvalidProgress);
        }
        if parent.status().is_terminal() {
            report.push(AlgoRiskViolation::new(
                AlgoRiskViolationKind::ParentTerminal,
                None,
                u128::from(parent.status() as u8),
                0,
            ));
        }
        if self.limits.max_parent_qty().0 > 0
            && parent.total_qty().0 > self.limits.max_parent_qty().0
        {
            report.push(AlgoRiskViolation::new(
                AlgoRiskViolationKind::ParentQuantityExceeded,
                None,
                i64_to_u128(parent.total_qty().0),
                i64_to_u128(self.limits.max_parent_qty().0),
            ));
        }
        Ok(())
    }

    fn check_dynamic_context<const N: usize>(
        &self,
        report: &mut AlgoRiskReport<N>,
        context: AlgoRiskContext,
    ) {
        if context.kill_switch_active() {
            report.push(AlgoRiskViolation::new(
                AlgoRiskViolationKind::KillSwitchActive,
                None,
                1,
                0,
            ));
        }
        if context.operator_paused() {
            report.push(AlgoRiskViolation::new(
                AlgoRiskViolationKind::OperatorPaused,
                None,
                1,
                0,
            ));
        }
        if context.stale_market_data() {
            report.push(AlgoRiskViolation::new(
                AlgoRiskViolationKind::StaleMarketData,
                None,
                1,
                0,
            ));
        }
        if context.route_degraded() {
            report.push(AlgoRiskViolation::new(
                AlgoRiskViolationKind::RouteDegraded,
                None,
                1,
                0,
            ));
        }
        if context.persistence_degraded() {
            report.push(AlgoRiskViolation::new(
                AlgoRiskViolationKind::PersistenceDegraded,
                None,
                1,
                0,
            ));
        }
    }

    fn check_child<const N: usize>(
        &self,
        report: &mut AlgoRiskReport<N>,
        parent: &ParentOrder,
        progress: AlgoProgress,
        child: &ChildOrderPlan,
        context: AlgoRiskContext,
        child_count: u16,
    ) -> Result<(), AlgoError> {
        if child.parent_id() != parent.id() {
            report.push(AlgoRiskViolation::new(
                AlgoRiskViolationKind::InvalidProgress,
                Some(child.child_id()),
                1,
                0,
            ));
            return Err(AlgoError::InvalidProgress);
        }
        if let Err(err) = child.request().validate() {
            report.push(AlgoRiskViolation::new(
                AlgoRiskViolationKind::InvalidChildPlan,
                Some(child.child_id()),
                1,
                0,
            ));
            return Err(AlgoError::Core(err));
        }

        let quantity = child.request().quantity.0;
        if self.limits.max_child_qty().0 > 0 && quantity > self.limits.max_child_qty().0 {
            report.push(AlgoRiskViolation::new(
                AlgoRiskViolationKind::ChildQuantityExceeded,
                Some(child.child_id()),
                i64_to_u128(quantity),
                i64_to_u128(self.limits.max_child_qty().0),
            ));
        }

        let notional = child_notional(child);
        if self.limits.max_child_notional() > 0 && notional > self.limits.max_child_notional() {
            report.push(AlgoRiskViolation::new(
                AlgoRiskViolationKind::ChildNotionalExceeded,
                Some(child.child_id()),
                notional,
                self.limits.max_child_notional(),
            ));
        }

        let price_distance =
            price_distance_bps(child.request().limit_price, context.reference_price());
        if self.limits.price_collar_bps() > 0
            && price_distance > u32::from(self.limits.price_collar_bps())
        {
            report.push(AlgoRiskViolation::new(
                AlgoRiskViolationKind::PriceCollarExceeded,
                Some(child.child_id()),
                u128::from(price_distance),
                u128::from(self.limits.price_collar_bps()),
            ));
        }

        if self.limits.max_participation_bps() > 0 && context.observed_market_volume().0 > 0 {
            let participation = participation_bps(quantity, context.observed_market_volume().0);
            if participation > u32::from(self.limits.max_participation_bps()) {
                report.push(AlgoRiskViolation::new(
                    AlgoRiskViolationKind::ParticipationExceeded,
                    Some(child.child_id()),
                    u128::from(participation),
                    u128::from(self.limits.max_participation_bps()),
                ));
            }
        }

        self.check_child_count(report, child_count, context);
        self.check_open_qty(
            report,
            progress.open_qty().0.saturating_add(quantity),
            Some(child.child_id()),
        );
        Ok(())
    }

    fn check_child_count<const N: usize>(
        &self,
        report: &mut AlgoRiskReport<N>,
        child_count: u16,
        context: AlgoRiskContext,
    ) {
        if self.limits.max_children_per_decision() > 0
            && child_count > self.limits.max_children_per_decision()
        {
            report.push(AlgoRiskViolation::new(
                AlgoRiskViolationKind::ChildrenPerDecisionExceeded,
                None,
                u128::from(child_count),
                u128::from(self.limits.max_children_per_decision()),
            ));
        }
        if self.limits.max_child_orders_in_window() > 0 {
            let projected = context
                .child_orders_in_window()
                .saturating_add(u32::from(child_count));
            if projected > self.limits.max_child_orders_in_window() {
                report.push(AlgoRiskViolation::new(
                    AlgoRiskViolationKind::ChildOrderRateExceeded,
                    None,
                    u128::from(projected),
                    u128::from(self.limits.max_child_orders_in_window()),
                ));
            }
        }
    }

    fn check_open_qty<const N: usize>(
        &self,
        report: &mut AlgoRiskReport<N>,
        open_qty: i64,
        child_id: Option<ChildOrderId>,
    ) {
        if self.limits.max_open_qty().0 > 0 && open_qty > self.limits.max_open_qty().0 {
            report.push(AlgoRiskViolation::new(
                AlgoRiskViolationKind::OpenQuantityExceeded,
                child_id,
                i64_to_u128(open_qty),
                i64_to_u128(self.limits.max_open_qty().0),
            ));
        }
    }
}

impl Default for AlgoRiskPolicy {
    fn default() -> Self {
        Self::new(AlgoRiskLimits::default())
    }
}

/// Recovery action recommended for an algorithm instance.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AlgoRecoveryAction {
    /// Resume planning after host reconciliation.
    Resume = 1,
    /// Keep the parent paused until an operator or host policy resumes it.
    Pause = 2,
    /// Mark parent complete because recovered progress reached target.
    CompleteParent = 3,
    /// Escalate for risk/operator handling.
    EscalateRisk = 4,
}

/// Deterministic checkpoint for one algorithm parent instance.
///
/// This type intentionally stores only algorithm-owned state. OMS order
/// journals, adapter sequence state, venue order ids, and fill reconciliation
/// remain owned by `of_execution` and adapter-specific recovery flows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoCheckpoint {
    schema_version: u16,
    parent: ParentOrder,
    progress: AlgoProgress,
    next_decision_seq: u64,
    last_input_sequence: u64,
}

impl AlgoCheckpoint {
    /// Creates an algorithm checkpoint.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidRecoveryState`] when parent/progress state
    /// is inconsistent or sequence counters are invalid.
    pub fn new(
        parent: ParentOrder,
        progress: AlgoProgress,
        next_decision_seq: u64,
        last_input_sequence: u64,
    ) -> Result<Self, AlgoError> {
        parent.validate()?;
        if progress.parent_id() != parent.id()
            || progress.target_qty() != parent.total_qty()
            || progress.released_qty().0 > parent.total_qty().0
            || progress.completed_qty().0 > parent.total_qty().0
            || progress.open_qty().0 > progress.released_qty().0
            || next_decision_seq == 0
        {
            return Err(AlgoError::InvalidRecoveryState);
        }
        Ok(Self {
            schema_version: ALGO_CHECKPOINT_SCHEMA_VERSION,
            parent,
            progress,
            next_decision_seq,
            last_input_sequence,
        })
    }

    /// Returns checkpoint schema version.
    pub const fn schema_version(&self) -> u16 {
        self.schema_version
    }

    /// Returns checkpointed parent order.
    pub const fn parent(&self) -> ParentOrder {
        self.parent
    }

    /// Returns checkpointed progress.
    pub const fn progress(&self) -> AlgoProgress {
        self.progress
    }

    /// Returns next decision sequence to assign after recovery.
    pub const fn next_decision_seq(&self) -> u64 {
        self.next_decision_seq
    }

    /// Returns last consumed input sequence.
    pub const fn last_input_sequence(&self) -> u64 {
        self.last_input_sequence
    }
}

/// Algorithm recovery policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoRecoveryPolicy {
    pause_on_recovery: bool,
    require_reconciliation: bool,
    complete_when_progress_complete: bool,
}

impl AlgoRecoveryPolicy {
    /// Creates recovery policy.
    pub const fn new(
        pause_on_recovery: bool,
        require_reconciliation: bool,
        complete_when_progress_complete: bool,
    ) -> Self {
        Self {
            pause_on_recovery,
            require_reconciliation,
            complete_when_progress_complete,
        }
    }

    /// Returns true when recovered parents should pause by default.
    pub const fn pause_on_recovery(&self) -> bool {
        self.pause_on_recovery
    }

    /// Returns true when OMS/venue reconciliation is required before resume.
    pub const fn require_reconciliation(&self) -> bool {
        self.require_reconciliation
    }

    /// Returns true when complete recovered progress should complete parent.
    pub const fn complete_when_progress_complete(&self) -> bool {
        self.complete_when_progress_complete
    }

    /// Returns a copy with pause-on-recovery behavior changed.
    pub const fn with_pause_on_recovery(mut self, value: bool) -> Self {
        self.pause_on_recovery = value;
        self
    }

    /// Returns a copy with reconciliation requirement changed.
    pub const fn with_require_reconciliation(mut self, value: bool) -> Self {
        self.require_reconciliation = value;
        self
    }

    /// Returns a copy with complete-on-recovered-progress behavior changed.
    pub const fn with_complete_when_progress_complete(mut self, value: bool) -> Self {
        self.complete_when_progress_complete = value;
        self
    }
}

impl Default for AlgoRecoveryPolicy {
    fn default() -> Self {
        Self::new(true, true, true)
    }
}

/// Deterministic recovery plan derived from a checkpoint and policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoRecoveryPlan {
    checkpoint: AlgoCheckpoint,
    action: AlgoRecoveryAction,
    replay_from_sequence: u64,
    next_decision_seq: u64,
    reconciliation_required: bool,
}

impl AlgoRecoveryPlan {
    /// Builds a recovery plan.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidRecoveryState`] when checkpoint state is not
    /// usable for deterministic recovery.
    pub fn new(checkpoint: AlgoCheckpoint, policy: AlgoRecoveryPolicy) -> Result<Self, AlgoError> {
        if checkpoint.schema_version() != ALGO_CHECKPOINT_SCHEMA_VERSION
            || checkpoint.next_decision_seq() == 0
        {
            return Err(AlgoError::InvalidRecoveryState);
        }
        let parent = checkpoint.parent();
        let progress = checkpoint.progress();
        let reconciliation_required = policy.require_reconciliation();
        let action = if policy.complete_when_progress_complete() && progress.is_complete() {
            AlgoRecoveryAction::CompleteParent
        } else if parent.status().is_terminal() {
            AlgoRecoveryAction::EscalateRisk
        } else if policy.pause_on_recovery() || reconciliation_required {
            AlgoRecoveryAction::Pause
        } else {
            AlgoRecoveryAction::Resume
        };
        Ok(Self {
            checkpoint,
            action,
            replay_from_sequence: checkpoint.last_input_sequence().saturating_add(1),
            next_decision_seq: checkpoint.next_decision_seq(),
            reconciliation_required,
        })
    }

    /// Returns the source checkpoint.
    pub const fn checkpoint(&self) -> AlgoCheckpoint {
        self.checkpoint
    }

    /// Returns recommended recovery action.
    pub const fn action(&self) -> AlgoRecoveryAction {
        self.action
    }

    /// Returns first input sequence to replay after the checkpoint.
    pub const fn replay_from_sequence(&self) -> u64 {
        self.replay_from_sequence
    }

    /// Returns next decision sequence to assign.
    pub const fn next_decision_seq(&self) -> u64 {
        self.next_decision_seq
    }

    /// Returns true when OMS/venue reconciliation should gate resume.
    pub const fn reconciliation_required(&self) -> bool {
        self.reconciliation_required
    }
}

/// Deterministic child-order simulation outcome.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AlgoSimOutcome {
    /// Child was fully filled.
    Filled = 1,
    /// Child was partially filled and remaining quantity stays open.
    PartiallyFilled = 2,
    /// Child was rejected.
    Rejected = 3,
    /// Child was partially filled and remaining quantity was cancelled.
    CancelledRemainder = 4,
    /// Child did not fill and remains resting.
    Resting = 5,
}

/// Deterministic market/fill model for one simulation pass.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoSimMarket {
    available_qty: OrderQty,
    fill_price: OrderPrice,
    reject: bool,
    cancel_unfilled: bool,
    latency_ns: u64,
}

impl AlgoSimMarket {
    /// Creates a simulation market model.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidSimulationParameters`] when quantities are
    /// negative or a non-rejecting model has a non-positive fill price.
    pub const fn new(
        available_qty: OrderQty,
        fill_price: OrderPrice,
        reject: bool,
        cancel_unfilled: bool,
        latency_ns: u64,
    ) -> Result<Self, AlgoError> {
        if available_qty.0 < 0 || (!reject && fill_price.0 <= 0) {
            return Err(AlgoError::InvalidSimulationParameters);
        }
        Ok(Self {
            available_qty,
            fill_price,
            reject,
            cancel_unfilled,
            latency_ns,
        })
    }

    /// Returns simulated available quantity.
    pub const fn available_qty(&self) -> OrderQty {
        self.available_qty
    }

    /// Returns simulated fill price.
    pub const fn fill_price(&self) -> OrderPrice {
        self.fill_price
    }

    /// Returns true when children should be rejected.
    pub const fn reject(&self) -> bool {
        self.reject
    }

    /// Returns true when unfilled leaves should be cancelled.
    pub const fn cancel_unfilled(&self) -> bool {
        self.cancel_unfilled
    }

    /// Returns simulated exchange-to-receive latency in nanoseconds.
    pub const fn latency_ns(&self) -> u64 {
        self.latency_ns
    }
}

/// One simulated child-order result.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoSimStep {
    sequence: u64,
    child_id: ChildOrderId,
    outcome: AlgoSimOutcome,
    filled_qty: OrderQty,
    leaves_qty: OrderQty,
    fill_price: OrderPrice,
    event: ExecutionEvent,
}

impl AlgoSimStep {
    /// Returns simulation sequence.
    pub const fn sequence(&self) -> u64 {
        self.sequence
    }

    /// Returns simulated child identifier.
    pub const fn child_id(&self) -> ChildOrderId {
        self.child_id
    }

    /// Returns simulation outcome.
    pub const fn outcome(&self) -> AlgoSimOutcome {
        self.outcome
    }

    /// Returns simulated filled quantity.
    pub const fn filled_qty(&self) -> OrderQty {
        self.filled_qty
    }

    /// Returns simulated leaves quantity.
    pub const fn leaves_qty(&self) -> OrderQty {
        self.leaves_qty
    }

    /// Returns simulated fill price.
    pub const fn fill_price(&self) -> OrderPrice {
        self.fill_price
    }

    /// Returns canonical simulated execution event.
    pub const fn event(&self) -> ExecutionEvent {
        self.event
    }
}

/// Fixed-capacity algorithm simulation report.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoSimReport<const N: usize = DEFAULT_ALGO_DECISION_CAPACITY> {
    steps: [Option<AlgoSimStep>; N],
    len: usize,
    truncated: bool,
    total_filled_qty: OrderQty,
    rejected_children: u64,
    cancelled_children: u64,
}

impl<const N: usize> AlgoSimReport<N> {
    /// Creates an empty report.
    pub const fn new() -> Self {
        Self {
            steps: [None; N],
            len: 0,
            truncated: false,
            total_filled_qty: OrderQty(0),
            rejected_children: 0,
            cancelled_children: 0,
        }
    }

    /// Returns retained simulation step count.
    pub const fn len(&self) -> usize {
        self.len
    }

    /// Returns true when no steps are retained.
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns true when more child submissions existed than report capacity.
    pub const fn truncated(&self) -> bool {
        self.truncated
    }

    /// Returns total simulated filled quantity.
    pub const fn total_filled_qty(&self) -> OrderQty {
        self.total_filled_qty
    }

    /// Returns rejected child count.
    pub const fn rejected_children(&self) -> u64 {
        self.rejected_children
    }

    /// Returns cancelled child count.
    pub const fn cancelled_children(&self) -> u64 {
        self.cancelled_children
    }

    /// Returns simulation steps in insertion order.
    pub fn steps(&self) -> impl Iterator<Item = &AlgoSimStep> {
        self.steps[..self.len].iter().filter_map(Option::as_ref)
    }

    fn push(&mut self, step: AlgoSimStep) {
        self.total_filled_qty =
            OrderQty(self.total_filled_qty.0.saturating_add(step.filled_qty().0));
        if matches!(step.outcome(), AlgoSimOutcome::Rejected) {
            self.rejected_children = self.rejected_children.saturating_add(1);
        }
        if matches!(step.outcome(), AlgoSimOutcome::CancelledRemainder) {
            self.cancelled_children = self.cancelled_children.saturating_add(1);
        }
        if self.len == N {
            self.truncated = true;
            return;
        }
        self.steps[self.len] = Some(step);
        self.len += 1;
    }
}

impl<const N: usize> Default for AlgoSimReport<N> {
    fn default() -> Self {
        Self::new()
    }
}

/// Deterministic simulator for generated child plans.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoSimulator {
    market: AlgoSimMarket,
}

impl AlgoSimulator {
    /// Creates a simulator.
    pub const fn new(market: AlgoSimMarket) -> Self {
        Self { market }
    }

    /// Returns the market model.
    pub const fn market(&self) -> AlgoSimMarket {
        self.market
    }

    /// Simulates one child plan.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when deterministic simulator identifiers exceed
    /// fixed identifier capacity.
    pub fn simulate_child(
        &self,
        child: &ChildOrderPlan,
        sequence: u64,
    ) -> Result<AlgoSimStep, AlgoError> {
        let request = child.request();
        let venue_order_id: VenueOrderId = fixed_id_with_index("sim-venue", sequence)?;
        let execution_id: ExecutionId = fixed_id_with_index("sim-exec", sequence)?;
        if self.market.reject() {
            let event = ExecutionEvent {
                exec_type: ExecutionType::Reject,
                order_status: OrderStatus::Rejected,
                client_order_id: request.client_order_id,
                orig_client_order_id: ClientOrderId::empty(),
                venue_order_id,
                execution_id,
                account_id: request.account_id,
                route_id: request.route_id,
                symbol: request.symbol,
                last_qty: OrderQty(0),
                last_price: OrderPrice(0),
                cumulative_qty: OrderQty(0),
                leaves_qty: request.quantity,
                average_price: OrderPrice(0),
                ts_exchange_ns: request.ts_recv_ns,
                ts_recv_ns: request.ts_recv_ns.saturating_add(self.market.latency_ns()),
                reason: RiskRejectReason::PriceBand,
                text: ExecutionText::empty(),
            };
            return Ok(AlgoSimStep {
                sequence,
                child_id: child.child_id(),
                outcome: AlgoSimOutcome::Rejected,
                filled_qty: OrderQty(0),
                leaves_qty: request.quantity,
                fill_price: OrderPrice(0),
                event,
            });
        }

        let filled_qty = request.quantity.0.min(self.market.available_qty().0).max(0);
        let leaves_qty = request.quantity.0.saturating_sub(filled_qty);
        let (outcome, status, exec_type) =
            match (filled_qty, leaves_qty, self.market.cancel_unfilled()) {
                (0, _, false) => (
                    AlgoSimOutcome::Resting,
                    OrderStatus::New,
                    ExecutionType::Ack,
                ),
                (0, _, true) => (
                    AlgoSimOutcome::CancelledRemainder,
                    OrderStatus::Cancelled,
                    ExecutionType::CancelAck,
                ),
                (_, 0, _) => (
                    AlgoSimOutcome::Filled,
                    OrderStatus::Filled,
                    ExecutionType::Trade,
                ),
                (_, _, true) => (
                    AlgoSimOutcome::CancelledRemainder,
                    OrderStatus::Cancelled,
                    ExecutionType::Trade,
                ),
                _ => (
                    AlgoSimOutcome::PartiallyFilled,
                    OrderStatus::PartiallyFilled,
                    ExecutionType::Trade,
                ),
            };
        let fill_price = if filled_qty > 0 {
            self.market.fill_price()
        } else {
            OrderPrice(0)
        };
        let event = ExecutionEvent {
            exec_type,
            order_status: status,
            client_order_id: request.client_order_id,
            orig_client_order_id: ClientOrderId::empty(),
            venue_order_id,
            execution_id,
            account_id: request.account_id,
            route_id: request.route_id,
            symbol: request.symbol,
            last_qty: OrderQty(filled_qty),
            last_price: fill_price,
            cumulative_qty: OrderQty(filled_qty),
            leaves_qty: OrderQty(leaves_qty),
            average_price: fill_price,
            ts_exchange_ns: request.ts_recv_ns,
            ts_recv_ns: request.ts_recv_ns.saturating_add(self.market.latency_ns()),
            reason: RiskRejectReason::None,
            text: ExecutionText::empty(),
        };
        Ok(AlgoSimStep {
            sequence,
            child_id: child.child_id(),
            outcome,
            filled_qty: OrderQty(filled_qty),
            leaves_qty: OrderQty(leaves_qty),
            fill_price,
            event,
        })
    }

    /// Simulates every child submission in an algorithm decision.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when deterministic simulator identifiers exceed
    /// fixed identifier capacity.
    pub fn simulate_decision<const REPORT_N: usize, const DECISION_N: usize>(
        &self,
        decision: &AlgoDecision<DECISION_N>,
        first_sequence: u64,
    ) -> Result<AlgoSimReport<REPORT_N>, AlgoError> {
        let mut report = AlgoSimReport::new();
        let mut sequence = first_sequence;
        for action in decision.actions() {
            if let AlgoAction::SubmitChild(child) = action {
                let step = self.simulate_child(child, sequence)?;
                report.push(step);
                sequence = sequence.saturating_add(1);
            }
        }
        Ok(report)
    }
}

/// Optional TCA benchmark prices for an algorithm parent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoTcaBenchmark {
    arrival_price: OrderPrice,
    vwap_price: OrderPrice,
    twap_price: OrderPrice,
}

impl AlgoTcaBenchmark {
    /// Creates benchmark prices.
    ///
    /// `vwap_price` and `twap_price` may be zero when unavailable.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidMetricsParameters`] when arrival price is
    /// not positive or optional benchmark prices are negative.
    pub const fn new(
        arrival_price: OrderPrice,
        vwap_price: OrderPrice,
        twap_price: OrderPrice,
    ) -> Result<Self, AlgoError> {
        if arrival_price.0 <= 0 || vwap_price.0 < 0 || twap_price.0 < 0 {
            return Err(AlgoError::InvalidMetricsParameters);
        }
        Ok(Self {
            arrival_price,
            vwap_price,
            twap_price,
        })
    }

    /// Returns arrival/decision price.
    pub const fn arrival_price(&self) -> OrderPrice {
        self.arrival_price
    }

    /// Returns VWAP benchmark price, or zero when unavailable.
    pub const fn vwap_price(&self) -> OrderPrice {
        self.vwap_price
    }

    /// Returns TWAP benchmark price, or zero when unavailable.
    pub const fn twap_price(&self) -> OrderPrice {
        self.twap_price
    }
}

/// Snapshot of algorithm execution metrics and TCA fields.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoMetricsSnapshot {
    parent_id: ParentOrderId,
    target_qty: OrderQty,
    submitted_children: u64,
    filled_children: u64,
    rejected_children: u64,
    cancelled_children: u64,
    completed_qty: OrderQty,
    completion_bps: u16,
    average_price: OrderPrice,
    arrival_slippage_bps: i32,
    vwap_slippage_bps: i32,
    twap_slippage_bps: i32,
    first_submit_ns: u64,
    last_event_ns: u64,
    average_latency_ns: u64,
}

impl AlgoMetricsSnapshot {
    /// Returns parent identifier.
    pub const fn parent_id(&self) -> ParentOrderId {
        self.parent_id
    }

    /// Returns target parent quantity.
    pub const fn target_qty(&self) -> OrderQty {
        self.target_qty
    }

    /// Returns submitted child count.
    pub const fn submitted_children(&self) -> u64 {
        self.submitted_children
    }

    /// Returns child count with at least one fill.
    pub const fn filled_children(&self) -> u64 {
        self.filled_children
    }

    /// Returns rejected child count.
    pub const fn rejected_children(&self) -> u64 {
        self.rejected_children
    }

    /// Returns cancelled child count.
    pub const fn cancelled_children(&self) -> u64 {
        self.cancelled_children
    }

    /// Returns completed quantity.
    pub const fn completed_qty(&self) -> OrderQty {
        self.completed_qty
    }

    /// Returns completion in basis points of target quantity.
    pub const fn completion_bps(&self) -> u16 {
        self.completion_bps
    }

    /// Returns average execution price, or zero when no fills exist.
    pub const fn average_price(&self) -> OrderPrice {
        self.average_price
    }

    /// Returns side-aware arrival slippage in basis points.
    pub const fn arrival_slippage_bps(&self) -> i32 {
        self.arrival_slippage_bps
    }

    /// Returns side-aware VWAP benchmark slippage in basis points, or zero when
    /// no VWAP benchmark is configured.
    pub const fn vwap_slippage_bps(&self) -> i32 {
        self.vwap_slippage_bps
    }

    /// Returns side-aware TWAP benchmark slippage in basis points, or zero when
    /// no TWAP benchmark is configured.
    pub const fn twap_slippage_bps(&self) -> i32 {
        self.twap_slippage_bps
    }

    /// Returns first child submit timestamp.
    pub const fn first_submit_ns(&self) -> u64 {
        self.first_submit_ns
    }

    /// Returns last execution-event receive timestamp.
    pub const fn last_event_ns(&self) -> u64 {
        self.last_event_ns
    }

    /// Returns average event latency in nanoseconds.
    pub const fn average_latency_ns(&self) -> u64 {
        self.average_latency_ns
    }
}

/// Allocation-free accumulator for algo execution metrics and TCA.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoMetricsAccumulator {
    parent_id: ParentOrderId,
    side: OrderSide,
    target_qty: OrderQty,
    benchmarks: AlgoTcaBenchmark,
    submitted_children: u64,
    filled_children: u64,
    rejected_children: u64,
    cancelled_children: u64,
    completed_qty: OrderQty,
    cumulative_notional: u128,
    first_submit_ns: u64,
    last_event_ns: u64,
    total_latency_ns: u128,
    latency_samples: u64,
}

impl AlgoMetricsAccumulator {
    /// Creates a metrics accumulator for a parent order.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when parent or benchmark inputs are invalid.
    pub fn new(parent: &ParentOrder, benchmarks: AlgoTcaBenchmark) -> Result<Self, AlgoError> {
        parent.validate()?;
        Ok(Self {
            parent_id: parent.id(),
            side: parent.side(),
            target_qty: parent.total_qty(),
            benchmarks,
            submitted_children: 0,
            filled_children: 0,
            rejected_children: 0,
            cancelled_children: 0,
            completed_qty: OrderQty(0),
            cumulative_notional: 0,
            first_submit_ns: 0,
            last_event_ns: 0,
            total_latency_ns: 0,
            latency_samples: 0,
        })
    }

    /// Records one child submission.
    pub fn on_child_submitted(&mut self, child: &ChildOrderPlan) {
        self.submitted_children = self.submitted_children.saturating_add(1);
        let ts = child.request().ts_recv_ns;
        if self.first_submit_ns == 0 || ts < self.first_submit_ns {
            self.first_submit_ns = ts;
        }
    }

    /// Folds one canonical execution event into metrics.
    pub fn on_execution_event(&mut self, event: &ExecutionEvent) {
        self.last_event_ns = self.last_event_ns.max(event.ts_recv_ns);
        if event.ts_recv_ns >= event.ts_exchange_ns {
            self.total_latency_ns = self
                .total_latency_ns
                .saturating_add(u128::from(event.ts_recv_ns - event.ts_exchange_ns));
            self.latency_samples = self.latency_samples.saturating_add(1);
        }
        match event.order_status {
            OrderStatus::Rejected => {
                self.rejected_children = self.rejected_children.saturating_add(1);
            }
            OrderStatus::Cancelled | OrderStatus::Expired => {
                self.cancelled_children = self.cancelled_children.saturating_add(1);
            }
            _ => {}
        }
        if event.last_qty.0 > 0 {
            self.filled_children = self.filled_children.saturating_add(1);
            self.completed_qty = OrderQty(
                self.completed_qty
                    .0
                    .saturating_add(event.last_qty.0)
                    .min(self.target_qty.0),
            );
            self.cumulative_notional = self.cumulative_notional.saturating_add(
                i64_to_u128(event.last_qty.0).saturating_mul(i64_to_u128(event.last_price.0)),
            );
        }
    }

    /// Returns current metrics snapshot.
    pub fn snapshot(&self) -> AlgoMetricsSnapshot {
        let average_price =
            average_price_from_notional(self.cumulative_notional, self.completed_qty);
        AlgoMetricsSnapshot {
            parent_id: self.parent_id,
            target_qty: self.target_qty,
            submitted_children: self.submitted_children,
            filled_children: self.filled_children,
            rejected_children: self.rejected_children,
            cancelled_children: self.cancelled_children,
            completed_qty: self.completed_qty,
            completion_bps: completion_bps(self.completed_qty.0, self.target_qty.0),
            average_price,
            arrival_slippage_bps: side_slippage_bps(
                self.side,
                average_price,
                self.benchmarks.arrival_price(),
            ),
            vwap_slippage_bps: optional_slippage_bps(
                self.side,
                average_price,
                self.benchmarks.vwap_price(),
            ),
            twap_slippage_bps: optional_slippage_bps(
                self.side,
                average_price,
                self.benchmarks.twap_price(),
            ),
            first_submit_ns: self.first_submit_ns,
            last_event_ns: self.last_event_ns,
            average_latency_ns: average_latency_ns(self.total_latency_ns, self.latency_samples),
        }
    }
}

/// Execution algorithm category for typed configuration.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AlgoKind {
    /// Time-weighted average price execution.
    Twap = 1,
    /// Percentage-of-volume execution.
    Pov = 2,
    /// Volume-weighted average price execution.
    Vwap = 3,
    /// Synthetic reserve/iceberg execution.
    Iceberg = 4,
    /// Implementation shortfall execution.
    ImplementationShortfall = 5,
    /// Passive queue/peg optimization.
    PassiveQueue = 6,
    /// Smart order routing.
    SmartOrderRouter = 7,
    /// Liquidity-seeking execution.
    LiquiditySeeking = 8,
    /// Aggressive sweep execution.
    Sweep = 9,
    /// Basket execution.
    Basket = 10,
    /// Two-leg spread execution.
    Spread = 11,
    /// Market-making quote planning.
    MarketMaking = 12,
    /// Host-defined algorithm.
    Custom = 255,
}

/// Typed parent-order configuration for algorithm construction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoParentConfig {
    id: ParentOrderId,
    account_id: AccountId,
    route_id: RouteId,
    strategy_id: StrategyId,
    symbol: ExecutionSymbol,
    side: OrderSide,
    order_type: OrderType,
    time_in_force: TimeInForce,
    total_qty: OrderQty,
    limit_price: OrderPrice,
    stop_price: OrderPrice,
    start_ns: u64,
    end_ns: u64,
    min_clip: OrderQty,
    max_clip: OrderQty,
    participation_cap_bps: u16,
}

impl AlgoParentConfig {
    /// Creates typed parent-order configuration.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when the resulting parent order would be invalid.
    #[allow(
        clippy::too_many_arguments,
        reason = "flat config mirrors externally supplied order ticket fields"
    )]
    pub fn new(
        id: ParentOrderId,
        account_id: AccountId,
        route_id: RouteId,
        strategy_id: StrategyId,
        symbol: ExecutionSymbol,
        side: OrderSide,
        order_type: OrderType,
        time_in_force: TimeInForce,
        total_qty: OrderQty,
        limit_price: OrderPrice,
        stop_price: OrderPrice,
        start_ns: u64,
        end_ns: u64,
        min_clip: OrderQty,
        max_clip: OrderQty,
        participation_cap_bps: u16,
    ) -> Result<Self, AlgoError> {
        let config = Self {
            id,
            account_id,
            route_id,
            strategy_id,
            symbol,
            side,
            order_type,
            time_in_force,
            total_qty,
            limit_price,
            stop_price,
            start_ns,
            end_ns,
            min_clip,
            max_clip,
            participation_cap_bps,
        };
        config.to_parent_order()?;
        Ok(config)
    }

    /// Creates config from an existing parent order.
    pub const fn from_parent(parent: ParentOrder) -> Self {
        Self {
            id: parent.id(),
            account_id: parent.account_id(),
            route_id: parent.route_id(),
            strategy_id: parent.strategy_id(),
            symbol: parent.symbol(),
            side: parent.side(),
            order_type: parent.order_type(),
            time_in_force: parent.time_in_force(),
            total_qty: parent.total_qty(),
            limit_price: parent.limit_price(),
            stop_price: parent.stop_price(),
            start_ns: parent.start_ns(),
            end_ns: parent.end_ns(),
            min_clip: parent.min_clip(),
            max_clip: parent.max_clip(),
            participation_cap_bps: parent.participation_cap_bps(),
        }
    }

    /// Builds a validated active parent order from the config.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when the configured parent is invalid.
    pub fn to_parent_order(&self) -> Result<ParentOrder, AlgoError> {
        ParentOrder::new(
            self.id,
            self.account_id,
            self.route_id,
            self.strategy_id,
            self.symbol,
            self.side,
            self.order_type,
            self.time_in_force,
            self.total_qty,
            self.limit_price,
            self.stop_price,
            self.start_ns,
            self.end_ns,
            self.min_clip,
            self.max_clip,
            self.participation_cap_bps,
        )
    }

    /// Returns parent identifier.
    pub const fn id(&self) -> ParentOrderId {
        self.id
    }

    /// Returns account identifier.
    pub const fn account_id(&self) -> AccountId {
        self.account_id
    }

    /// Returns default route identifier.
    pub const fn route_id(&self) -> RouteId {
        self.route_id
    }

    /// Returns strategy identifier.
    pub const fn strategy_id(&self) -> StrategyId {
        self.strategy_id
    }

    /// Returns execution symbol.
    pub const fn symbol(&self) -> ExecutionSymbol {
        self.symbol
    }

    /// Returns order side.
    pub const fn side(&self) -> OrderSide {
        self.side
    }

    /// Returns order type.
    pub const fn order_type(&self) -> OrderType {
        self.order_type
    }

    /// Returns time in force.
    pub const fn time_in_force(&self) -> TimeInForce {
        self.time_in_force
    }

    /// Returns total quantity.
    pub const fn total_qty(&self) -> OrderQty {
        self.total_qty
    }

    /// Returns limit price.
    pub const fn limit_price(&self) -> OrderPrice {
        self.limit_price
    }

    /// Returns stop price.
    pub const fn stop_price(&self) -> OrderPrice {
        self.stop_price
    }

    /// Returns algorithm start timestamp.
    pub const fn start_ns(&self) -> u64 {
        self.start_ns
    }

    /// Returns algorithm end timestamp.
    pub const fn end_ns(&self) -> u64 {
        self.end_ns
    }

    /// Returns minimum clip.
    pub const fn min_clip(&self) -> OrderQty {
        self.min_clip
    }

    /// Returns maximum clip.
    pub const fn max_clip(&self) -> OrderQty {
        self.max_clip
    }

    /// Returns participation cap in basis points, or zero when unset.
    pub const fn participation_cap_bps(&self) -> u16 {
        self.participation_cap_bps
    }
}

/// Typed top-level algorithm configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoConfig {
    kind: AlgoKind,
    parent: AlgoParentConfig,
    risk_limits: AlgoRiskLimits,
    recovery_policy: AlgoRecoveryPolicy,
}

impl AlgoConfig {
    /// Creates algorithm configuration.
    pub const fn new(kind: AlgoKind, parent: AlgoParentConfig) -> Self {
        Self {
            kind,
            parent,
            risk_limits: AlgoRiskLimits::unbounded(),
            recovery_policy: AlgoRecoveryPolicy::new(true, true, true),
        }
    }

    /// Returns algorithm kind.
    pub const fn kind(&self) -> AlgoKind {
        self.kind
    }

    /// Returns parent config.
    pub const fn parent(&self) -> AlgoParentConfig {
        self.parent
    }

    /// Returns risk limits.
    pub const fn risk_limits(&self) -> AlgoRiskLimits {
        self.risk_limits
    }

    /// Returns recovery policy.
    pub const fn recovery_policy(&self) -> AlgoRecoveryPolicy {
        self.recovery_policy
    }

    /// Returns a copy with risk limits.
    pub const fn with_risk_limits(mut self, limits: AlgoRiskLimits) -> Self {
        self.risk_limits = limits;
        self
    }

    /// Returns a copy with recovery policy.
    pub const fn with_recovery_policy(mut self, policy: AlgoRecoveryPolicy) -> Self {
        self.recovery_policy = policy;
        self
    }

    /// Builds a validated active parent order from the config.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when the configured parent is invalid.
    pub fn to_parent_order(&self) -> Result<ParentOrder, AlgoError> {
        self.parent.to_parent_order()
    }

    /// Builds a risk policy from configured risk limits.
    pub const fn to_risk_policy(&self) -> AlgoRiskPolicy {
        AlgoRiskPolicy::new(self.risk_limits)
    }
}

/// Deterministic TWAP slice planner.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TwapSlicePlanner {
    slice_interval_ns: u64,
}

impl TwapSlicePlanner {
    /// Creates a TWAP planner.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidSliceInterval`] when the interval is zero.
    pub const fn try_new(slice_interval_ns: u64) -> Result<Self, AlgoError> {
        if slice_interval_ns == 0 {
            return Err(AlgoError::InvalidSliceInterval);
        }
        Ok(Self { slice_interval_ns })
    }

    /// Creates a TWAP planner, panicking when the interval is zero.
    pub const fn new(slice_interval_ns: u64) -> Self {
        assert!(slice_interval_ns > 0, "slice interval must be positive");
        Self { slice_interval_ns }
    }

    /// Returns the configured slice interval.
    pub const fn slice_interval_ns(&self) -> u64 {
        self.slice_interval_ns
    }

    /// Plans one due child slice for `now_ns`.
    ///
    /// The planner uses only caller-provided timestamps and integer arithmetic.
    /// It returns `Ok(None)` when no additional child quantity is due.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when the parent/progress state is invalid or the
    /// generated child order would be invalid.
    #[allow(
        clippy::too_many_arguments,
        reason = "caller owns identifiers and timestamps"
    )]
    pub fn plan_due_slice(
        &self,
        parent: &ParentOrder,
        progress: AlgoProgress,
        now_ns: u64,
        child_id: ChildOrderId,
        client_order_id: ClientOrderId,
        ts_recv_ns: u64,
    ) -> Result<Option<ChildOrderPlan>, AlgoError> {
        parent.validate()?;
        if parent.status().is_terminal() {
            return Err(AlgoError::ParentTerminal);
        }
        if progress.parent_id() != parent.id() || progress.target_qty() != parent.total_qty() {
            return Err(AlgoError::InvalidProgress);
        }
        if progress.released_qty().0 > parent.total_qty().0
            || progress.completed_qty().0 > parent.total_qty().0
        {
            return Err(AlgoError::InvalidProgress);
        }
        if now_ns < parent.start_ns() || progress.is_complete() {
            return Ok(None);
        }

        let total_slices = div_ceil_u64(
            parent.end_ns().saturating_sub(parent.start_ns()),
            self.slice_interval_ns,
        )
        .max(1);
        let elapsed_ns = now_ns
            .min(parent.end_ns())
            .saturating_sub(parent.start_ns());
        let due_slices = (elapsed_ns / self.slice_interval_ns)
            .saturating_add(1)
            .min(total_slices);
        let desired = div_ceil_i128(
            i128::from(parent.total_qty().0) * i128::from(due_slices),
            i128::from(total_slices),
        );
        let desired_qty = i64::try_from(desired).unwrap_or(i64::MAX);
        let due_qty = desired_qty.saturating_sub(progress.released_qty().0);
        if due_qty <= 0 {
            return Ok(None);
        }
        let leaves = parent
            .total_qty()
            .0
            .saturating_sub(progress.released_qty().0);
        let mut child_qty = due_qty.min(parent.max_clip().0).min(leaves);
        let final_slice = progress.released_qty().0.saturating_add(child_qty)
            >= parent.total_qty().0
            || now_ns >= parent.end_ns();
        if child_qty < parent.min_clip().0 && !final_slice {
            return Ok(None);
        }
        if child_qty <= 0 {
            return Ok(None);
        }
        child_qty = child_qty.min(
            parent
                .total_qty()
                .0
                .saturating_sub(progress.released_qty().0),
        );
        let request = parent.build_order_request(client_order_id, OrderQty(child_qty), ts_recv_ns);
        Ok(Some(ChildOrderPlan::new(
            child_id,
            parent.id(),
            request,
            now_ns,
        )?))
    }
}

/// Deterministic percentage-of-volume child slice planner.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PovSlicePlanner {
    target_participation_bps: u16,
    max_participation_bps: u16,
}

impl PovSlicePlanner {
    /// Creates a POV planner.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidParticipationRate`] when target or cap is
    /// zero, or when target exceeds cap.
    pub const fn try_new(
        target_participation_bps: u16,
        max_participation_bps: u16,
    ) -> Result<Self, AlgoError> {
        if target_participation_bps == 0
            || max_participation_bps == 0
            || target_participation_bps > max_participation_bps
        {
            return Err(AlgoError::InvalidParticipationRate);
        }
        Ok(Self {
            target_participation_bps,
            max_participation_bps,
        })
    }

    /// Creates a POV planner, panicking when rates are invalid.
    pub const fn new(target_participation_bps: u16, max_participation_bps: u16) -> Self {
        assert!(
            target_participation_bps > 0
                && max_participation_bps > 0
                && target_participation_bps <= max_participation_bps,
            "participation target must be positive and <= cap"
        );
        Self {
            target_participation_bps,
            max_participation_bps,
        }
    }

    /// Returns target participation in basis points.
    pub const fn target_participation_bps(&self) -> u16 {
        self.target_participation_bps
    }

    /// Returns maximum participation in basis points.
    pub const fn max_participation_bps(&self) -> u16 {
        self.max_participation_bps
    }

    /// Plans one child slice from cumulative observed market volume.
    ///
    /// The planner assumes `observed_market_volume` excludes the algo's own
    /// child fills when the host can provide that view. If self-volume cannot
    /// be excluded, hosts should choose conservative rates and caps.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when parent/progress state is invalid or the
    /// generated child order would be invalid.
    #[allow(
        clippy::too_many_arguments,
        reason = "caller owns identifiers and timestamps"
    )]
    pub fn plan_volume_slice(
        &self,
        parent: &ParentOrder,
        progress: AlgoProgress,
        observed_market_volume: OrderQty,
        now_ns: u64,
        child_id: ChildOrderId,
        client_order_id: ClientOrderId,
        ts_recv_ns: u64,
    ) -> Result<Option<ChildOrderPlan>, AlgoError> {
        parent.validate()?;
        if parent.status().is_terminal() {
            return Err(AlgoError::ParentTerminal);
        }
        if progress.parent_id() != parent.id() || progress.target_qty() != parent.total_qty() {
            return Err(AlgoError::InvalidProgress);
        }
        if observed_market_volume.0 <= 0 || now_ns < parent.start_ns() || progress.is_complete() {
            return Ok(None);
        }

        let effective_max_bps = if parent.participation_cap_bps() == 0 {
            self.max_participation_bps
        } else {
            self.max_participation_bps
                .min(parent.participation_cap_bps())
        };
        if self.target_participation_bps == 0
            || effective_max_bps == 0
            || self.target_participation_bps > effective_max_bps
        {
            return Err(AlgoError::InvalidParticipationRate);
        }

        let desired = participation_qty(observed_market_volume.0, self.target_participation_bps)
            .min(parent.total_qty().0);
        let max_allowed = participation_qty(observed_market_volume.0, effective_max_bps)
            .min(parent.total_qty().0);
        let due_qty = desired
            .min(max_allowed)
            .saturating_sub(progress.released_qty().0);
        if due_qty <= 0 {
            return Ok(None);
        }

        let leaves = parent
            .total_qty()
            .0
            .saturating_sub(progress.released_qty().0);
        let mut child_qty = due_qty.min(parent.max_clip().0).min(leaves);
        let final_slice = progress.released_qty().0.saturating_add(child_qty)
            >= parent.total_qty().0
            || now_ns >= parent.end_ns();
        if child_qty < parent.min_clip().0 && !final_slice {
            return Ok(None);
        }
        if child_qty <= 0 {
            return Ok(None);
        }
        child_qty = child_qty.min(
            parent
                .total_qty()
                .0
                .saturating_sub(progress.released_qty().0),
        );
        let request = parent.build_order_request(client_order_id, OrderQty(child_qty), ts_recv_ns);
        Ok(Some(ChildOrderPlan::new(
            child_id,
            parent.id(),
            request,
            now_ns,
        )?))
    }
}

/// Borrowed cumulative volume curve for VWAP planning.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VwapVolumeCurve<'a> {
    start_ns: u64,
    bucket_interval_ns: u64,
    cumulative_weights: &'a [u64],
}

impl<'a> VwapVolumeCurve<'a> {
    /// Creates a borrowed cumulative VWAP volume curve.
    ///
    /// `cumulative_weights` must be non-empty, strictly positive at the end,
    /// and monotonically non-decreasing. The last element is the total expected
    /// volume weight for the parent interval.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidVolumeProfile`] when the interval is zero,
    /// the curve is empty, total weight is zero, or cumulative weights regress.
    pub fn new(
        start_ns: u64,
        bucket_interval_ns: u64,
        cumulative_weights: &'a [u64],
    ) -> Result<Self, AlgoError> {
        if bucket_interval_ns == 0 || cumulative_weights.is_empty() {
            return Err(AlgoError::InvalidVolumeProfile);
        }
        let Some(total) = cumulative_weights.last().copied() else {
            return Err(AlgoError::InvalidVolumeProfile);
        };
        if total == 0 {
            return Err(AlgoError::InvalidVolumeProfile);
        }
        let mut previous = 0_u64;
        for weight in cumulative_weights {
            if *weight < previous {
                return Err(AlgoError::InvalidVolumeProfile);
            }
            previous = *weight;
        }
        Ok(Self {
            start_ns,
            bucket_interval_ns,
            cumulative_weights,
        })
    }

    /// Returns curve start timestamp.
    pub const fn start_ns(&self) -> u64 {
        self.start_ns
    }

    /// Returns bucket interval in nanoseconds.
    pub const fn bucket_interval_ns(&self) -> u64 {
        self.bucket_interval_ns
    }

    /// Returns cumulative profile weights.
    pub const fn cumulative_weights(&self) -> &'a [u64] {
        self.cumulative_weights
    }

    /// Returns total curve weight.
    pub fn total_weight(&self) -> u64 {
        self.cumulative_weights
            .last()
            .copied()
            .expect("validated curve is non-empty")
    }

    fn cumulative_weight_at(&self, now_ns: u64) -> u64 {
        if now_ns < self.start_ns {
            return 0;
        }
        let elapsed = now_ns.saturating_sub(self.start_ns);
        let index = (elapsed / self.bucket_interval_ns) as usize;
        let capped = index.min(self.cumulative_weights.len().saturating_sub(1));
        self.cumulative_weights[capped]
    }
}

/// Deterministic VWAP child slice planner.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VwapSlicePlanner<'a> {
    curve: VwapVolumeCurve<'a>,
}

impl<'a> VwapSlicePlanner<'a> {
    /// Creates a VWAP planner from a validated volume curve.
    pub const fn new(curve: VwapVolumeCurve<'a>) -> Self {
        Self { curve }
    }

    /// Returns the borrowed volume curve.
    pub const fn curve(&self) -> VwapVolumeCurve<'a> {
        self.curve
    }

    /// Plans one child slice from the expected cumulative volume curve.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when parent/progress state is invalid or the
    /// generated child order would be invalid.
    #[allow(
        clippy::too_many_arguments,
        reason = "caller owns identifiers and timestamps"
    )]
    pub fn plan_curve_slice(
        &self,
        parent: &ParentOrder,
        progress: AlgoProgress,
        now_ns: u64,
        child_id: ChildOrderId,
        client_order_id: ClientOrderId,
        ts_recv_ns: u64,
    ) -> Result<Option<ChildOrderPlan>, AlgoError> {
        parent.validate()?;
        if parent.status().is_terminal() {
            return Err(AlgoError::ParentTerminal);
        }
        if progress.parent_id() != parent.id() || progress.target_qty() != parent.total_qty() {
            return Err(AlgoError::InvalidProgress);
        }
        if now_ns < parent.start_ns() || progress.is_complete() {
            return Ok(None);
        }

        let cumulative_weight = self.curve.cumulative_weight_at(now_ns);
        if cumulative_weight == 0 {
            return Ok(None);
        }
        let desired = vwap_target_qty(
            parent.total_qty().0,
            cumulative_weight,
            self.curve.total_weight(),
        );
        let due_qty = desired.saturating_sub(progress.released_qty().0);
        if due_qty <= 0 {
            return Ok(None);
        }

        let leaves = parent
            .total_qty()
            .0
            .saturating_sub(progress.released_qty().0);
        let mut child_qty = due_qty.min(parent.max_clip().0).min(leaves);
        let final_slice = progress.released_qty().0.saturating_add(child_qty)
            >= parent.total_qty().0
            || now_ns >= parent.end_ns();
        if child_qty < parent.min_clip().0 && !final_slice {
            return Ok(None);
        }
        if child_qty <= 0 {
            return Ok(None);
        }
        child_qty = child_qty.min(
            parent
                .total_qty()
                .0
                .saturating_sub(progress.released_qty().0),
        );
        let request = parent.build_order_request(client_order_id, OrderQty(child_qty), ts_recv_ns);
        Ok(Some(ChildOrderPlan::new(
            child_id,
            parent.id(),
            request,
            now_ns,
        )?))
    }
}

/// Deterministic synthetic iceberg replenishment planner.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IcebergSlicePlanner {
    display_qty: OrderQty,
    replenish_threshold: OrderQty,
}

impl IcebergSlicePlanner {
    /// Creates an iceberg planner.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidDisplayQuantity`] when display quantity is
    /// non-positive, threshold is negative, or threshold exceeds display size.
    pub const fn try_new(
        display_qty: OrderQty,
        replenish_threshold: OrderQty,
    ) -> Result<Self, AlgoError> {
        if display_qty.0 <= 0 || replenish_threshold.0 < 0 || replenish_threshold.0 > display_qty.0
        {
            return Err(AlgoError::InvalidDisplayQuantity);
        }
        Ok(Self {
            display_qty,
            replenish_threshold,
        })
    }

    /// Creates an iceberg planner, panicking when display settings are invalid.
    pub const fn new(display_qty: OrderQty, replenish_threshold: OrderQty) -> Self {
        assert!(
            display_qty.0 > 0
                && replenish_threshold.0 >= 0
                && replenish_threshold.0 <= display_qty.0,
            "iceberg display quantity must be positive and threshold must be within display"
        );
        Self {
            display_qty,
            replenish_threshold,
        }
    }

    /// Returns the target displayed child quantity.
    pub const fn display_qty(&self) -> OrderQty {
        self.display_qty
    }

    /// Returns the open-quantity threshold at or below which replenishment is
    /// due.
    pub const fn replenish_threshold(&self) -> OrderQty {
        self.replenish_threshold
    }

    /// Plans one synthetic iceberg replenishment child.
    ///
    /// The host remains responsible for deciding whether to use native venue
    /// reserve/iceberg order support or submit synthetic child orders through
    /// the OMS.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when parent/progress state is invalid or the
    /// generated child order would be invalid.
    #[allow(
        clippy::too_many_arguments,
        reason = "caller owns identifiers and timestamps"
    )]
    pub fn plan_replenishment(
        &self,
        parent: &ParentOrder,
        progress: AlgoProgress,
        now_ns: u64,
        child_id: ChildOrderId,
        client_order_id: ClientOrderId,
        ts_recv_ns: u64,
    ) -> Result<Option<ChildOrderPlan>, AlgoError> {
        parent.validate()?;
        if parent.status().is_terminal() {
            return Err(AlgoError::ParentTerminal);
        }
        if progress.parent_id() != parent.id() || progress.target_qty() != parent.total_qty() {
            return Err(AlgoError::InvalidProgress);
        }
        if now_ns < parent.start_ns()
            || progress.is_complete()
            || progress.open_qty().0 > self.replenish_threshold.0
        {
            return Ok(None);
        }

        let leaves = parent
            .total_qty()
            .0
            .saturating_sub(progress.released_qty().0);
        if leaves <= 0 {
            return Ok(None);
        }
        let mut child_qty = self.display_qty.0.min(parent.max_clip().0).min(leaves);
        let final_slice = progress.released_qty().0.saturating_add(child_qty)
            >= parent.total_qty().0
            || now_ns >= parent.end_ns();
        if child_qty < parent.min_clip().0 && !final_slice {
            return Ok(None);
        }
        if child_qty <= 0 {
            return Ok(None);
        }
        child_qty = child_qty.min(
            parent
                .total_qty()
                .0
                .saturating_sub(progress.released_qty().0),
        );
        let request = parent.build_order_request(client_order_id, OrderQty(child_qty), ts_recv_ns);
        Ok(Some(ChildOrderPlan::new(
            child_id,
            parent.id(),
            request,
            now_ns,
        )?))
    }
}

/// Passive peg reference used by [`PassiveQueuePlanner`].
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PassivePegMode {
    /// Quote at the same-side best price.
    SameSide = 1,
    /// Quote at the midpoint when the spread allows it.
    Midpoint = 2,
    /// Quote one passive tick inside the spread when possible.
    ImproveOneTick = 3,
}

/// Passive queue action selected by [`PassiveQueuePlanner`].
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PassiveQueueAction {
    /// Do not release a child order for this decision.
    Wait = 1,
    /// Join the selected passive queue.
    JoinQueue = 2,
    /// Improve the selected passive price inside the spread.
    ImprovePrice = 3,
    /// Cross the spread because the configured time budget is exhausted.
    CrossSpread = 4,
}

impl PassiveQueueAction {
    /// Returns true when the action releases a child order.
    pub const fn releases_child(self) -> bool {
        matches!(
            self,
            Self::JoinQueue | Self::ImprovePrice | Self::CrossSpread
        )
    }
}

/// Market context for passive queue planning.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PassiveQueueContext {
    best_bid: OrderPrice,
    best_ask: OrderPrice,
    queue_ahead_qty: OrderQty,
    expected_take_qty: OrderQty,
    adverse_selection_bps: u16,
}

impl PassiveQueueContext {
    /// Creates passive queue market context.
    ///
    /// `queue_ahead_qty` is the visible or modeled quantity ahead of the
    /// planned child at the candidate price. `expected_take_qty` is the host's
    /// short-horizon estimate of contra-side volume that can trade through the
    /// queue.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidPassiveQueueParameters`] when best bid/ask
    /// are non-positive, crossed, or queue quantities are negative.
    pub const fn new(
        best_bid: OrderPrice,
        best_ask: OrderPrice,
        queue_ahead_qty: OrderQty,
        expected_take_qty: OrderQty,
        adverse_selection_bps: u16,
    ) -> Result<Self, AlgoError> {
        if best_bid.0 <= 0
            || best_ask.0 <= 0
            || best_bid.0 >= best_ask.0
            || queue_ahead_qty.0 < 0
            || expected_take_qty.0 < 0
        {
            return Err(AlgoError::InvalidPassiveQueueParameters);
        }
        Ok(Self {
            best_bid,
            best_ask,
            queue_ahead_qty,
            expected_take_qty,
            adverse_selection_bps,
        })
    }

    /// Returns the current best bid.
    pub const fn best_bid(&self) -> OrderPrice {
        self.best_bid
    }

    /// Returns the current best ask.
    pub const fn best_ask(&self) -> OrderPrice {
        self.best_ask
    }

    /// Returns estimated quantity ahead at the candidate queue.
    pub const fn queue_ahead_qty(&self) -> OrderQty {
        self.queue_ahead_qty
    }

    /// Returns expected contra-side trade quantity at the candidate queue.
    pub const fn expected_take_qty(&self) -> OrderQty {
        self.expected_take_qty
    }

    /// Returns adverse-selection estimate in basis points.
    pub const fn adverse_selection_bps(&self) -> u16 {
        self.adverse_selection_bps
    }
}

/// Configuration for passive queue planning.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PassiveQueueConfig {
    peg_mode: PassivePegMode,
    tick_size: OrderPrice,
    min_fill_probability_bps: u16,
    max_adverse_selection_bps: u16,
    improve_when_fill_below_bps: u16,
    max_improvement_ticks: u16,
    allow_cross: bool,
    cross_after_elapsed_bps: u16,
}

impl PassiveQueueConfig {
    /// Creates passive queue configuration with conservative defaults.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidPassiveQueueParameters`] when tick size is
    /// not positive.
    pub const fn new(peg_mode: PassivePegMode, tick_size: OrderPrice) -> Result<Self, AlgoError> {
        if tick_size.0 <= 0 {
            return Err(AlgoError::InvalidPassiveQueueParameters);
        }
        Ok(Self {
            peg_mode,
            tick_size,
            min_fill_probability_bps: 2_500,
            max_adverse_selection_bps: 250,
            improve_when_fill_below_bps: 1_500,
            max_improvement_ticks: 1,
            allow_cross: false,
            cross_after_elapsed_bps: 9_500,
        })
    }

    /// Returns a copy with queue thresholds updated.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidPassiveQueueParameters`] when any basis
    /// point value exceeds 10,000.
    pub const fn with_thresholds(
        mut self,
        min_fill_probability_bps: u16,
        max_adverse_selection_bps: u16,
        improve_when_fill_below_bps: u16,
    ) -> Result<Self, AlgoError> {
        if min_fill_probability_bps > 10_000
            || max_adverse_selection_bps > 10_000
            || improve_when_fill_below_bps > 10_000
        {
            return Err(AlgoError::InvalidPassiveQueueParameters);
        }
        self.min_fill_probability_bps = min_fill_probability_bps;
        self.max_adverse_selection_bps = max_adverse_selection_bps;
        self.improve_when_fill_below_bps = improve_when_fill_below_bps;
        Ok(self)
    }

    /// Returns a copy with maximum inside-spread improvement ticks updated.
    pub const fn with_max_improvement_ticks(mut self, max_improvement_ticks: u16) -> Self {
        self.max_improvement_ticks = max_improvement_ticks;
        self
    }

    /// Returns a copy with crossing behavior updated.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidPassiveQueueParameters`] when elapsed basis
    /// points exceed 10,000.
    pub const fn with_crossing(
        mut self,
        allow_cross: bool,
        cross_after_elapsed_bps: u16,
    ) -> Result<Self, AlgoError> {
        if cross_after_elapsed_bps > 10_000 {
            return Err(AlgoError::InvalidPassiveQueueParameters);
        }
        self.allow_cross = allow_cross;
        self.cross_after_elapsed_bps = cross_after_elapsed_bps;
        Ok(self)
    }

    /// Returns peg mode.
    pub const fn peg_mode(&self) -> PassivePegMode {
        self.peg_mode
    }

    /// Returns tick size in normalized price units.
    pub const fn tick_size(&self) -> OrderPrice {
        self.tick_size
    }

    /// Returns minimum fill probability in basis points.
    pub const fn min_fill_probability_bps(&self) -> u16 {
        self.min_fill_probability_bps
    }

    /// Returns maximum tolerated adverse selection in basis points.
    pub const fn max_adverse_selection_bps(&self) -> u16 {
        self.max_adverse_selection_bps
    }

    /// Returns fill-probability threshold below which improvement is preferred.
    pub const fn improve_when_fill_below_bps(&self) -> u16 {
        self.improve_when_fill_below_bps
    }

    /// Returns maximum passive improvement ticks.
    pub const fn max_improvement_ticks(&self) -> u16 {
        self.max_improvement_ticks
    }

    /// Returns true when the planner may cross the spread after the time
    /// threshold.
    pub const fn allow_cross(&self) -> bool {
        self.allow_cross
    }

    /// Returns elapsed parent interval threshold for crossing.
    pub const fn cross_after_elapsed_bps(&self) -> u16 {
        self.cross_after_elapsed_bps
    }
}

impl Default for PassiveQueueConfig {
    fn default() -> Self {
        Self::new(PassivePegMode::SameSide, OrderPrice(1))
            .expect("static passive queue defaults are valid")
    }
}

/// Passive queue planning estimate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PassiveQueueEstimate {
    action: PassiveQueueAction,
    candidate_price: OrderPrice,
    fill_probability_bps: u16,
    elapsed_bps: u16,
    candidate_qty: OrderQty,
}

impl PassiveQueueEstimate {
    /// Returns selected passive queue action.
    pub const fn action(&self) -> PassiveQueueAction {
        self.action
    }

    /// Returns selected limit price.
    pub const fn candidate_price(&self) -> OrderPrice {
        self.candidate_price
    }

    /// Returns estimated fill probability in basis points.
    pub const fn fill_probability_bps(&self) -> u16 {
        self.fill_probability_bps
    }

    /// Returns elapsed parent interval in basis points.
    pub const fn elapsed_bps(&self) -> u16 {
        self.elapsed_bps
    }

    /// Returns candidate child quantity used for the estimate.
    pub const fn candidate_qty(&self) -> OrderQty {
        self.candidate_qty
    }
}

/// Passive queue decision with an optional child order plan.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PassiveQueueDecision {
    estimate: PassiveQueueEstimate,
    child: Option<ChildOrderPlan>,
}

impl PassiveQueueDecision {
    /// Returns the estimate that drove the decision.
    pub const fn estimate(&self) -> PassiveQueueEstimate {
        self.estimate
    }

    /// Returns the selected action.
    pub const fn action(&self) -> PassiveQueueAction {
        self.estimate.action()
    }

    /// Returns the optional child order plan.
    pub const fn child(&self) -> Option<ChildOrderPlan> {
        self.child
    }
}

/// Deterministic passive peg and queue-position planner.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PassiveQueuePlanner {
    config: PassiveQueueConfig,
}

impl PassiveQueuePlanner {
    /// Creates a passive queue planner.
    pub const fn new(config: PassiveQueueConfig) -> Self {
        Self { config }
    }

    /// Returns planner configuration.
    pub const fn config(&self) -> PassiveQueueConfig {
        self.config
    }

    /// Estimates passive queue action, price, fill probability, and quantity.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when parent/progress/context state is invalid.
    pub fn estimate(
        &self,
        parent: &ParentOrder,
        progress: AlgoProgress,
        now_ns: u64,
        context: PassiveQueueContext,
    ) -> Result<PassiveQueueEstimate, AlgoError> {
        parent.validate()?;
        self.validate_context(context)?;
        if progress.parent_id() != parent.id() || progress.target_qty() != parent.total_qty() {
            return Err(AlgoError::InvalidProgress);
        }

        let candidate_qty = passive_candidate_qty(parent, progress, now_ns);
        let fill_probability_bps = queue_fill_probability_bps(
            context.queue_ahead_qty().0,
            candidate_qty.0,
            context.expected_take_qty().0,
        );
        let elapsed = elapsed_bps(parent.start_ns(), parent.end_ns(), now_ns);
        let action = self.select_action(parent, now_ns, context, fill_probability_bps, elapsed);
        let candidate_price = self.price_for_action(parent.side(), context, action);

        Ok(PassiveQueueEstimate {
            action,
            candidate_price,
            fill_probability_bps,
            elapsed_bps: elapsed,
            candidate_qty,
        })
    }

    /// Plans one passive queue child decision.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when parent/progress/context state is invalid or
    /// the generated child order would be invalid.
    #[allow(
        clippy::too_many_arguments,
        reason = "caller owns identifiers and timestamps"
    )]
    pub fn plan_passive_slice(
        &self,
        parent: &ParentOrder,
        progress: AlgoProgress,
        now_ns: u64,
        context: PassiveQueueContext,
        child_id: ChildOrderId,
        client_order_id: ClientOrderId,
        ts_recv_ns: u64,
    ) -> Result<PassiveQueueDecision, AlgoError> {
        if parent.status().is_terminal() {
            return Err(AlgoError::ParentTerminal);
        }
        if now_ns < parent.start_ns() || progress.is_complete() {
            let estimate = self.estimate(parent, progress, now_ns, context)?;
            return Ok(PassiveQueueDecision {
                estimate: PassiveQueueEstimate {
                    action: PassiveQueueAction::Wait,
                    ..estimate
                },
                child: None,
            });
        }

        let estimate = self.estimate(parent, progress, now_ns, context)?;
        if !estimate.action().releases_child() || estimate.candidate_qty().0 <= 0 {
            return Ok(PassiveQueueDecision {
                estimate,
                child: None,
            });
        }
        let final_slice = progress
            .released_qty()
            .0
            .saturating_add(estimate.candidate_qty().0)
            >= parent.total_qty().0
            || now_ns >= parent.end_ns();
        if estimate.candidate_qty().0 < parent.min_clip().0 && !final_slice {
            return Ok(PassiveQueueDecision {
                estimate: PassiveQueueEstimate {
                    action: PassiveQueueAction::Wait,
                    ..estimate
                },
                child: None,
            });
        }

        let request = parent.build_order_request_at_price(
            client_order_id,
            estimate.candidate_qty(),
            estimate.candidate_price(),
            ts_recv_ns,
        );
        Ok(PassiveQueueDecision {
            estimate,
            child: Some(ChildOrderPlan::new(child_id, parent.id(), request, now_ns)?),
        })
    }

    fn validate_context(&self, context: PassiveQueueContext) -> Result<(), AlgoError> {
        if self.config.tick_size().0 <= 0
            || self.config.min_fill_probability_bps() > 10_000
            || self.config.max_adverse_selection_bps() > 10_000
            || self.config.improve_when_fill_below_bps() > 10_000
            || self.config.cross_after_elapsed_bps() > 10_000
            || context.best_bid().0 <= 0
            || context.best_ask().0 <= 0
            || context.best_bid().0 >= context.best_ask().0
            || context.queue_ahead_qty().0 < 0
            || context.expected_take_qty().0 < 0
        {
            return Err(AlgoError::InvalidPassiveQueueParameters);
        }
        Ok(())
    }

    fn select_action(
        &self,
        parent: &ParentOrder,
        now_ns: u64,
        context: PassiveQueueContext,
        fill_probability_bps: u16,
        elapsed: u16,
    ) -> PassiveQueueAction {
        if context.adverse_selection_bps() > self.config.max_adverse_selection_bps() {
            return PassiveQueueAction::Wait;
        }
        if self.config.allow_cross() && elapsed >= self.config.cross_after_elapsed_bps() {
            return PassiveQueueAction::CrossSpread;
        }
        if fill_probability_bps < self.config.improve_when_fill_below_bps()
            && self.can_improve(parent.side(), context)
            && now_ns < parent.end_ns()
        {
            return PassiveQueueAction::ImprovePrice;
        }
        if fill_probability_bps >= self.config.min_fill_probability_bps()
            || self.config.peg_mode() != PassivePegMode::SameSide
        {
            return PassiveQueueAction::JoinQueue;
        }
        PassiveQueueAction::Wait
    }

    fn price_for_action(
        &self,
        side: OrderSide,
        context: PassiveQueueContext,
        action: PassiveQueueAction,
    ) -> OrderPrice {
        match action {
            PassiveQueueAction::Wait | PassiveQueueAction::JoinQueue => {
                self.base_price(side, context)
            }
            PassiveQueueAction::ImprovePrice => self.improved_price(side, context),
            PassiveQueueAction::CrossSpread => match side {
                OrderSide::Buy => context.best_ask(),
                OrderSide::Sell => context.best_bid(),
            },
        }
    }

    fn base_price(&self, side: OrderSide, context: PassiveQueueContext) -> OrderPrice {
        match self.config.peg_mode() {
            PassivePegMode::SameSide => match side {
                OrderSide::Buy => context.best_bid(),
                OrderSide::Sell => context.best_ask(),
            },
            PassivePegMode::Midpoint => midpoint_price(side, context, self.config.tick_size()),
            PassivePegMode::ImproveOneTick => self.improved_price(side, context),
        }
    }

    fn improved_price(&self, side: OrderSide, context: PassiveQueueContext) -> OrderPrice {
        let ticks = i64::from(self.config.max_improvement_ticks().max(1));
        let improvement = self.config.tick_size().0.saturating_mul(ticks);
        match side {
            OrderSide::Buy => {
                let max_passive = context
                    .best_ask()
                    .0
                    .saturating_sub(self.config.tick_size().0);
                OrderPrice(
                    context
                        .best_bid()
                        .0
                        .saturating_add(improvement)
                        .min(max_passive),
                )
            }
            OrderSide::Sell => {
                let min_passive = context
                    .best_bid()
                    .0
                    .saturating_add(self.config.tick_size().0);
                OrderPrice(
                    context
                        .best_ask()
                        .0
                        .saturating_sub(improvement)
                        .max(min_passive),
                )
            }
        }
    }

    fn can_improve(&self, side: OrderSide, context: PassiveQueueContext) -> bool {
        if self.config.max_improvement_ticks() == 0 {
            return false;
        }
        let spread = context.best_ask().0.saturating_sub(context.best_bid().0);
        if spread <= self.config.tick_size().0 {
            return false;
        }
        self.improved_price(side, context) != self.base_price(side, context)
    }
}

/// Route availability state used by [`SorPlanner`].
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SorRouteStatus {
    /// Route is available for new child orders.
    Available = 1,
    /// Route is blocked by policy, risk, or operator action.
    Blocked = 2,
    /// Route is degraded and should be skipped by default routing.
    Degraded = 3,
    /// Route is temporarily cooling down after rejects, disconnects, or throttles.
    Cooldown = 4,
}

impl SorRouteStatus {
    /// Returns true when the route can receive a new child order.
    pub const fn is_routable(self) -> bool {
        matches!(self, Self::Available)
    }
}

/// Order-type capability advertised by a SOR route.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SorRouteCapability {
    supports_limit: bool,
    supports_market: bool,
}

impl SorRouteCapability {
    /// Creates route order-type capability flags.
    pub const fn new(supports_limit: bool, supports_market: bool) -> Self {
        Self {
            supports_limit,
            supports_market,
        }
    }

    /// Returns true when limit orders are supported.
    pub const fn supports_limit(&self) -> bool {
        self.supports_limit
    }

    /// Returns true when market orders are supported.
    pub const fn supports_market(&self) -> bool {
        self.supports_market
    }

    fn supports_order_type(&self, order_type: OrderType) -> bool {
        match order_type {
            OrderType::Limit | OrderType::StopLimit => self.supports_limit,
            OrderType::Market | OrderType::Stop => self.supports_market,
        }
    }
}

impl Default for SorRouteCapability {
    fn default() -> Self {
        Self::new(true, true)
    }
}

/// Route quality metrics used for smart-order-router scoring.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SorRouteMetrics {
    fee_bps: i16,
    latency_us: u32,
    reject_rate_bps: u16,
    fill_probability_bps: u16,
    toxicity_bps: u16,
    data_quality_bps: u16,
}

impl SorRouteMetrics {
    /// Creates route metrics for deterministic scoring.
    ///
    /// `fee_bps` may be negative for rebates. All unsigned basis-point values
    /// must be at most 10,000.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidSorParameters`] when a metric is outside
    /// its supported range.
    pub const fn new(
        fee_bps: i16,
        latency_us: u32,
        reject_rate_bps: u16,
        fill_probability_bps: u16,
        toxicity_bps: u16,
        data_quality_bps: u16,
    ) -> Result<Self, AlgoError> {
        if fee_bps < -10_000
            || fee_bps > 10_000
            || reject_rate_bps > 10_000
            || fill_probability_bps > 10_000
            || toxicity_bps > 10_000
            || data_quality_bps > 10_000
        {
            return Err(AlgoError::InvalidSorParameters);
        }
        Ok(Self {
            fee_bps,
            latency_us,
            reject_rate_bps,
            fill_probability_bps,
            toxicity_bps,
            data_quality_bps,
        })
    }

    /// Returns fee or rebate estimate in basis points.
    pub const fn fee_bps(&self) -> i16 {
        self.fee_bps
    }

    /// Returns route latency estimate in microseconds.
    pub const fn latency_us(&self) -> u32 {
        self.latency_us
    }

    /// Returns recent route reject rate in basis points.
    pub const fn reject_rate_bps(&self) -> u16 {
        self.reject_rate_bps
    }

    /// Returns estimated route fill probability in basis points.
    pub const fn fill_probability_bps(&self) -> u16 {
        self.fill_probability_bps
    }

    /// Returns route toxicity estimate in basis points.
    pub const fn toxicity_bps(&self) -> u16 {
        self.toxicity_bps
    }

    /// Returns market-data quality score in basis points.
    pub const fn data_quality_bps(&self) -> u16 {
        self.data_quality_bps
    }
}

impl Default for SorRouteMetrics {
    fn default() -> Self {
        Self {
            fee_bps: 0,
            latency_us: 0,
            reject_rate_bps: 0,
            fill_probability_bps: 10_000,
            toxicity_bps: 0,
            data_quality_bps: 10_000,
        }
    }
}

/// Routable liquidity candidate consumed by [`SorPlanner`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SorRouteCandidate {
    route_id: RouteId,
    price: OrderPrice,
    available_qty: OrderQty,
    status: SorRouteStatus,
    capability: SorRouteCapability,
    metrics: SorRouteMetrics,
}

impl SorRouteCandidate {
    /// Creates an available route candidate with default capabilities and
    /// metrics.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidSorParameters`] when price or available
    /// quantity is non-positive.
    pub const fn new(
        route_id: RouteId,
        price: OrderPrice,
        available_qty: OrderQty,
    ) -> Result<Self, AlgoError> {
        if price.0 <= 0 || available_qty.0 <= 0 {
            return Err(AlgoError::InvalidSorParameters);
        }
        Ok(Self {
            route_id,
            price,
            available_qty,
            status: SorRouteStatus::Available,
            capability: SorRouteCapability::new(true, true),
            metrics: SorRouteMetrics {
                fee_bps: 0,
                latency_us: 0,
                reject_rate_bps: 0,
                fill_probability_bps: 10_000,
                toxicity_bps: 0,
                data_quality_bps: 10_000,
            },
        })
    }

    /// Returns a copy with route status updated.
    pub const fn with_status(mut self, status: SorRouteStatus) -> Self {
        self.status = status;
        self
    }

    /// Returns a copy with capability updated.
    pub const fn with_capability(mut self, capability: SorRouteCapability) -> Self {
        self.capability = capability;
        self
    }

    /// Returns a copy with route metrics updated.
    pub const fn with_metrics(mut self, metrics: SorRouteMetrics) -> Self {
        self.metrics = metrics;
        self
    }

    /// Returns route identifier.
    pub const fn route_id(&self) -> RouteId {
        self.route_id
    }

    /// Returns route price.
    pub const fn price(&self) -> OrderPrice {
        self.price
    }

    /// Returns available route quantity.
    pub const fn available_qty(&self) -> OrderQty {
        self.available_qty
    }

    /// Returns route status.
    pub const fn status(&self) -> SorRouteStatus {
        self.status
    }

    /// Returns route capability flags.
    pub const fn capability(&self) -> SorRouteCapability {
        self.capability
    }

    /// Returns route metrics.
    pub const fn metrics(&self) -> SorRouteMetrics {
        self.metrics
    }
}

/// Integer score weights for [`SorPlanner`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SorScoreWeights {
    price_weight: u16,
    liquidity_weight: u16,
    fee_weight: u16,
    latency_weight: u16,
    reject_weight: u16,
    fill_weight: u16,
    toxicity_weight: u16,
    data_quality_weight: u16,
}

impl SorScoreWeights {
    /// Creates SOR score weights.
    #[allow(
        clippy::too_many_arguments,
        reason = "flat constructor keeps score weights explicit and allocation-free"
    )]
    pub const fn new(
        price_weight: u16,
        liquidity_weight: u16,
        fee_weight: u16,
        latency_weight: u16,
        reject_weight: u16,
        fill_weight: u16,
        toxicity_weight: u16,
        data_quality_weight: u16,
    ) -> Self {
        Self {
            price_weight,
            liquidity_weight,
            fee_weight,
            latency_weight,
            reject_weight,
            fill_weight,
            toxicity_weight,
            data_quality_weight,
        }
    }

    /// Returns price weight.
    pub const fn price_weight(&self) -> u16 {
        self.price_weight
    }

    /// Returns liquidity weight.
    pub const fn liquidity_weight(&self) -> u16 {
        self.liquidity_weight
    }

    /// Returns fee weight.
    pub const fn fee_weight(&self) -> u16 {
        self.fee_weight
    }

    /// Returns latency weight.
    pub const fn latency_weight(&self) -> u16 {
        self.latency_weight
    }

    /// Returns reject-rate weight.
    pub const fn reject_weight(&self) -> u16 {
        self.reject_weight
    }

    /// Returns fill-probability weight.
    pub const fn fill_weight(&self) -> u16 {
        self.fill_weight
    }

    /// Returns toxicity weight.
    pub const fn toxicity_weight(&self) -> u16 {
        self.toxicity_weight
    }

    /// Returns data-quality weight.
    pub const fn data_quality_weight(&self) -> u16 {
        self.data_quality_weight
    }
}

impl Default for SorScoreWeights {
    fn default() -> Self {
        Self::new(8, 2, 2, 1, 3, 3, 4, 1)
    }
}

/// Smart-order-router configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SorConfig {
    max_route_count: usize,
    weights: SorScoreWeights,
}

impl SorConfig {
    /// Creates SOR configuration.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidSorParameters`] when max route count is
    /// zero.
    pub const fn new(max_route_count: usize, weights: SorScoreWeights) -> Result<Self, AlgoError> {
        if max_route_count == 0 {
            return Err(AlgoError::InvalidSorParameters);
        }
        Ok(Self {
            max_route_count,
            weights,
        })
    }

    /// Returns maximum number of routes to allocate in one decision.
    pub const fn max_route_count(&self) -> usize {
        self.max_route_count
    }

    /// Returns score weights.
    pub const fn weights(&self) -> SorScoreWeights {
        self.weights
    }
}

impl Default for SorConfig {
    fn default() -> Self {
        Self::new(4, SorScoreWeights::default()).expect("static SOR defaults are valid")
    }
}

/// Scored child allocation produced by [`SorPlanner`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SorChildAllocation {
    score: i64,
    plan: ChildOrderPlan,
}

impl SorChildAllocation {
    /// Returns route score used for selection.
    pub const fn score(&self) -> i64 {
        self.score
    }

    /// Returns planned child order for the selected route.
    pub const fn plan(&self) -> ChildOrderPlan {
        self.plan
    }
}

/// Fixed-capacity SOR decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SorDecision<const N: usize = DEFAULT_ALGO_DECISION_CAPACITY> {
    allocations: [Option<SorChildAllocation>; N],
    len: usize,
    considered_routes: usize,
    blocked_routes: usize,
}

impl<const N: usize> SorDecision<N> {
    /// Creates an empty SOR decision.
    pub const fn new(considered_routes: usize) -> Self {
        Self {
            allocations: [None; N],
            len: 0,
            considered_routes,
            blocked_routes: 0,
        }
    }

    /// Returns allocation count.
    pub const fn len(&self) -> usize {
        self.len
    }

    /// Returns true when no allocations were produced.
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns number of considered route candidates.
    pub const fn considered_routes(&self) -> usize {
        self.considered_routes
    }

    /// Returns number of skipped routes.
    pub const fn blocked_routes(&self) -> usize {
        self.blocked_routes
    }

    /// Returns allocations in selected order.
    pub fn allocations(&self) -> impl Iterator<Item = &SorChildAllocation> {
        self.allocations[..self.len]
            .iter()
            .filter_map(Option::as_ref)
    }

    fn push(&mut self, allocation: SorChildAllocation) -> Result<(), AlgoError> {
        if self.len == N {
            return Err(AlgoError::DecisionFull { capacity: N });
        }
        self.allocations[self.len] = Some(allocation);
        self.len += 1;
        Ok(())
    }

    fn mark_blocked(&mut self) {
        self.blocked_routes = self.blocked_routes.saturating_add(1);
    }
}

/// Deterministic smart-order-router planner.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SorPlanner {
    config: SorConfig,
}

impl SorPlanner {
    /// Creates a SOR planner.
    pub const fn new(config: SorConfig) -> Self {
        Self { config }
    }

    /// Returns planner configuration.
    pub const fn config(&self) -> SorConfig {
        self.config
    }

    /// Scores one route candidate for a parent order.
    ///
    /// Higher scores are preferred. Non-routable candidates return `None`.
    pub fn score_route(
        &self,
        parent: &ParentOrder,
        candidate: SorRouteCandidate,
        best_price: OrderPrice,
    ) -> Option<i64> {
        if !candidate.status().is_routable()
            || !candidate
                .capability()
                .supports_order_type(parent.order_type())
            || candidate.available_qty().0 <= 0
            || candidate.price().0 <= 0
        {
            return None;
        }
        let weights = self.config.weights();
        let liquidity_bps = route_liquidity_bps(candidate.available_qty().0, parent.max_clip().0);
        let price_penalty = route_price_penalty_bps(parent.side(), candidate.price(), best_price);
        let latency_penalty = candidate.metrics().latency_us() / 100;
        let fee_penalty =
            i64::from(candidate.metrics().fee_bps()) * i64::from(weights.fee_weight());

        let mut score = 0_i64;
        score = score.saturating_add(
            i64::from(candidate.metrics().fill_probability_bps())
                * i64::from(weights.fill_weight()),
        );
        score =
            score.saturating_add(i64::from(liquidity_bps) * i64::from(weights.liquidity_weight()));
        score = score.saturating_add(
            i64::from(candidate.metrics().data_quality_bps())
                * i64::from(weights.data_quality_weight()),
        );
        score = score.saturating_sub(i64::from(price_penalty) * i64::from(weights.price_weight()));
        score = score.saturating_sub(fee_penalty);
        score =
            score.saturating_sub(i64::from(latency_penalty) * i64::from(weights.latency_weight()));
        score = score.saturating_sub(
            i64::from(candidate.metrics().reject_rate_bps()) * i64::from(weights.reject_weight()),
        );
        score = score.saturating_sub(
            i64::from(candidate.metrics().toxicity_bps()) * i64::from(weights.toxicity_weight()),
        );
        Some(score)
    }

    /// Plans route allocations for one child-routing decision.
    ///
    /// `child_ids` and `client_order_ids` must contain at least `N` entries
    /// when the caller wants to allow `N` allocations. The planner never
    /// generates ids internally.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when parent/progress state is invalid, candidate
    /// data is invalid, capacity is exhausted, or not enough ids are supplied.
    #[allow(
        clippy::too_many_arguments,
        reason = "caller owns identifiers, timestamps, and route candidates"
    )]
    pub fn plan_routes<const N: usize>(
        &self,
        parent: &ParentOrder,
        progress: AlgoProgress,
        now_ns: u64,
        candidates: &[SorRouteCandidate],
        child_ids: &[ChildOrderId],
        client_order_ids: &[ClientOrderId],
        ts_recv_ns: u64,
    ) -> Result<SorDecision<N>, AlgoError> {
        parent.validate()?;
        if parent.status().is_terminal() {
            return Err(AlgoError::ParentTerminal);
        }
        if progress.parent_id() != parent.id() || progress.target_qty() != parent.total_qty() {
            return Err(AlgoError::InvalidProgress);
        }
        if child_ids.len() < N || client_order_ids.len() < N {
            return Err(AlgoError::InvalidSorParameters);
        }
        if now_ns < parent.start_ns() || progress.is_complete() || candidates.is_empty() {
            return Ok(SorDecision::new(candidates.len()));
        }

        let mut decision = SorDecision::<N>::new(candidates.len());
        let mut leaves = parent
            .total_qty()
            .0
            .saturating_sub(progress.released_qty().0)
            .min(parent.max_clip().0);
        let route_limit = self.config.max_route_count().min(N);
        let Some(best_price) = best_sor_price(parent.side(), candidates) else {
            return Ok(decision);
        };

        while leaves > 0 && decision.len() < route_limit {
            let mut best_index = None;
            let mut best_score = i64::MIN;
            for (index, candidate) in candidates.iter().copied().enumerate() {
                if decision_has_route(&decision, candidate.route_id()) {
                    continue;
                }
                let Some(score) = self.score_route(parent, candidate, best_price) else {
                    if decision.is_empty() {
                        decision.mark_blocked();
                    }
                    continue;
                };
                if score > best_score {
                    best_score = score;
                    best_index = Some(index);
                }
            }
            let Some(index) = best_index else {
                break;
            };
            let candidate = candidates[index];
            let qty = leaves.min(candidate.available_qty().0);
            let final_slice = progress.released_qty().0.saturating_add(qty) >= parent.total_qty().0
                || now_ns >= parent.end_ns();
            if qty < parent.min_clip().0 && !final_slice {
                break;
            }
            let request = parent.build_order_request_for_route_at_price(
                candidate.route_id(),
                client_order_ids[decision.len()],
                OrderQty(qty),
                candidate.price(),
                ts_recv_ns,
            );
            let plan =
                ChildOrderPlan::new(child_ids[decision.len()], parent.id(), request, now_ns)?;
            decision.push(SorChildAllocation {
                score: best_score,
                plan,
            })?;
            leaves = leaves.saturating_sub(qty);
        }

        Ok(decision)
    }
}

/// Liquidity-seeking action selected for one route.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LiquiditySeekingAction {
    /// Skip the route for this decision.
    Skip = 1,
    /// Send a small probe child order.
    Probe = 2,
    /// Send a larger liquidity-taking child order.
    Take = 3,
}

impl LiquiditySeekingAction {
    /// Returns true when this action releases a child order.
    pub const fn releases_child(self) -> bool {
        matches!(self, Self::Probe | Self::Take)
    }
}

/// Liquidity-seeking candidate derived from a routable venue.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LiquiditySeekingCandidate {
    route: SorRouteCandidate,
    hidden_liquidity_bps: u16,
    price_improvement_bps: u16,
    minimum_quantity: OrderQty,
}

impl LiquiditySeekingCandidate {
    /// Creates a liquidity-seeking route candidate.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidLiquiditySeekingParameters`] when bps
    /// fields exceed 10,000 or minimum quantity is negative.
    pub const fn new(
        route: SorRouteCandidate,
        hidden_liquidity_bps: u16,
        price_improvement_bps: u16,
        minimum_quantity: OrderQty,
    ) -> Result<Self, AlgoError> {
        if hidden_liquidity_bps > 10_000 || price_improvement_bps > 10_000 || minimum_quantity.0 < 0
        {
            return Err(AlgoError::InvalidLiquiditySeekingParameters);
        }
        Ok(Self {
            route,
            hidden_liquidity_bps,
            price_improvement_bps,
            minimum_quantity,
        })
    }

    /// Returns embedded SOR route candidate.
    pub const fn route(&self) -> SorRouteCandidate {
        self.route
    }

    /// Returns hidden-liquidity estimate in basis points.
    pub const fn hidden_liquidity_bps(&self) -> u16 {
        self.hidden_liquidity_bps
    }

    /// Returns price-improvement estimate in basis points.
    pub const fn price_improvement_bps(&self) -> u16 {
        self.price_improvement_bps
    }

    /// Returns minimum executable quantity requirement.
    pub const fn minimum_quantity(&self) -> OrderQty {
        self.minimum_quantity
    }
}

/// Configuration for liquidity-seeking route selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LiquiditySeekingConfig {
    max_routes: usize,
    probe_qty: OrderQty,
    min_score: i64,
    sweep_fill_probability_bps: u16,
    max_toxicity_bps: u16,
    hidden_liquidity_weight: u16,
    price_improvement_weight: u16,
}

impl LiquiditySeekingConfig {
    /// Creates liquidity-seeking configuration.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidLiquiditySeekingParameters`] when route
    /// count, quantity, or bps bounds are invalid.
    pub const fn new(
        max_routes: usize,
        probe_qty: OrderQty,
        min_score: i64,
        sweep_fill_probability_bps: u16,
        max_toxicity_bps: u16,
        hidden_liquidity_weight: u16,
        price_improvement_weight: u16,
    ) -> Result<Self, AlgoError> {
        if max_routes == 0
            || probe_qty.0 <= 0
            || sweep_fill_probability_bps > 10_000
            || max_toxicity_bps > 10_000
        {
            return Err(AlgoError::InvalidLiquiditySeekingParameters);
        }
        Ok(Self {
            max_routes,
            probe_qty,
            min_score,
            sweep_fill_probability_bps,
            max_toxicity_bps,
            hidden_liquidity_weight,
            price_improvement_weight,
        })
    }

    /// Returns maximum route allocations per decision.
    pub const fn max_routes(&self) -> usize {
        self.max_routes
    }

    /// Returns probe child quantity.
    pub const fn probe_qty(&self) -> OrderQty {
        self.probe_qty
    }

    /// Returns minimum score required for route selection.
    pub const fn min_score(&self) -> i64 {
        self.min_score
    }

    /// Returns fill-probability threshold for take/sweep behavior.
    pub const fn sweep_fill_probability_bps(&self) -> u16 {
        self.sweep_fill_probability_bps
    }

    /// Returns maximum tolerated venue toxicity.
    pub const fn max_toxicity_bps(&self) -> u16 {
        self.max_toxicity_bps
    }

    /// Returns hidden-liquidity score weight.
    pub const fn hidden_liquidity_weight(&self) -> u16 {
        self.hidden_liquidity_weight
    }

    /// Returns price-improvement score weight.
    pub const fn price_improvement_weight(&self) -> u16 {
        self.price_improvement_weight
    }
}

impl Default for LiquiditySeekingConfig {
    fn default() -> Self {
        Self {
            max_routes: 4,
            probe_qty: OrderQty(1),
            min_score: 0,
            sweep_fill_probability_bps: 7_500,
            max_toxicity_bps: 1_500,
            hidden_liquidity_weight: 3,
            price_improvement_weight: 4,
        }
    }
}

/// One liquidity-seeking allocation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LiquiditySeekingAllocation {
    action: LiquiditySeekingAction,
    score: i64,
    plan: ChildOrderPlan,
}

impl LiquiditySeekingAllocation {
    /// Returns selected action.
    pub const fn action(&self) -> LiquiditySeekingAction {
        self.action
    }

    /// Returns route score.
    pub const fn score(&self) -> i64 {
        self.score
    }

    /// Returns planned child order.
    pub const fn plan(&self) -> ChildOrderPlan {
        self.plan
    }
}

/// Fixed-capacity liquidity-seeking decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LiquiditySeekingDecision<const N: usize = DEFAULT_ALGO_DECISION_CAPACITY> {
    allocations: [Option<LiquiditySeekingAllocation>; N],
    len: usize,
    considered_routes: usize,
    skipped_routes: usize,
}

impl<const N: usize> LiquiditySeekingDecision<N> {
    /// Creates an empty liquidity-seeking decision.
    pub const fn new(considered_routes: usize) -> Self {
        Self {
            allocations: [None; N],
            len: 0,
            considered_routes,
            skipped_routes: 0,
        }
    }

    /// Returns allocation count.
    pub const fn len(&self) -> usize {
        self.len
    }

    /// Returns true when no allocations were produced.
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns number of route candidates considered.
    pub const fn considered_routes(&self) -> usize {
        self.considered_routes
    }

    /// Returns number of skipped route candidates.
    pub const fn skipped_routes(&self) -> usize {
        self.skipped_routes
    }

    /// Returns allocations in selected order.
    pub fn allocations(&self) -> impl Iterator<Item = &LiquiditySeekingAllocation> {
        self.allocations[..self.len]
            .iter()
            .filter_map(Option::as_ref)
    }

    fn push(&mut self, allocation: LiquiditySeekingAllocation) -> Result<(), AlgoError> {
        if self.len == N {
            return Err(AlgoError::DecisionFull { capacity: N });
        }
        self.allocations[self.len] = Some(allocation);
        self.len += 1;
        Ok(())
    }

    fn mark_skipped(&mut self) {
        self.skipped_routes = self.skipped_routes.saturating_add(1);
    }
}

/// Deterministic liquidity-seeking planner.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LiquiditySeekingPlanner {
    config: LiquiditySeekingConfig,
    sor: SorPlanner,
}

impl LiquiditySeekingPlanner {
    /// Creates a liquidity-seeking planner.
    pub const fn new(config: LiquiditySeekingConfig, sor_config: SorConfig) -> Self {
        Self {
            config,
            sor: SorPlanner::new(sor_config),
        }
    }

    /// Returns planner configuration.
    pub const fn config(&self) -> LiquiditySeekingConfig {
        self.config
    }

    /// Scores one liquidity-seeking candidate.
    pub fn score_candidate(
        &self,
        parent: &ParentOrder,
        candidate: LiquiditySeekingCandidate,
        best_price: OrderPrice,
    ) -> Option<i64> {
        if candidate.route().metrics().toxicity_bps() > self.config.max_toxicity_bps()
            || candidate.route().available_qty().0 < candidate.minimum_quantity().0
        {
            return None;
        }
        let mut score = self
            .sor
            .score_route(parent, candidate.route(), best_price)?;
        score = score.saturating_add(
            i64::from(candidate.hidden_liquidity_bps())
                * i64::from(self.config.hidden_liquidity_weight()),
        );
        score = score.saturating_add(
            i64::from(candidate.price_improvement_bps())
                * i64::from(self.config.price_improvement_weight()),
        );
        Some(score)
    }

    /// Plans route probes or larger liquidity-taking child orders.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when parent/progress/id slices are invalid, a
    /// generated child order is invalid, or fixed output capacity is exhausted.
    #[allow(
        clippy::too_many_arguments,
        reason = "caller owns route candidates, ids, and timestamps"
    )]
    pub fn plan_liquidity<const N: usize>(
        &self,
        parent: &ParentOrder,
        progress: AlgoProgress,
        now_ns: u64,
        candidates: &[LiquiditySeekingCandidate],
        child_ids: &[ChildOrderId],
        client_order_ids: &[ClientOrderId],
        ts_recv_ns: u64,
    ) -> Result<LiquiditySeekingDecision<N>, AlgoError> {
        parent.validate()?;
        if parent.status().is_terminal() {
            return Err(AlgoError::ParentTerminal);
        }
        if progress.parent_id() != parent.id() || progress.target_qty() != parent.total_qty() {
            return Err(AlgoError::InvalidProgress);
        }
        if child_ids.len() < N || client_order_ids.len() < N {
            return Err(AlgoError::InvalidLiquiditySeekingParameters);
        }
        if now_ns < parent.start_ns() || progress.is_complete() || candidates.is_empty() {
            return Ok(LiquiditySeekingDecision::new(candidates.len()));
        }

        let mut decision = LiquiditySeekingDecision::<N>::new(candidates.len());
        let mut leaves = parent
            .total_qty()
            .0
            .saturating_sub(progress.released_qty().0)
            .min(parent.max_clip().0);
        let route_limit = self.config.max_routes().min(N);
        let Some(best_price) = best_liquidity_price(parent.side(), candidates) else {
            return Ok(decision);
        };

        while leaves > 0 && decision.len() < route_limit {
            let mut best_index = None;
            let mut best_score = i64::MIN;
            for (index, candidate) in candidates.iter().copied().enumerate() {
                if liquidity_decision_has_route(&decision, candidate.route().route_id()) {
                    continue;
                }
                let Some(score) = self.score_candidate(parent, candidate, best_price) else {
                    if decision.is_empty() {
                        decision.mark_skipped();
                    }
                    continue;
                };
                if score >= self.config.min_score() && score > best_score {
                    best_score = score;
                    best_index = Some(index);
                }
            }
            let Some(index) = best_index else {
                break;
            };
            if decision.len() == N {
                return Err(AlgoError::DecisionFull { capacity: N });
            }
            let candidate = candidates[index];
            let action = if candidate.route().metrics().fill_probability_bps()
                >= self.config.sweep_fill_probability_bps()
            {
                LiquiditySeekingAction::Take
            } else {
                LiquiditySeekingAction::Probe
            };
            let desired_qty = match action {
                LiquiditySeekingAction::Take => candidate.route().available_qty().0,
                LiquiditySeekingAction::Probe => self.config.probe_qty().0,
                LiquiditySeekingAction::Skip => 0,
            };
            let qty = desired_qty
                .min(candidate.route().available_qty().0)
                .min(leaves);
            let final_slice = progress.released_qty().0.saturating_add(qty) >= parent.total_qty().0
                || now_ns >= parent.end_ns();
            if qty < parent.min_clip().0 && !final_slice {
                decision.mark_skipped();
                break;
            }
            if qty <= 0 {
                break;
            }
            let request = parent.build_order_request_for_route_at_price(
                candidate.route().route_id(),
                client_order_ids[decision.len()],
                OrderQty(qty),
                candidate.route().price(),
                ts_recv_ns,
            );
            let plan =
                ChildOrderPlan::new(child_ids[decision.len()], parent.id(), request, now_ns)?;
            decision.push(LiquiditySeekingAllocation {
                action,
                score: best_score,
                plan,
            })?;
            leaves = leaves.saturating_sub(qty);
        }

        Ok(decision)
    }
}

/// Aggressive sweep configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SweepConfig {
    max_routes: usize,
    price_collar: OrderPrice,
    min_fill_qty: OrderQty,
}

impl SweepConfig {
    /// Creates sweep configuration.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidSweepParameters`] when route count, collar,
    /// or minimum fill quantity is invalid.
    pub const fn new(
        max_routes: usize,
        price_collar: OrderPrice,
        min_fill_qty: OrderQty,
    ) -> Result<Self, AlgoError> {
        if max_routes == 0 || price_collar.0 <= 0 || min_fill_qty.0 < 0 {
            return Err(AlgoError::InvalidSweepParameters);
        }
        Ok(Self {
            max_routes,
            price_collar,
            min_fill_qty,
        })
    }

    /// Returns maximum route/level allocations per decision.
    pub const fn max_routes(&self) -> usize {
        self.max_routes
    }

    /// Returns side-aware price collar.
    pub const fn price_collar(&self) -> OrderPrice {
        self.price_collar
    }

    /// Returns minimum total fill quantity required for a non-empty decision.
    pub const fn min_fill_qty(&self) -> OrderQty {
        self.min_fill_qty
    }
}

/// One aggressive sweep allocation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SweepAllocation {
    plan: ChildOrderPlan,
}

impl SweepAllocation {
    /// Returns planned child order for this sweep level.
    pub const fn plan(&self) -> ChildOrderPlan {
        self.plan
    }
}

/// Fixed-capacity aggressive sweep decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SweepDecision<const N: usize = DEFAULT_ALGO_DECISION_CAPACITY> {
    allocations: [Option<SweepAllocation>; N],
    len: usize,
    considered_levels: usize,
    skipped_levels: usize,
    total_qty: OrderQty,
    average_price: OrderPrice,
    collar_reached: bool,
}

impl<const N: usize> SweepDecision<N> {
    /// Creates an empty sweep decision.
    pub const fn new(considered_levels: usize) -> Self {
        Self {
            allocations: [None; N],
            len: 0,
            considered_levels,
            skipped_levels: 0,
            total_qty: OrderQty(0),
            average_price: OrderPrice(0),
            collar_reached: false,
        }
    }

    /// Returns allocation count.
    pub const fn len(&self) -> usize {
        self.len
    }

    /// Returns true when no allocations were produced.
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns considered book/route levels.
    pub const fn considered_levels(&self) -> usize {
        self.considered_levels
    }

    /// Returns skipped book/route levels.
    pub const fn skipped_levels(&self) -> usize {
        self.skipped_levels
    }

    /// Returns total planned sweep quantity.
    pub const fn total_qty(&self) -> OrderQty {
        self.total_qty
    }

    /// Returns average planned sweep price.
    pub const fn average_price(&self) -> OrderPrice {
        self.average_price
    }

    /// Returns true when at least one candidate was outside the price collar.
    pub const fn collar_reached(&self) -> bool {
        self.collar_reached
    }

    /// Returns allocations in selected order.
    pub fn allocations(&self) -> impl Iterator<Item = &SweepAllocation> {
        self.allocations[..self.len]
            .iter()
            .filter_map(Option::as_ref)
    }

    fn push(&mut self, allocation: SweepAllocation) -> Result<(), AlgoError> {
        if self.len == N {
            return Err(AlgoError::DecisionFull { capacity: N });
        }
        let qty = allocation.plan().request().quantity.0;
        let price = allocation.plan().request().limit_price.0;
        let previous_notional = i128::from(self.average_price.0) * i128::from(self.total_qty.0);
        let new_notional = previous_notional.saturating_add(i128::from(price) * i128::from(qty));
        self.total_qty = OrderQty(self.total_qty.0.saturating_add(qty));
        if self.total_qty.0 > 0 {
            self.average_price = OrderPrice(
                i64::try_from(new_notional / i128::from(self.total_qty.0)).unwrap_or(i64::MAX),
            );
        }
        self.allocations[self.len] = Some(allocation);
        self.len += 1;
        Ok(())
    }

    fn mark_skipped(&mut self) {
        self.skipped_levels = self.skipped_levels.saturating_add(1);
    }

    fn mark_collar_reached(&mut self) {
        self.collar_reached = true;
    }
}

/// Deterministic aggressive sweep planner.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SweepPlanner {
    config: SweepConfig,
}

impl SweepPlanner {
    /// Creates a sweep planner.
    pub const fn new(config: SweepConfig) -> Self {
        Self { config }
    }

    /// Returns planner configuration.
    pub const fn config(&self) -> SweepConfig {
        self.config
    }

    /// Plans aggressive route/level child orders up to the price collar.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when parent/progress/id slices are invalid, a
    /// generated child order is invalid, or fixed output capacity is exhausted.
    #[allow(
        clippy::too_many_arguments,
        reason = "caller owns route candidates, ids, and timestamps"
    )]
    pub fn plan_sweep<const N: usize>(
        &self,
        parent: &ParentOrder,
        progress: AlgoProgress,
        now_ns: u64,
        candidates: &[SorRouteCandidate],
        child_ids: &[ChildOrderId],
        client_order_ids: &[ClientOrderId],
        ts_recv_ns: u64,
    ) -> Result<SweepDecision<N>, AlgoError> {
        parent.validate()?;
        if parent.status().is_terminal() {
            return Err(AlgoError::ParentTerminal);
        }
        if progress.parent_id() != parent.id() || progress.target_qty() != parent.total_qty() {
            return Err(AlgoError::InvalidProgress);
        }
        if child_ids.len() < N || client_order_ids.len() < N {
            return Err(AlgoError::InvalidSweepParameters);
        }
        if now_ns < parent.start_ns() || progress.is_complete() || candidates.is_empty() {
            return Ok(SweepDecision::new(candidates.len()));
        }

        let mut decision = SweepDecision::<N>::new(candidates.len());
        let mut leaves = parent
            .total_qty()
            .0
            .saturating_sub(progress.released_qty().0)
            .min(parent.max_clip().0);
        let route_limit = self.config.max_routes().min(N);

        while leaves > 0 && decision.len() < route_limit {
            let mut best_index = None;
            let mut best_price = match parent.side() {
                OrderSide::Buy => OrderPrice(i64::MAX),
                OrderSide::Sell => OrderPrice(0),
            };
            for (index, candidate) in candidates.iter().copied().enumerate() {
                if sweep_decision_has_level(&decision, candidate.route_id(), candidate.price()) {
                    continue;
                }
                if !candidate.status().is_routable()
                    || !candidate
                        .capability()
                        .supports_order_type(parent.order_type())
                    || candidate.available_qty().0 <= 0
                    || candidate.price().0 <= 0
                {
                    decision.mark_skipped();
                    continue;
                }
                if !price_inside_collar(
                    parent.side(),
                    candidate.price(),
                    self.config.price_collar(),
                ) {
                    decision.mark_collar_reached();
                    continue;
                }
                let better = match parent.side() {
                    OrderSide::Buy => candidate.price().0 < best_price.0,
                    OrderSide::Sell => candidate.price().0 > best_price.0,
                };
                if better {
                    best_price = candidate.price();
                    best_index = Some(index);
                }
            }
            let Some(index) = best_index else {
                break;
            };
            if decision.len() == N {
                return Err(AlgoError::DecisionFull { capacity: N });
            }
            let candidate = candidates[index];
            let qty = candidate.available_qty().0.min(leaves);
            if qty <= 0 {
                break;
            }
            let request = parent.build_order_request_for_route_at_price(
                candidate.route_id(),
                client_order_ids[decision.len()],
                OrderQty(qty),
                candidate.price(),
                ts_recv_ns,
            );
            let plan =
                ChildOrderPlan::new(child_ids[decision.len()], parent.id(), request, now_ns)?;
            decision.push(SweepAllocation { plan })?;
            leaves = leaves.saturating_sub(qty);
        }

        if decision.total_qty().0 < self.config.min_fill_qty().0 {
            return Ok(SweepDecision::new(candidates.len()));
        }
        Ok(decision)
    }
}

/// Basket or spread leg side in the portfolio objective.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BasketLegRole {
    /// Primary alpha or exposure leg.
    Primary = 1,
    /// Hedge leg intended to reduce exposure drift.
    Hedge = 2,
    /// Offset leg in a spread or relative-value structure.
    Offset = 3,
}

/// One parent order participating in a basket or spread execution.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BasketLeg {
    parent: ParentOrder,
    role: BasketLegRole,
    hedge_ratio_bps: i32,
}

impl BasketLeg {
    /// Creates a basket leg.
    ///
    /// `hedge_ratio_bps` is metadata for audit and host-side risk checks. The
    /// first planner slice uses each leg's own parent quantity as the executable
    /// target so existing single-leg OMS semantics remain unchanged.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when the parent is invalid or hedge ratio is zero.
    pub fn new(
        parent: ParentOrder,
        role: BasketLegRole,
        hedge_ratio_bps: i32,
    ) -> Result<Self, AlgoError> {
        parent.validate()?;
        if hedge_ratio_bps == 0 {
            return Err(AlgoError::InvalidBasketParameters);
        }
        Ok(Self {
            parent,
            role,
            hedge_ratio_bps,
        })
    }

    /// Returns the leg parent order.
    pub const fn parent(&self) -> ParentOrder {
        self.parent
    }

    /// Returns leg role.
    pub const fn role(&self) -> BasketLegRole {
        self.role
    }

    /// Returns hedge ratio metadata in basis points.
    pub const fn hedge_ratio_bps(&self) -> i32 {
        self.hedge_ratio_bps
    }
}

/// Planned child allocation for one basket leg.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BasketChildAllocation {
    leg_index: usize,
    role: BasketLegRole,
    target_release_qty: OrderQty,
    plan: ChildOrderPlan,
}

impl BasketChildAllocation {
    /// Returns leg index from the caller-provided leg slice.
    pub const fn leg_index(&self) -> usize {
        self.leg_index
    }

    /// Returns leg role.
    pub const fn role(&self) -> BasketLegRole {
        self.role
    }

    /// Returns cumulative target release quantity for the leg.
    pub const fn target_release_qty(&self) -> OrderQty {
        self.target_release_qty
    }

    /// Returns planned child order.
    pub const fn plan(&self) -> ChildOrderPlan {
        self.plan
    }
}

/// Fixed-capacity basket decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BasketDecision<const N: usize = DEFAULT_ALGO_DECISION_CAPACITY> {
    allocations: [Option<BasketChildAllocation>; N],
    len: usize,
    considered_legs: usize,
    blocked_legs: usize,
}

impl<const N: usize> BasketDecision<N> {
    /// Creates an empty basket decision.
    pub const fn new(considered_legs: usize) -> Self {
        Self {
            allocations: [None; N],
            len: 0,
            considered_legs,
            blocked_legs: 0,
        }
    }

    /// Returns allocation count.
    pub const fn len(&self) -> usize {
        self.len
    }

    /// Returns true when no allocations were produced.
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns considered leg count.
    pub const fn considered_legs(&self) -> usize {
        self.considered_legs
    }

    /// Returns blocked leg count.
    pub const fn blocked_legs(&self) -> usize {
        self.blocked_legs
    }

    /// Returns allocations in leg order.
    pub fn allocations(&self) -> impl Iterator<Item = &BasketChildAllocation> {
        self.allocations[..self.len]
            .iter()
            .filter_map(Option::as_ref)
    }

    fn push(&mut self, allocation: BasketChildAllocation) -> Result<(), AlgoError> {
        if self.len == N {
            return Err(AlgoError::DecisionFull { capacity: N });
        }
        self.allocations[self.len] = Some(allocation);
        self.len += 1;
        Ok(())
    }

    fn mark_blocked(&mut self) {
        self.blocked_legs = self.blocked_legs.saturating_add(1);
    }
}

/// Deterministic synchronized basket/spread planner.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct BasketPlanner;

impl BasketPlanner {
    /// Creates a basket planner.
    pub const fn new() -> Self {
        Self
    }

    /// Plans synchronized child slices for a basket.
    ///
    /// Each leg uses its own parent schedule and clip bounds. The function
    /// emits at most one child per due leg and writes allocations into a
    /// fixed-capacity decision. Hosts remain responsible for atomic package
    /// semantics, linked-order support, hedge drift monitoring, and venue
    /// cancel/replace orchestration.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when leg/progress/id slices are inconsistent, a
    /// parent/progress pair is invalid, or the fixed output capacity is full.
    pub fn plan_synchronized_slice<const N: usize>(
        &self,
        legs: &[BasketLeg],
        progresses: &[AlgoProgress],
        now_ns: u64,
        child_ids: &[ChildOrderId],
        client_order_ids: &[ClientOrderId],
        ts_recv_ns: u64,
    ) -> Result<BasketDecision<N>, AlgoError> {
        if legs.len() != progresses.len()
            || child_ids.len() < legs.len().min(N)
            || client_order_ids.len() < legs.len().min(N)
        {
            return Err(AlgoError::InvalidBasketParameters);
        }

        let mut decision = BasketDecision::<N>::new(legs.len());
        for (index, (leg, progress)) in legs.iter().zip(progresses.iter()).enumerate() {
            let parent = leg.parent();
            parent.validate()?;
            if parent.status().is_terminal() {
                decision.mark_blocked();
                continue;
            }
            if progress.parent_id() != parent.id() || progress.target_qty() != parent.total_qty() {
                return Err(AlgoError::InvalidProgress);
            }
            if now_ns < parent.start_ns() || progress.is_complete() {
                continue;
            }
            let target_release_qty = scale_qty_bps(
                parent.total_qty().0,
                u32::from(elapsed_bps(parent.start_ns(), parent.end_ns(), now_ns)),
            );
            let due_qty = target_release_qty.saturating_sub(progress.released_qty().0);
            if due_qty <= 0 {
                continue;
            }
            let leaves = parent
                .total_qty()
                .0
                .saturating_sub(progress.released_qty().0);
            let mut child_qty = due_qty.min(parent.max_clip().0).min(leaves);
            let final_slice = progress.released_qty().0.saturating_add(child_qty)
                >= parent.total_qty().0
                || now_ns >= parent.end_ns();
            if child_qty < parent.min_clip().0 && !final_slice {
                continue;
            }
            if child_qty <= 0 {
                continue;
            }
            child_qty = child_qty.min(leaves);
            if decision.len() == N {
                return Err(AlgoError::DecisionFull { capacity: N });
            }
            let request = parent.build_order_request(
                client_order_ids[decision.len()],
                OrderQty(child_qty),
                ts_recv_ns,
            );
            let plan =
                ChildOrderPlan::new(child_ids[decision.len()], parent.id(), request, now_ns)?;
            decision.push(BasketChildAllocation {
                leg_index: index,
                role: leg.role(),
                target_release_qty: OrderQty(target_release_qty),
                plan,
            })?;
        }
        Ok(decision)
    }
}

/// Two-leg spread execution configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SpreadConfig {
    ratio_bps: u32,
    min_edge_bps: i32,
}

impl SpreadConfig {
    /// Creates spread configuration.
    ///
    /// `ratio_bps` scales the sell leg price and quantity relative to the buy
    /// leg. A value of 10,000 means one-to-one.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidSpreadParameters`] when ratio is zero.
    pub const fn new(ratio_bps: u32, min_edge_bps: i32) -> Result<Self, AlgoError> {
        if ratio_bps == 0 {
            return Err(AlgoError::InvalidSpreadParameters);
        }
        Ok(Self {
            ratio_bps,
            min_edge_bps,
        })
    }

    /// Returns sell-leg ratio in basis points.
    pub const fn ratio_bps(&self) -> u32 {
        self.ratio_bps
    }

    /// Returns minimum required spread edge in basis points.
    pub const fn min_edge_bps(&self) -> i32 {
        self.min_edge_bps
    }
}

/// Current executable two-leg spread prices.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SpreadQuote {
    buy_price: OrderPrice,
    sell_price: OrderPrice,
}

impl SpreadQuote {
    /// Creates spread quote prices.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidSpreadParameters`] when either price is not
    /// positive.
    pub const fn new(buy_price: OrderPrice, sell_price: OrderPrice) -> Result<Self, AlgoError> {
        if buy_price.0 <= 0 || sell_price.0 <= 0 {
            return Err(AlgoError::InvalidSpreadParameters);
        }
        Ok(Self {
            buy_price,
            sell_price,
        })
    }

    /// Returns executable buy-leg price.
    pub const fn buy_price(&self) -> OrderPrice {
        self.buy_price
    }

    /// Returns executable sell-leg price.
    pub const fn sell_price(&self) -> OrderPrice {
        self.sell_price
    }
}

/// Spread estimate used by [`SpreadPlanner`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SpreadEstimate {
    edge_bps: i32,
    executable: bool,
    buy_qty: OrderQty,
    sell_qty: OrderQty,
}

impl SpreadEstimate {
    /// Returns current spread edge in basis points.
    pub const fn edge_bps(&self) -> i32 {
        self.edge_bps
    }

    /// Returns true when edge meets the configured threshold.
    pub const fn executable(&self) -> bool {
        self.executable
    }

    /// Returns planned buy-leg quantity.
    pub const fn buy_qty(&self) -> OrderQty {
        self.buy_qty
    }

    /// Returns planned sell-leg quantity.
    pub const fn sell_qty(&self) -> OrderQty {
        self.sell_qty
    }
}

/// Two-leg spread decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SpreadDecision {
    estimate: SpreadEstimate,
    buy: Option<ChildOrderPlan>,
    sell: Option<ChildOrderPlan>,
}

impl SpreadDecision {
    /// Returns estimate used by the decision.
    pub const fn estimate(&self) -> SpreadEstimate {
        self.estimate
    }

    /// Returns optional buy-leg child order.
    pub const fn buy(&self) -> Option<ChildOrderPlan> {
        self.buy
    }

    /// Returns optional sell-leg child order.
    pub const fn sell(&self) -> Option<ChildOrderPlan> {
        self.sell
    }
}

/// Deterministic two-leg pairs/spread planner.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SpreadPlanner {
    config: SpreadConfig,
}

impl SpreadPlanner {
    /// Creates a spread planner.
    pub const fn new(config: SpreadConfig) -> Self {
        Self { config }
    }

    /// Returns planner configuration.
    pub const fn config(&self) -> SpreadConfig {
        self.config
    }

    /// Estimates edge and executable leg quantities.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when leg, progress, or quote inputs are invalid.
    pub fn estimate(
        &self,
        buy_parent: &ParentOrder,
        buy_progress: AlgoProgress,
        sell_parent: &ParentOrder,
        sell_progress: AlgoProgress,
        quote: SpreadQuote,
    ) -> Result<SpreadEstimate, AlgoError> {
        self.validate_legs(buy_parent, buy_progress, sell_parent, sell_progress)?;
        let edge_bps = spread_edge_bps(
            quote.buy_price(),
            quote.sell_price(),
            self.config.ratio_bps(),
        );
        let executable = edge_bps >= self.config.min_edge_bps();
        let buy_leaves = buy_parent
            .total_qty()
            .0
            .saturating_sub(buy_progress.released_qty().0)
            .min(buy_parent.max_clip().0);
        let sell_leaves = sell_parent
            .total_qty()
            .0
            .saturating_sub(sell_progress.released_qty().0)
            .min(sell_parent.max_clip().0);
        let buy_from_sell = scale_qty_inverse_bps(sell_leaves, self.config.ratio_bps());
        let buy_qty = buy_leaves.min(buy_from_sell);
        let sell_qty = scale_qty_bps(buy_qty, self.config.ratio_bps());
        Ok(SpreadEstimate {
            edge_bps,
            executable,
            buy_qty: OrderQty(buy_qty),
            sell_qty: OrderQty(sell_qty.min(sell_leaves)),
        })
    }

    /// Plans synchronized buy/sell spread child orders.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when inputs are invalid or generated child orders
    /// fail OMS request validation.
    #[allow(
        clippy::too_many_arguments,
        reason = "caller owns both legs, ids, quotes, and timestamps"
    )]
    pub fn plan_spread(
        &self,
        buy_parent: &ParentOrder,
        buy_progress: AlgoProgress,
        sell_parent: &ParentOrder,
        sell_progress: AlgoProgress,
        now_ns: u64,
        quote: SpreadQuote,
        buy_child_id: ChildOrderId,
        buy_client_order_id: ClientOrderId,
        sell_child_id: ChildOrderId,
        sell_client_order_id: ClientOrderId,
        ts_recv_ns: u64,
    ) -> Result<SpreadDecision, AlgoError> {
        if now_ns < buy_parent.start_ns().max(sell_parent.start_ns())
            || buy_progress.is_complete()
            || sell_progress.is_complete()
        {
            let estimate =
                self.estimate(buy_parent, buy_progress, sell_parent, sell_progress, quote)?;
            return Ok(SpreadDecision {
                estimate: SpreadEstimate {
                    executable: false,
                    ..estimate
                },
                buy: None,
                sell: None,
            });
        }
        let estimate =
            self.estimate(buy_parent, buy_progress, sell_parent, sell_progress, quote)?;
        if !estimate.executable()
            || estimate.buy_qty().0 < buy_parent.min_clip().0
            || estimate.sell_qty().0 < sell_parent.min_clip().0
        {
            return Ok(SpreadDecision {
                estimate,
                buy: None,
                sell: None,
            });
        }
        let buy_request = buy_parent.build_order_request_for_side_at_price(
            OrderSide::Buy,
            buy_client_order_id,
            estimate.buy_qty(),
            quote.buy_price(),
            ts_recv_ns,
        );
        let sell_request = sell_parent.build_order_request_for_side_at_price(
            OrderSide::Sell,
            sell_client_order_id,
            estimate.sell_qty(),
            quote.sell_price(),
            ts_recv_ns,
        );
        Ok(SpreadDecision {
            estimate,
            buy: Some(ChildOrderPlan::new(
                buy_child_id,
                buy_parent.id(),
                buy_request,
                now_ns,
            )?),
            sell: Some(ChildOrderPlan::new(
                sell_child_id,
                sell_parent.id(),
                sell_request,
                now_ns,
            )?),
        })
    }

    fn validate_legs(
        &self,
        buy_parent: &ParentOrder,
        buy_progress: AlgoProgress,
        sell_parent: &ParentOrder,
        sell_progress: AlgoProgress,
    ) -> Result<(), AlgoError> {
        buy_parent.validate()?;
        sell_parent.validate()?;
        if buy_parent.status().is_terminal() || sell_parent.status().is_terminal() {
            return Err(AlgoError::ParentTerminal);
        }
        if buy_parent.side() != OrderSide::Buy || sell_parent.side() != OrderSide::Sell {
            return Err(AlgoError::InvalidSpreadParameters);
        }
        if buy_progress.parent_id() != buy_parent.id()
            || buy_progress.target_qty() != buy_parent.total_qty()
            || sell_progress.parent_id() != sell_parent.id()
            || sell_progress.target_qty() != sell_parent.total_qty()
        {
            return Err(AlgoError::InvalidProgress);
        }
        Ok(())
    }
}

/// Market-making context supplied by the host quote model.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MarketMakerContext {
    fair_value: OrderPrice,
    best_bid: OrderPrice,
    best_ask: OrderPrice,
    inventory_qty: OrderQty,
    max_inventory_qty: OrderQty,
    volatility_bps: u16,
    adverse_selection_bps: u16,
}

impl MarketMakerContext {
    /// Creates market-making quote context.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidMarketMakingParameters`] when prices are
    /// non-positive/crossed or maximum inventory is not positive.
    #[allow(
        clippy::too_many_arguments,
        reason = "flat context mirrors one hot-path quote snapshot"
    )]
    pub const fn new(
        fair_value: OrderPrice,
        best_bid: OrderPrice,
        best_ask: OrderPrice,
        inventory_qty: OrderQty,
        max_inventory_qty: OrderQty,
        volatility_bps: u16,
        adverse_selection_bps: u16,
    ) -> Result<Self, AlgoError> {
        if fair_value.0 <= 0
            || best_bid.0 <= 0
            || best_ask.0 <= 0
            || best_bid.0 >= best_ask.0
            || max_inventory_qty.0 <= 0
        {
            return Err(AlgoError::InvalidMarketMakingParameters);
        }
        Ok(Self {
            fair_value,
            best_bid,
            best_ask,
            inventory_qty,
            max_inventory_qty,
            volatility_bps,
            adverse_selection_bps,
        })
    }

    /// Returns model fair value.
    pub const fn fair_value(&self) -> OrderPrice {
        self.fair_value
    }

    /// Returns current best bid.
    pub const fn best_bid(&self) -> OrderPrice {
        self.best_bid
    }

    /// Returns current best ask.
    pub const fn best_ask(&self) -> OrderPrice {
        self.best_ask
    }

    /// Returns signed inventory quantity.
    pub const fn inventory_qty(&self) -> OrderQty {
        self.inventory_qty
    }

    /// Returns absolute maximum inventory quantity.
    pub const fn max_inventory_qty(&self) -> OrderQty {
        self.max_inventory_qty
    }

    /// Returns volatility estimate in basis points.
    pub const fn volatility_bps(&self) -> u16 {
        self.volatility_bps
    }

    /// Returns adverse-selection estimate in basis points.
    pub const fn adverse_selection_bps(&self) -> u16 {
        self.adverse_selection_bps
    }
}

/// Market-making quote configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MarketMakerConfig {
    tick_size: OrderPrice,
    quote_qty: OrderQty,
    base_spread_bps: u16,
    min_spread_ticks: u16,
    max_spread_bps: u16,
    inventory_skew_bps: u16,
    volatility_weight_bps: u16,
    adverse_selection_weight_bps: u16,
}

impl MarketMakerConfig {
    /// Creates market-making configuration.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidMarketMakingParameters`] when tick size,
    /// quote quantity, or spread bounds are invalid.
    #[allow(
        clippy::too_many_arguments,
        reason = "flat constructor keeps quote controls explicit"
    )]
    pub const fn new(
        tick_size: OrderPrice,
        quote_qty: OrderQty,
        base_spread_bps: u16,
        min_spread_ticks: u16,
        max_spread_bps: u16,
        inventory_skew_bps: u16,
        volatility_weight_bps: u16,
        adverse_selection_weight_bps: u16,
    ) -> Result<Self, AlgoError> {
        if tick_size.0 <= 0
            || quote_qty.0 <= 0
            || min_spread_ticks == 0
            || base_spread_bps > 10_000
            || max_spread_bps > 10_000
            || base_spread_bps > max_spread_bps
        {
            return Err(AlgoError::InvalidMarketMakingParameters);
        }
        Ok(Self {
            tick_size,
            quote_qty,
            base_spread_bps,
            min_spread_ticks,
            max_spread_bps,
            inventory_skew_bps,
            volatility_weight_bps,
            adverse_selection_weight_bps,
        })
    }

    /// Returns tick size in normalized price units.
    pub const fn tick_size(&self) -> OrderPrice {
        self.tick_size
    }

    /// Returns quote quantity.
    pub const fn quote_qty(&self) -> OrderQty {
        self.quote_qty
    }

    /// Returns base spread in basis points.
    pub const fn base_spread_bps(&self) -> u16 {
        self.base_spread_bps
    }

    /// Returns minimum spread in ticks.
    pub const fn min_spread_ticks(&self) -> u16 {
        self.min_spread_ticks
    }

    /// Returns maximum spread in basis points.
    pub const fn max_spread_bps(&self) -> u16 {
        self.max_spread_bps
    }

    /// Returns inventory skew strength in basis points.
    pub const fn inventory_skew_bps(&self) -> u16 {
        self.inventory_skew_bps
    }

    /// Returns volatility spread weight in basis points.
    pub const fn volatility_weight_bps(&self) -> u16 {
        self.volatility_weight_bps
    }

    /// Returns adverse-selection spread weight in basis points.
    pub const fn adverse_selection_weight_bps(&self) -> u16 {
        self.adverse_selection_weight_bps
    }
}

impl Default for MarketMakerConfig {
    fn default() -> Self {
        Self::new(
            OrderPrice(1),
            OrderQty(1),
            10,
            1,
            1_000,
            1_000,
            5_000,
            5_000,
        )
        .expect("static market-making defaults are valid")
    }
}

/// Market-making quote estimate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MarketMakerQuoteEstimate {
    adjusted_fair_value: OrderPrice,
    bid_price: OrderPrice,
    ask_price: OrderPrice,
    spread_bps: u16,
    quote_bid: bool,
    quote_ask: bool,
}

impl MarketMakerQuoteEstimate {
    /// Returns inventory-skewed fair value.
    pub const fn adjusted_fair_value(&self) -> OrderPrice {
        self.adjusted_fair_value
    }

    /// Returns bid quote price.
    pub const fn bid_price(&self) -> OrderPrice {
        self.bid_price
    }

    /// Returns ask quote price.
    pub const fn ask_price(&self) -> OrderPrice {
        self.ask_price
    }

    /// Returns selected spread in basis points.
    pub const fn spread_bps(&self) -> u16 {
        self.spread_bps
    }

    /// Returns true when a bid quote is allowed.
    pub const fn quote_bid(&self) -> bool {
        self.quote_bid
    }

    /// Returns true when an ask quote is allowed.
    pub const fn quote_ask(&self) -> bool {
        self.quote_ask
    }
}

/// Market-making quote decision.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MarketMakerQuoteDecision {
    estimate: MarketMakerQuoteEstimate,
    bid: Option<ChildOrderPlan>,
    ask: Option<ChildOrderPlan>,
}

impl MarketMakerQuoteDecision {
    /// Returns the quote estimate.
    pub const fn estimate(&self) -> MarketMakerQuoteEstimate {
        self.estimate
    }

    /// Returns optional bid child order plan.
    pub const fn bid(&self) -> Option<ChildOrderPlan> {
        self.bid
    }

    /// Returns optional ask child order plan.
    pub const fn ask(&self) -> Option<ChildOrderPlan> {
        self.ask
    }
}

/// Deterministic market-making quote planner.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MarketMakerPlanner {
    config: MarketMakerConfig,
}

impl MarketMakerPlanner {
    /// Creates a market-making planner.
    pub const fn new(config: MarketMakerConfig) -> Self {
        Self { config }
    }

    /// Returns planner configuration.
    pub const fn config(&self) -> MarketMakerConfig {
        self.config
    }

    /// Estimates bid/ask quote prices and inventory-side quote suppression.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when template or context is invalid.
    pub fn estimate(
        &self,
        template: &ParentOrder,
        context: MarketMakerContext,
    ) -> Result<MarketMakerQuoteEstimate, AlgoError> {
        template.validate()?;
        self.validate_context(context)?;
        let inventory_ratio_bps =
            signed_inventory_ratio_bps(context.inventory_qty().0, context.max_inventory_qty().0);
        let skew_bps = scale_signed_bps(
            inventory_ratio_bps,
            i32::from(self.config.inventory_skew_bps()),
        );
        let adjusted_fair_value = apply_price_bps(context.fair_value(), -skew_bps);

        let mut spread_bps = self.config.base_spread_bps();
        spread_bps = spread_bps.saturating_add(
            u16::try_from(scale_bps_u32(
                u32::from(context.volatility_bps()),
                u32::from(self.config.volatility_weight_bps()),
            ))
            .unwrap_or(u16::MAX),
        );
        spread_bps = spread_bps.saturating_add(
            u16::try_from(scale_bps_u32(
                u32::from(context.adverse_selection_bps()),
                u32::from(self.config.adverse_selection_weight_bps()),
            ))
            .unwrap_or(u16::MAX),
        );
        spread_bps = spread_bps.min(self.config.max_spread_bps());

        let min_spread = self
            .config
            .tick_size()
            .0
            .saturating_mul(i64::from(self.config.min_spread_ticks()));
        let spread_price = price_bps_to_ticks(adjusted_fair_value, spread_bps).max(min_spread);
        let half = (spread_price / 2).max(self.config.tick_size().0);
        let bid_price = snap_down_to_tick(
            adjusted_fair_value.0.saturating_sub(half),
            self.config.tick_size().0,
        );
        let ask_price = snap_up_to_tick(
            adjusted_fair_value.0.saturating_add(half),
            self.config.tick_size().0,
        );
        let quote_bid = context.inventory_qty().0 < context.max_inventory_qty().0;
        let quote_ask = context.inventory_qty().0 > -context.max_inventory_qty().0;

        Ok(MarketMakerQuoteEstimate {
            adjusted_fair_value,
            bid_price: OrderPrice(bid_price.max(self.config.tick_size().0)),
            ask_price: OrderPrice(
                ask_price.max(bid_price.saturating_add(self.config.tick_size().0)),
            ),
            spread_bps,
            quote_bid,
            quote_ask,
        })
    }

    /// Plans bid and ask child quote orders.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when inputs are invalid or a generated quote order
    /// fails OMS request validation.
    #[allow(
        clippy::too_many_arguments,
        reason = "caller owns quote identifiers and timestamps"
    )]
    pub fn plan_quotes(
        &self,
        template: &ParentOrder,
        now_ns: u64,
        context: MarketMakerContext,
        bid_child_id: ChildOrderId,
        bid_client_order_id: ClientOrderId,
        ask_child_id: ChildOrderId,
        ask_client_order_id: ClientOrderId,
        ts_recv_ns: u64,
    ) -> Result<MarketMakerQuoteDecision, AlgoError> {
        if template.status().is_terminal() {
            return Err(AlgoError::ParentTerminal);
        }
        let estimate = self.estimate(template, context)?;
        let bid = if estimate.quote_bid() {
            let request = template.build_order_request_for_side_at_price(
                OrderSide::Buy,
                bid_client_order_id,
                self.config.quote_qty(),
                estimate.bid_price(),
                ts_recv_ns,
            );
            Some(ChildOrderPlan::new(
                bid_child_id,
                template.id(),
                request,
                now_ns,
            )?)
        } else {
            None
        };
        let ask = if estimate.quote_ask() {
            let request = template.build_order_request_for_side_at_price(
                OrderSide::Sell,
                ask_client_order_id,
                self.config.quote_qty(),
                estimate.ask_price(),
                ts_recv_ns,
            );
            Some(ChildOrderPlan::new(
                ask_child_id,
                template.id(),
                request,
                now_ns,
            )?)
        } else {
            None
        };
        Ok(MarketMakerQuoteDecision { estimate, bid, ask })
    }

    fn validate_context(&self, context: MarketMakerContext) -> Result<(), AlgoError> {
        if self.config.tick_size().0 <= 0
            || self.config.quote_qty().0 <= 0
            || self.config.base_spread_bps() > self.config.max_spread_bps()
            || context.fair_value().0 <= 0
            || context.best_bid().0 <= 0
            || context.best_ask().0 <= 0
            || context.best_bid().0 >= context.best_ask().0
            || context.max_inventory_qty().0 <= 0
        {
            return Err(AlgoError::InvalidMarketMakingParameters);
        }
        Ok(())
    }
}

/// Market context for implementation-shortfall planning.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ImplementationShortfallContext {
    arrival_price: OrderPrice,
    reference_price: OrderPrice,
    volatility_bps: u16,
    spread_bps: u16,
    temporary_impact_bps: u16,
}

impl ImplementationShortfallContext {
    /// Creates implementation-shortfall market context.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidShortfallParameters`] when either price is
    /// not positive.
    pub const fn new(
        arrival_price: OrderPrice,
        reference_price: OrderPrice,
        volatility_bps: u16,
        spread_bps: u16,
        temporary_impact_bps: u16,
    ) -> Result<Self, AlgoError> {
        if arrival_price.0 <= 0 || reference_price.0 <= 0 {
            return Err(AlgoError::InvalidShortfallParameters);
        }
        Ok(Self {
            arrival_price,
            reference_price,
            volatility_bps,
            spread_bps,
            temporary_impact_bps,
        })
    }

    /// Returns the arrival benchmark price.
    pub const fn arrival_price(&self) -> OrderPrice {
        self.arrival_price
    }

    /// Returns the current decision/reference price.
    pub const fn reference_price(&self) -> OrderPrice {
        self.reference_price
    }

    /// Returns estimated short-horizon volatility in basis points.
    pub const fn volatility_bps(&self) -> u16 {
        self.volatility_bps
    }

    /// Returns current spread in basis points.
    pub const fn spread_bps(&self) -> u16 {
        self.spread_bps
    }

    /// Returns temporary market-impact estimate in basis points.
    pub const fn temporary_impact_bps(&self) -> u16 {
        self.temporary_impact_bps
    }
}

/// Configuration for implementation-shortfall planning.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ImplementationShortfallConfig {
    base_urgency_bps: u16,
    max_urgency_bps: u16,
    volatility_weight_bps: u16,
    spread_weight_bps: u16,
    adverse_move_weight_bps: u16,
    impact_weight_bps: u16,
}

impl ImplementationShortfallConfig {
    /// Creates implementation-shortfall planner configuration.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError::InvalidShortfallParameters`] when urgency values
    /// exceed 10,000 bps or base urgency exceeds the cap.
    pub const fn new(
        base_urgency_bps: u16,
        max_urgency_bps: u16,
        volatility_weight_bps: u16,
        spread_weight_bps: u16,
        adverse_move_weight_bps: u16,
        impact_weight_bps: u16,
    ) -> Result<Self, AlgoError> {
        if base_urgency_bps > 10_000
            || max_urgency_bps > 10_000
            || base_urgency_bps > max_urgency_bps
        {
            return Err(AlgoError::InvalidShortfallParameters);
        }
        Ok(Self {
            base_urgency_bps,
            max_urgency_bps,
            volatility_weight_bps,
            spread_weight_bps,
            adverse_move_weight_bps,
            impact_weight_bps,
        })
    }

    /// Returns base urgency in basis points.
    pub const fn base_urgency_bps(&self) -> u16 {
        self.base_urgency_bps
    }

    /// Returns maximum urgency in basis points.
    pub const fn max_urgency_bps(&self) -> u16 {
        self.max_urgency_bps
    }

    /// Returns volatility urgency weight in basis points.
    pub const fn volatility_weight_bps(&self) -> u16 {
        self.volatility_weight_bps
    }

    /// Returns spread urgency weight in basis points.
    pub const fn spread_weight_bps(&self) -> u16 {
        self.spread_weight_bps
    }

    /// Returns adverse move urgency weight in basis points.
    pub const fn adverse_move_weight_bps(&self) -> u16 {
        self.adverse_move_weight_bps
    }

    /// Returns temporary impact patience weight in basis points.
    pub const fn impact_weight_bps(&self) -> u16 {
        self.impact_weight_bps
    }
}

impl Default for ImplementationShortfallConfig {
    fn default() -> Self {
        Self {
            base_urgency_bps: 1_000,
            max_urgency_bps: 7_500,
            volatility_weight_bps: 5_000,
            spread_weight_bps: 2_500,
            adverse_move_weight_bps: 7_500,
            impact_weight_bps: 3_000,
        }
    }
}

/// Implementation-shortfall planning estimate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ImplementationShortfallEstimate {
    elapsed_bps: u16,
    adverse_move_bps: u16,
    urgency_bps: u16,
    target_release_qty: OrderQty,
}

impl ImplementationShortfallEstimate {
    /// Returns elapsed parent interval in basis points.
    pub const fn elapsed_bps(&self) -> u16 {
        self.elapsed_bps
    }

    /// Returns adverse move from arrival price in basis points.
    pub const fn adverse_move_bps(&self) -> u16 {
        self.adverse_move_bps
    }

    /// Returns urgency used for the decision in basis points.
    pub const fn urgency_bps(&self) -> u16 {
        self.urgency_bps
    }

    /// Returns target cumulative released quantity.
    pub const fn target_release_qty(&self) -> OrderQty {
        self.target_release_qty
    }
}

/// Deterministic implementation-shortfall planner.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ImplementationShortfallPlanner {
    config: ImplementationShortfallConfig,
}

impl ImplementationShortfallPlanner {
    /// Creates an implementation-shortfall planner.
    pub const fn new(config: ImplementationShortfallConfig) -> Self {
        Self { config }
    }

    /// Returns planner configuration.
    pub const fn config(&self) -> ImplementationShortfallConfig {
        self.config
    }

    /// Estimates the current implementation-shortfall target.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when parent/progress/context state is invalid.
    pub fn estimate(
        &self,
        parent: &ParentOrder,
        progress: AlgoProgress,
        now_ns: u64,
        context: ImplementationShortfallContext,
    ) -> Result<ImplementationShortfallEstimate, AlgoError> {
        parent.validate()?;
        if progress.parent_id() != parent.id() || progress.target_qty() != parent.total_qty() {
            return Err(AlgoError::InvalidProgress);
        }
        if context.arrival_price().0 <= 0 || context.reference_price().0 <= 0 {
            return Err(AlgoError::InvalidShortfallParameters);
        }
        let elapsed_bps = elapsed_bps(parent.start_ns(), parent.end_ns(), now_ns);
        let adverse_move_bps = adverse_move_bps(
            parent.side(),
            context.arrival_price(),
            context.reference_price(),
        );
        let urgency_bps = self.urgency_bps(context, adverse_move_bps);
        let remaining_time_bps = 10_000_u16.saturating_sub(elapsed_bps);
        let target_bps = u32::from(elapsed_bps).saturating_add(scale_bps_u32(
            u32::from(remaining_time_bps),
            u32::from(urgency_bps),
        ));
        let target_release_qty = scale_qty_bps(parent.total_qty().0, target_bps.min(10_000));
        Ok(ImplementationShortfallEstimate {
            elapsed_bps,
            adverse_move_bps,
            urgency_bps,
            target_release_qty: OrderQty(target_release_qty),
        })
    }

    /// Plans one implementation-shortfall child slice.
    ///
    /// # Errors
    ///
    /// Returns [`AlgoError`] when parent/progress/context state is invalid or
    /// the generated child order would be invalid.
    #[allow(
        clippy::too_many_arguments,
        reason = "caller owns identifiers and timestamps"
    )]
    pub fn plan_shortfall_slice(
        &self,
        parent: &ParentOrder,
        progress: AlgoProgress,
        now_ns: u64,
        context: ImplementationShortfallContext,
        child_id: ChildOrderId,
        client_order_id: ClientOrderId,
        ts_recv_ns: u64,
    ) -> Result<Option<ChildOrderPlan>, AlgoError> {
        if parent.status().is_terminal() {
            return Err(AlgoError::ParentTerminal);
        }
        if now_ns < parent.start_ns() || progress.is_complete() {
            return Ok(None);
        }

        let estimate = self.estimate(parent, progress, now_ns, context)?;
        let due_qty = estimate
            .target_release_qty()
            .0
            .saturating_sub(progress.released_qty().0);
        if due_qty <= 0 {
            return Ok(None);
        }
        let leaves = parent
            .total_qty()
            .0
            .saturating_sub(progress.released_qty().0);
        let mut child_qty = due_qty.min(parent.max_clip().0).min(leaves);
        let final_slice = progress.released_qty().0.saturating_add(child_qty)
            >= parent.total_qty().0
            || now_ns >= parent.end_ns();
        if child_qty < parent.min_clip().0 && !final_slice {
            return Ok(None);
        }
        if child_qty <= 0 {
            return Ok(None);
        }
        child_qty = child_qty.min(
            parent
                .total_qty()
                .0
                .saturating_sub(progress.released_qty().0),
        );
        let request = parent.build_order_request(client_order_id, OrderQty(child_qty), ts_recv_ns);
        Ok(Some(ChildOrderPlan::new(
            child_id,
            parent.id(),
            request,
            now_ns,
        )?))
    }

    fn urgency_bps(&self, context: ImplementationShortfallContext, adverse_move_bps: u16) -> u16 {
        let mut urgency = i64::from(self.config.base_urgency_bps());
        urgency = urgency.saturating_add(i64::from(scale_bps_u32(
            u32::from(context.volatility_bps()),
            u32::from(self.config.volatility_weight_bps()),
        )));
        urgency = urgency.saturating_add(i64::from(scale_bps_u32(
            u32::from(context.spread_bps()),
            u32::from(self.config.spread_weight_bps()),
        )));
        urgency = urgency.saturating_add(i64::from(scale_bps_u32(
            u32::from(adverse_move_bps),
            u32::from(self.config.adverse_move_weight_bps()),
        )));
        urgency = urgency.saturating_sub(i64::from(scale_bps_u32(
            u32::from(context.temporary_impact_bps()),
            u32::from(self.config.impact_weight_bps()),
        )));
        let bounded = urgency.clamp(0, i64::from(self.config.max_urgency_bps()));
        u16::try_from(bounded).unwrap_or(self.config.max_urgency_bps())
    }
}

/// Replay event consumed by an algorithm harness.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
#[allow(
    clippy::large_enum_variant,
    reason = "replay events remain Copy so caller-owned replay buffers avoid boxing"
)]
pub enum AlgoReplayEvent {
    /// Deterministic timer tick at `timestamp_ns`.
    Timer {
        /// Timer timestamp in nanoseconds.
        timestamp_ns: u64,
    },
    /// Canonical OMS execution event.
    Execution(ExecutionEvent),
    /// Parent lifecycle status update.
    ParentStatus {
        /// New parent status.
        status: ParentOrderStatus,
    },
}

/// Sequenced replay input.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoReplayInput {
    sequence: u64,
    event: AlgoReplayEvent,
}

impl AlgoReplayInput {
    /// Creates a replay input.
    pub const fn new(sequence: u64, event: AlgoReplayEvent) -> Self {
        Self { sequence, event }
    }

    /// Returns the replay input sequence.
    pub const fn sequence(&self) -> u64 {
        self.sequence
    }

    /// Returns the replay event.
    pub const fn event(&self) -> AlgoReplayEvent {
        self.event
    }
}

/// Deterministic child/client id generation prefixes for replay.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoReplayIdScheme {
    child_prefix: FixedAscii<24>,
    client_prefix: FixedAscii<24>,
}

impl AlgoReplayIdScheme {
    /// Creates replay id prefixes.
    ///
    /// # Errors
    ///
    /// Returns [`ExecutionCoreError`] when a prefix is non-ASCII or too long.
    pub fn new(child_prefix: &str, client_prefix: &str) -> Result<Self, ExecutionCoreError> {
        Ok(Self {
            child_prefix: FixedAscii::new(child_prefix)?,
            client_prefix: FixedAscii::new(client_prefix)?,
        })
    }

    /// Returns the child id prefix.
    pub const fn child_prefix(&self) -> FixedAscii<24> {
        self.child_prefix
    }

    /// Returns the client order id prefix.
    pub const fn client_prefix(&self) -> FixedAscii<24> {
        self.client_prefix
    }

    fn child_id(&self, index: u64) -> Result<ChildOrderId, AlgoError> {
        fixed_id_with_index(self.child_prefix.as_str(), index)
    }

    fn client_order_id(&self, index: u64) -> Result<ClientOrderId, AlgoError> {
        fixed_id_with_index(self.client_prefix.as_str(), index)
    }
}

impl Default for AlgoReplayIdScheme {
    fn default() -> Self {
        Self::new("child", "cl").expect("static replay id prefixes are valid")
    }
}

/// Replay step emitted for one input event.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoReplayStep<const N: usize = DEFAULT_ALGO_DECISION_CAPACITY> {
    input_sequence: u64,
    event: AlgoReplayEvent,
    progress_before: AlgoProgress,
    progress_after: AlgoProgress,
    decision: AlgoDecision<N>,
}

impl<const N: usize> AlgoReplayStep<N> {
    /// Returns the replay input sequence.
    pub const fn input_sequence(&self) -> u64 {
        self.input_sequence
    }

    /// Returns the replay event.
    pub const fn event(&self) -> AlgoReplayEvent {
        self.event
    }

    /// Returns progress before applying the event.
    pub const fn progress_before(&self) -> AlgoProgress {
        self.progress_before
    }

    /// Returns progress after applying the event and any generated decision.
    pub const fn progress_after(&self) -> AlgoProgress {
        self.progress_after
    }

    /// Returns the decision generated for this input.
    pub const fn decision(&self) -> &AlgoDecision<N> {
        &self.decision
    }
}

/// Summary returned by deterministic TWAP replay.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AlgoReplaySummary {
    input_events: u64,
    decisions: u64,
    actions: u64,
    submitted_children: u64,
    final_progress: AlgoProgress,
    deterministic_hash: u64,
}

impl AlgoReplaySummary {
    /// Returns replay input event count.
    pub const fn input_events(&self) -> u64 {
        self.input_events
    }

    /// Returns emitted decision count.
    pub const fn decisions(&self) -> u64 {
        self.decisions
    }

    /// Returns total emitted action count.
    pub const fn actions(&self) -> u64 {
        self.actions
    }

    /// Returns submitted child action count.
    pub const fn submitted_children(&self) -> u64 {
        self.submitted_children
    }

    /// Returns final parent progress.
    pub const fn final_progress(&self) -> AlgoProgress {
        self.final_progress
    }

    /// Returns deterministic replay hash for regression checks.
    pub const fn deterministic_hash(&self) -> u64 {
        self.deterministic_hash
    }
}

/// Replays TWAP planning over explicit deterministic inputs.
///
/// `out` is caller-owned and cleared before replay. This keeps allocation
/// policy outside the harness and lets test/benchmark callers reuse capacity.
///
/// # Errors
///
/// Returns [`AlgoError`] when parent/progress state is invalid, a generated
/// child plan is invalid, or the fixed-capacity decision cannot hold a due
/// action.
pub fn replay_twap_into<const N: usize>(
    parent: ParentOrder,
    planner: TwapSlicePlanner,
    inputs: &[AlgoReplayInput],
    id_scheme: AlgoReplayIdScheme,
    out: &mut Vec<AlgoReplayStep<N>>,
) -> Result<AlgoReplaySummary, AlgoError> {
    parent.validate()?;
    out.clear();

    let mut active_parent = parent;
    let mut progress = AlgoProgress::new(parent.id(), parent.total_qty());
    let mut decisions = 0_u64;
    let mut actions = 0_u64;
    let mut submitted_children = 0_u64;
    let mut hash = FNV_OFFSET_BASIS;

    for input in inputs {
        let before = progress;
        let mut decision = AlgoDecision::<N>::new(decisions.saturating_add(1));
        match input.event() {
            AlgoReplayEvent::Timer { timestamp_ns } => {
                let next_child = submitted_children.saturating_add(1);
                if let Some(plan) = planner.plan_due_slice(
                    &active_parent,
                    progress,
                    timestamp_ns,
                    id_scheme.child_id(next_child)?,
                    id_scheme.client_order_id(next_child)?,
                    timestamp_ns,
                )? {
                    decision.push(AlgoAction::SubmitChild(plan))?;
                    progress.on_child_released(&plan)?;
                    submitted_children = submitted_children.saturating_add(1);
                }
            }
            AlgoReplayEvent::Execution(event) => {
                progress.on_execution_event(&event);
            }
            AlgoReplayEvent::ParentStatus { status } => {
                active_parent = active_parent.with_status(status);
            }
        }

        decisions = decisions.saturating_add(1);
        actions = actions.saturating_add(usize_to_u64(decision.len()));
        hash = hash_replay_step(hash, input.sequence(), input.event(), progress, &decision);
        out.push(AlgoReplayStep {
            input_sequence: input.sequence(),
            event: input.event(),
            progress_before: before,
            progress_after: progress,
            decision,
        });
    }

    Ok(AlgoReplaySummary {
        input_events: usize_to_u64(inputs.len()),
        decisions,
        actions,
        submitted_children,
        final_progress: progress,
        deterministic_hash: hash,
    })
}

fn div_ceil_u64(lhs: u64, rhs: u64) -> u64 {
    lhs / rhs + u64::from(!lhs.is_multiple_of(rhs))
}

fn div_ceil_i128(lhs: i128, rhs: i128) -> i128 {
    lhs / rhs + i128::from(lhs % rhs != 0)
}

fn participation_qty(volume: i64, bps: u16) -> i64 {
    let value = i128::from(volume) * i128::from(bps);
    i64::try_from(value / 10_000).unwrap_or(i64::MAX)
}

fn vwap_target_qty(parent_qty: i64, cumulative_weight: u64, total_weight: u64) -> i64 {
    let value = i128::from(parent_qty) * i128::from(cumulative_weight);
    i64::try_from(value / i128::from(total_weight)).unwrap_or(i64::MAX)
}

fn elapsed_bps(start_ns: u64, end_ns: u64, now_ns: u64) -> u16 {
    if now_ns <= start_ns {
        return 0;
    }
    if now_ns >= end_ns {
        return 10_000;
    }
    let elapsed = now_ns.saturating_sub(start_ns);
    let total = end_ns.saturating_sub(start_ns).max(1);
    u16::try_from((u128::from(elapsed) * 10_000) / u128::from(total)).unwrap_or(10_000)
}

fn scale_bps_u32(value: u32, bps: u32) -> u32 {
    let scaled = (u128::from(value) * u128::from(bps)) / 10_000;
    u32::try_from(scaled).unwrap_or(u32::MAX)
}

fn scale_qty_bps(quantity: i64, bps: u32) -> i64 {
    let scaled = (i128::from(quantity) * i128::from(bps)) / 10_000;
    i64::try_from(scaled).unwrap_or(i64::MAX)
}

fn participation_bps(child_qty: i64, market_volume: i64) -> u32 {
    if child_qty <= 0 || market_volume <= 0 {
        return 0;
    }
    let bps = (i128::from(child_qty) * 10_000) / i128::from(market_volume);
    u32::try_from(bps.clamp(0, i128::from(u32::MAX))).unwrap_or(u32::MAX)
}

fn price_distance_bps(price: OrderPrice, reference: OrderPrice) -> u32 {
    if price.0 <= 0 || reference.0 <= 0 {
        return u32::MAX;
    }
    let distance = price.0.abs_diff(reference.0);
    let bps = (u128::from(distance) * 10_000) / i64_to_u128(reference.0);
    u32::try_from(bps.min(u128::from(u32::MAX))).unwrap_or(u32::MAX)
}

fn child_notional(child: &ChildOrderPlan) -> u128 {
    i64_to_u128(child.request().quantity.0)
        .saturating_mul(i64_to_u128(child.request().limit_price.0))
}

fn completion_bps(completed_qty: i64, target_qty: i64) -> u16 {
    if completed_qty <= 0 || target_qty <= 0 {
        return 0;
    }
    let bps = (i128::from(completed_qty) * 10_000) / i128::from(target_qty);
    u16::try_from(bps.clamp(0, 10_000)).unwrap_or(10_000)
}

fn average_price_from_notional(notional: u128, quantity: OrderQty) -> OrderPrice {
    if notional == 0 || quantity.0 <= 0 {
        return OrderPrice(0);
    }
    let avg = notional / i64_to_u128(quantity.0);
    OrderPrice(i64::try_from(avg).unwrap_or(i64::MAX))
}

fn side_slippage_bps(side: OrderSide, average_price: OrderPrice, benchmark: OrderPrice) -> i32 {
    if average_price.0 <= 0 || benchmark.0 <= 0 {
        return 0;
    }
    let raw = match side {
        OrderSide::Buy => i128::from(average_price.0) - i128::from(benchmark.0),
        OrderSide::Sell => i128::from(benchmark.0) - i128::from(average_price.0),
    };
    let bps = (raw * 10_000) / i128::from(benchmark.0);
    i32::try_from(bps.clamp(i128::from(i32::MIN), i128::from(i32::MAX))).unwrap_or(0)
}

fn optional_slippage_bps(side: OrderSide, average_price: OrderPrice, benchmark: OrderPrice) -> i32 {
    if benchmark.0 <= 0 {
        0
    } else {
        side_slippage_bps(side, average_price, benchmark)
    }
}

fn average_latency_ns(total_latency_ns: u128, samples: u64) -> u64 {
    if samples == 0 {
        return 0;
    }
    u64::try_from(total_latency_ns / u128::from(samples)).unwrap_or(u64::MAX)
}

fn i64_to_u128(value: i64) -> u128 {
    u128::try_from(value.max(0)).unwrap_or(0)
}

fn stronger_risk_outcome(current: AlgoRiskOutcome, kind: AlgoRiskViolationKind) -> AlgoRiskOutcome {
    if matches!(
        kind,
        AlgoRiskViolationKind::KillSwitchActive | AlgoRiskViolationKind::OperatorPaused
    ) {
        return AlgoRiskOutcome::KillSwitch;
    }
    if matches!(current, AlgoRiskOutcome::KillSwitch) {
        AlgoRiskOutcome::KillSwitch
    } else {
        AlgoRiskOutcome::Block
    }
}

fn scale_qty_inverse_bps(quantity: i64, bps: u32) -> i64 {
    if bps == 0 {
        return 0;
    }
    let scaled = (i128::from(quantity) * 10_000) / i128::from(bps);
    i64::try_from(scaled).unwrap_or(i64::MAX)
}

fn spread_edge_bps(buy_price: OrderPrice, sell_price: OrderPrice, ratio_bps: u32) -> i32 {
    if buy_price.0 <= 0 || sell_price.0 <= 0 || ratio_bps == 0 {
        return i32::MIN;
    }
    let scaled_sell = (i128::from(sell_price.0) * i128::from(ratio_bps)) / 10_000;
    let edge = ((scaled_sell - i128::from(buy_price.0)) * 10_000) / i128::from(buy_price.0);
    i32::try_from(edge.clamp(i128::from(i32::MIN), i128::from(i32::MAX))).unwrap_or(0)
}

fn passive_candidate_qty(parent: &ParentOrder, progress: AlgoProgress, now_ns: u64) -> OrderQty {
    let leaves = parent
        .total_qty()
        .0
        .saturating_sub(progress.released_qty().0);
    if leaves <= 0 {
        return OrderQty(0);
    }
    let mut qty = leaves.min(parent.max_clip().0);
    let final_slice = progress.released_qty().0.saturating_add(qty) >= parent.total_qty().0
        || now_ns >= parent.end_ns();
    if qty < parent.min_clip().0 && final_slice {
        qty = leaves;
    }
    OrderQty(qty.min(leaves))
}

fn queue_fill_probability_bps(queue_ahead_qty: i64, child_qty: i64, expected_take_qty: i64) -> u16 {
    if child_qty <= 0 || expected_take_qty <= 0 {
        return 0;
    }
    let required = queue_ahead_qty.max(0).saturating_add(child_qty);
    if required <= 0 {
        return 10_000;
    }
    let bps = (i128::from(expected_take_qty) * 10_000) / i128::from(required);
    u16::try_from(bps.clamp(0, 10_000)).unwrap_or(10_000)
}

fn midpoint_price(
    side: OrderSide,
    context: PassiveQueueContext,
    tick_size: OrderPrice,
) -> OrderPrice {
    let bid = context.best_bid().0;
    let ask = context.best_ask().0;
    let mid = bid.saturating_add(ask.saturating_sub(bid) / 2);
    match side {
        OrderSide::Buy => {
            let ticks_from_bid = mid.saturating_sub(bid) / tick_size.0;
            OrderPrice(bid.saturating_add(ticks_from_bid.saturating_mul(tick_size.0)))
        }
        OrderSide::Sell => {
            let ticks_from_ask = ask.saturating_sub(mid) / tick_size.0;
            OrderPrice(ask.saturating_sub(ticks_from_ask.saturating_mul(tick_size.0)))
        }
    }
}

fn route_liquidity_bps(available_qty: i64, target_qty: i64) -> u16 {
    if available_qty <= 0 || target_qty <= 0 {
        return 0;
    }
    let bps = (i128::from(available_qty) * 10_000) / i128::from(target_qty);
    u16::try_from(bps.clamp(0, 10_000)).unwrap_or(10_000)
}

fn route_price_penalty_bps(side: OrderSide, price: OrderPrice, best_price: OrderPrice) -> u16 {
    if price.0 <= 0 || best_price.0 <= 0 {
        return 10_000;
    }
    let penalty_ticks = match side {
        OrderSide::Buy => price.0.saturating_sub(best_price.0),
        OrderSide::Sell => best_price.0.saturating_sub(price.0),
    };
    if penalty_ticks <= 0 {
        return 0;
    }
    let bps = (i128::from(penalty_ticks) * 10_000) / i128::from(best_price.0);
    u16::try_from(bps.clamp(0, 10_000)).unwrap_or(10_000)
}

fn best_sor_price(side: OrderSide, candidates: &[SorRouteCandidate]) -> Option<OrderPrice> {
    let mut best: Option<OrderPrice> = None;
    for candidate in candidates {
        if !candidate.status().is_routable()
            || candidate.price().0 <= 0
            || candidate.available_qty().0 <= 0
        {
            continue;
        }
        best = Some(match (side, best) {
            (_, None) => candidate.price(),
            (OrderSide::Buy, Some(current)) => OrderPrice(current.0.min(candidate.price().0)),
            (OrderSide::Sell, Some(current)) => OrderPrice(current.0.max(candidate.price().0)),
        });
    }
    best
}

fn decision_has_route<const N: usize>(decision: &SorDecision<N>, route_id: RouteId) -> bool {
    decision
        .allocations()
        .any(|allocation| allocation.plan().request().route_id == route_id)
}

fn liquidity_decision_has_route<const N: usize>(
    decision: &LiquiditySeekingDecision<N>,
    route_id: RouteId,
) -> bool {
    decision
        .allocations()
        .any(|allocation| allocation.plan().request().route_id == route_id)
}

fn sweep_decision_has_level<const N: usize>(
    decision: &SweepDecision<N>,
    route_id: RouteId,
    price: OrderPrice,
) -> bool {
    decision.allocations().any(|allocation| {
        allocation.plan().request().route_id == route_id
            && allocation.plan().request().limit_price == price
    })
}

fn price_inside_collar(side: OrderSide, price: OrderPrice, collar: OrderPrice) -> bool {
    match side {
        OrderSide::Buy => price.0 <= collar.0,
        OrderSide::Sell => price.0 >= collar.0,
    }
}

fn best_liquidity_price(
    side: OrderSide,
    candidates: &[LiquiditySeekingCandidate],
) -> Option<OrderPrice> {
    let mut best: Option<OrderPrice> = None;
    for candidate in candidates {
        let route = candidate.route();
        if !route.status().is_routable() || route.price().0 <= 0 || route.available_qty().0 <= 0 {
            continue;
        }
        best = Some(match (side, best) {
            (_, None) => route.price(),
            (OrderSide::Buy, Some(current)) => OrderPrice(current.0.min(route.price().0)),
            (OrderSide::Sell, Some(current)) => OrderPrice(current.0.max(route.price().0)),
        });
    }
    best
}

fn signed_inventory_ratio_bps(inventory_qty: i64, max_inventory_qty: i64) -> i32 {
    if max_inventory_qty <= 0 {
        return 0;
    }
    let ratio = (i128::from(inventory_qty) * 10_000) / i128::from(max_inventory_qty);
    i32::try_from(ratio.clamp(-10_000, 10_000)).unwrap_or(0)
}

fn scale_signed_bps(value_bps: i32, weight_bps: i32) -> i32 {
    let scaled = (i64::from(value_bps) * i64::from(weight_bps)) / 10_000;
    i32::try_from(scaled.clamp(i64::from(i32::MIN), i64::from(i32::MAX))).unwrap_or(0)
}

fn apply_price_bps(price: OrderPrice, adjustment_bps: i32) -> OrderPrice {
    let adjustment = (i128::from(price.0) * i128::from(adjustment_bps)) / 10_000;
    let adjusted = i128::from(price.0).saturating_add(adjustment);
    OrderPrice(i64::try_from(adjusted.max(1)).unwrap_or(i64::MAX))
}

fn price_bps_to_ticks(price: OrderPrice, bps: u16) -> i64 {
    let value = (i128::from(price.0) * i128::from(bps)) / 10_000;
    i64::try_from(value.max(1)).unwrap_or(i64::MAX)
}

fn snap_down_to_tick(price: i64, tick_size: i64) -> i64 {
    if tick_size <= 0 {
        return price;
    }
    price - price.rem_euclid(tick_size)
}

fn snap_up_to_tick(price: i64, tick_size: i64) -> i64 {
    if tick_size <= 0 {
        return price;
    }
    let rem = price.rem_euclid(tick_size);
    if rem == 0 {
        price
    } else {
        price.saturating_add(tick_size.saturating_sub(rem))
    }
}

fn adverse_move_bps(side: OrderSide, arrival: OrderPrice, reference: OrderPrice) -> u16 {
    let adverse_ticks = match side {
        OrderSide::Buy => reference.0.saturating_sub(arrival.0),
        OrderSide::Sell => arrival.0.saturating_sub(reference.0),
    };
    if adverse_ticks <= 0 || arrival.0 <= 0 {
        return 0;
    }
    let bps = (i128::from(adverse_ticks) * 10_000) / i128::from(arrival.0);
    u16::try_from(bps.min(i128::from(u16::MAX))).unwrap_or(u16::MAX)
}

fn fixed_id_with_index<const N: usize>(
    prefix: &str,
    index: u64,
) -> Result<FixedAscii<N>, AlgoError> {
    let mut bytes = [0_u8; N];
    let prefix_bytes = prefix.as_bytes();
    if prefix_bytes.len().saturating_add(1) > N {
        return Err(AlgoError::GeneratedIdentifierTooLong);
    }
    bytes[..prefix_bytes.len()].copy_from_slice(prefix_bytes);
    let mut len = prefix_bytes.len();
    bytes[len] = b'-';
    len += 1;

    let mut digits = [0_u8; 20];
    let mut value = index;
    let mut digit_len = 0_usize;
    loop {
        digits[digit_len] = b'0' + u8::try_from(value % 10).unwrap_or(0);
        digit_len += 1;
        value /= 10;
        if value == 0 {
            break;
        }
    }
    if len.saturating_add(digit_len) > N {
        return Err(AlgoError::GeneratedIdentifierTooLong);
    }
    for digit in digits[..digit_len].iter().rev() {
        bytes[len] = *digit;
        len += 1;
    }
    let value =
        std::str::from_utf8(&bytes[..len]).expect("prefix is ASCII and generated digits are ASCII");
    Ok(FixedAscii::new(value)?)
}

fn usize_to_u64(value: usize) -> u64 {
    u64::try_from(value).unwrap_or(u64::MAX)
}

fn hash_u64(mut hash: u64, value: u64) -> u64 {
    for byte in value.to_le_bytes() {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(FNV_PRIME);
    }
    hash
}

fn hash_i64(hash: u64, value: i64) -> u64 {
    hash_u64(hash, value as u64)
}

fn hash_replay_step<const N: usize>(
    mut hash: u64,
    input_sequence: u64,
    event: AlgoReplayEvent,
    progress: AlgoProgress,
    decision: &AlgoDecision<N>,
) -> u64 {
    hash = hash_u64(hash, input_sequence);
    hash = match event {
        AlgoReplayEvent::Timer { timestamp_ns } => hash_u64(hash_u64(hash, 1), timestamp_ns),
        AlgoReplayEvent::Execution(event) => hash_i64(
            hash_u64(hash_u64(hash, 2), u64::from(event.order_status as u8)),
            event.last_qty.0,
        ),
        AlgoReplayEvent::ParentStatus { status } => hash_u64(hash_u64(hash, 3), status as u64),
    };
    hash = hash_i64(hash, progress.released_qty().0);
    hash = hash_i64(hash, progress.completed_qty().0);
    hash = hash_i64(hash, progress.open_qty().0);
    hash_u64(hash, usize_to_u64(decision.len()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use of_execution_core::{ExecutionEvent, ExecutionId, RiskRejectReason, VenueOrderId};

    fn parent() -> ParentOrder {
        ParentOrder::new(
            ParentOrderId::new("parent-1").expect("id"),
            AccountId::new("acct").expect("account"),
            RouteId::new("sim").expect("route"),
            StrategyId::new("twap").expect("strategy"),
            ExecutionSymbol::new("SIM", "ESZ6").expect("symbol"),
            OrderSide::Buy,
            OrderType::Limit,
            TimeInForce::Day,
            OrderQty(100),
            OrderPrice(500_000),
            OrderPrice(0),
            1_000,
            11_000,
            OrderQty(10),
            OrderQty(25),
            0,
        )
        .expect("parent")
    }

    fn sell_parent(
        id: &str,
        total_qty: OrderQty,
        min_clip: OrderQty,
        max_clip: OrderQty,
    ) -> ParentOrder {
        ParentOrder::new(
            ParentOrderId::new(id).expect("id"),
            AccountId::new("acct").expect("account"),
            RouteId::new("sim").expect("route"),
            StrategyId::new("spread").expect("strategy"),
            ExecutionSymbol::new("SIM", "NQZ6").expect("symbol"),
            OrderSide::Sell,
            OrderType::Limit,
            TimeInForce::Day,
            total_qty,
            OrderPrice(1_000_000),
            OrderPrice(0),
            1_000,
            11_000,
            min_clip,
            max_clip,
            0,
        )
        .expect("sell parent")
    }

    #[test]
    fn twap_plans_due_slices_without_over_release() {
        let parent = parent();
        let planner = TwapSlicePlanner::new(1_000);
        let mut progress = AlgoProgress::new(parent.id(), parent.total_qty());

        let first = planner
            .plan_due_slice(
                &parent,
                progress,
                1_000,
                ChildOrderId::new("child-1").expect("child"),
                ClientOrderId::new("cl-1").expect("client"),
                1_000,
            )
            .expect("plan")
            .expect("due");
        assert_eq!(first.request().quantity, OrderQty(10));
        progress.on_child_released(&first).expect("release");

        let second_same_bucket = planner
            .plan_due_slice(
                &parent,
                progress,
                1_500,
                ChildOrderId::new("child-2").expect("child"),
                ClientOrderId::new("cl-2").expect("client"),
                1_500,
            )
            .expect("plan");
        assert!(second_same_bucket.is_none());

        let later = planner
            .plan_due_slice(
                &parent,
                progress,
                3_000,
                ChildOrderId::new("child-3").expect("child"),
                ClientOrderId::new("cl-3").expect("client"),
                3_000,
            )
            .expect("plan")
            .expect("due");
        assert_eq!(later.request().quantity, OrderQty(20));
    }

    #[test]
    fn twap_respects_max_clip_and_final_leaves() {
        let parent = parent();
        let planner = TwapSlicePlanner::new(1_000);
        let progress = AlgoProgress::new(parent.id(), parent.total_qty());

        let late = planner
            .plan_due_slice(
                &parent,
                progress,
                10_500,
                ChildOrderId::new("child-late").expect("child"),
                ClientOrderId::new("cl-late").expect("client"),
                10_500,
            )
            .expect("plan")
            .expect("due");
        assert_eq!(late.request().quantity, parent.max_clip());
    }

    #[test]
    fn decision_buffer_is_bounded() {
        let mut decision = AlgoDecision::<1>::new(7);
        let plan = ChildOrderPlan::new(
            ChildOrderId::new("child-1").expect("child"),
            parent().id(),
            parent().build_order_request(
                ClientOrderId::new("cl-1").expect("client"),
                OrderQty(10),
                1,
            ),
            1,
        )
        .expect("plan");

        decision
            .push(AlgoAction::SubmitChild(plan))
            .expect("first action");
        assert_eq!(decision.len(), 1);
        assert_eq!(
            decision.push(AlgoAction::CompleteParent {
                parent_id: parent().id()
            }),
            Err(AlgoError::DecisionFull { capacity: 1 })
        );
        assert_eq!(decision.actions().count(), 1);
    }

    #[test]
    fn risk_policy_allows_child_inside_limits() {
        let parent = parent();
        let child = ChildOrderPlan::new(
            ChildOrderId::new("risk-ok").expect("child"),
            parent.id(),
            parent.build_order_request(
                ClientOrderId::new("risk-ok-cl").expect("client"),
                OrderQty(10),
                1,
            ),
            1,
        )
        .expect("child");
        let limits = AlgoRiskLimits::new(
            OrderQty(200),
            OrderQty(25),
            10_000_000,
            1_500,
            100,
            OrderQty(50),
            2,
            10,
        )
        .expect("limits");
        let context = AlgoRiskContext::new(OrderPrice(500_000))
            .expect("context")
            .with_observed_market_volume(OrderQty(1_000));

        let report = AlgoRiskPolicy::new(limits)
            .evaluate_child::<DEFAULT_ALGO_RISK_VIOLATION_CAPACITY>(
                &parent,
                AlgoProgress::new(parent.id(), parent.total_qty()),
                &child,
                context,
            )
            .expect("report");

        assert!(report.is_allowed());
        assert!(report.is_empty());
    }

    #[test]
    fn risk_policy_blocks_limit_breaches() {
        let parent = parent();
        let child = ChildOrderPlan::new(
            ChildOrderId::new("risk-block").expect("child"),
            parent.id(),
            parent.build_order_request_at_price(
                ClientOrderId::new("risk-block-cl").expect("client"),
                OrderQty(25),
                OrderPrice(510_000),
                1,
            ),
            1,
        )
        .expect("child");
        let limits = AlgoRiskLimits::new(
            OrderQty(100),
            OrderQty(10),
            5_000_000,
            1_000,
            100,
            OrderQty(50),
            2,
            10,
        )
        .expect("limits");
        let context = AlgoRiskContext::new(OrderPrice(500_000))
            .expect("context")
            .with_observed_market_volume(OrderQty(100));

        let report = AlgoRiskPolicy::new(limits)
            .evaluate_child::<DEFAULT_ALGO_RISK_VIOLATION_CAPACITY>(
                &parent,
                AlgoProgress::new(parent.id(), parent.total_qty()),
                &child,
                context,
            )
            .expect("report");

        assert_eq!(report.outcome(), AlgoRiskOutcome::Block);
        assert!(report
            .violations()
            .any(|violation| violation.kind() == AlgoRiskViolationKind::ChildQuantityExceeded));
        assert!(report
            .violations()
            .any(|violation| violation.kind() == AlgoRiskViolationKind::PriceCollarExceeded));
        assert!(report
            .violations()
            .any(|violation| violation.kind() == AlgoRiskViolationKind::ParticipationExceeded));
    }

    #[test]
    fn risk_policy_kill_switch_halts_submission() {
        let parent = parent();
        let child = ChildOrderPlan::new(
            ChildOrderId::new("risk-kill").expect("child"),
            parent.id(),
            parent.build_order_request(
                ClientOrderId::new("risk-kill-cl").expect("client"),
                OrderQty(10),
                1,
            ),
            1,
        )
        .expect("child");
        let context = AlgoRiskContext::new(OrderPrice(500_000))
            .expect("context")
            .with_kill_switch_active(true);

        let report = AlgoRiskPolicy::default()
            .evaluate_child::<DEFAULT_ALGO_RISK_VIOLATION_CAPACITY>(
                &parent,
                AlgoProgress::new(parent.id(), parent.total_qty()),
                &child,
                context,
            )
            .expect("report");

        assert_eq!(report.outcome(), AlgoRiskOutcome::KillSwitch);
        assert_eq!(
            report.first_violation().expect("violation").kind(),
            AlgoRiskViolationKind::KillSwitchActive
        );
    }

    #[test]
    fn risk_policy_checks_decision_level_limits() {
        let parent = parent();
        let mut decision = AlgoDecision::<2>::new(1);
        for index in 1..=2 {
            let suffix = index.to_string();
            let child = ChildOrderPlan::new(
                ChildOrderId::new(&format!("risk-d-{suffix}")).expect("child"),
                parent.id(),
                parent.build_order_request(
                    ClientOrderId::new(&format!("risk-d-cl-{suffix}")).expect("client"),
                    OrderQty(10),
                    index,
                ),
                index,
            )
            .expect("child");
            decision.push(AlgoAction::SubmitChild(child)).expect("push");
        }
        let limits = AlgoRiskLimits::new(OrderQty(0), OrderQty(0), 0, 0, 0, OrderQty(15), 1, 1)
            .expect("limits");
        let context = AlgoRiskContext::new(OrderPrice(500_000))
            .expect("context")
            .with_child_orders_in_window(0);

        let report = AlgoRiskPolicy::new(limits)
            .evaluate_decision::<DEFAULT_ALGO_RISK_VIOLATION_CAPACITY, 2>(
                &parent,
                AlgoProgress::new(parent.id(), parent.total_qty()),
                &decision,
                context,
            )
            .expect("report");

        assert_eq!(report.outcome(), AlgoRiskOutcome::Block);
        assert!(report.violations().any(
            |violation| violation.kind() == AlgoRiskViolationKind::ChildrenPerDecisionExceeded
        ));
        assert!(report
            .violations()
            .any(|violation| violation.kind() == AlgoRiskViolationKind::OpenQuantityExceeded));
    }

    #[test]
    fn algo_checkpoint_records_replay_cursors() {
        let parent = parent();
        let progress = AlgoProgress::new(parent.id(), parent.total_qty());
        let checkpoint = AlgoCheckpoint::new(parent, progress, 7, 42).expect("checkpoint");

        assert_eq!(checkpoint.schema_version(), ALGO_CHECKPOINT_SCHEMA_VERSION);
        assert_eq!(checkpoint.parent(), parent);
        assert_eq!(checkpoint.progress(), progress);
        assert_eq!(checkpoint.next_decision_seq(), 7);
        assert_eq!(checkpoint.last_input_sequence(), 42);
        assert_eq!(
            AlgoCheckpoint::new(parent, progress, 0, 42),
            Err(AlgoError::InvalidRecoveryState)
        );
    }

    #[test]
    fn recovery_plan_pauses_by_default() {
        let parent = parent();
        let progress = AlgoProgress::new(parent.id(), parent.total_qty());
        let checkpoint = AlgoCheckpoint::new(parent, progress, 7, 42).expect("checkpoint");
        let plan = AlgoRecoveryPlan::new(checkpoint, AlgoRecoveryPolicy::default()).expect("plan");

        assert_eq!(plan.action(), AlgoRecoveryAction::Pause);
        assert_eq!(plan.replay_from_sequence(), 43);
        assert_eq!(plan.next_decision_seq(), 7);
        assert!(plan.reconciliation_required());
    }

    #[test]
    fn recovery_plan_can_resume_when_policy_allows() {
        let parent = parent();
        let progress = AlgoProgress::new(parent.id(), parent.total_qty());
        let checkpoint = AlgoCheckpoint::new(parent, progress, 3, 9).expect("checkpoint");
        let policy = AlgoRecoveryPolicy::default()
            .with_pause_on_recovery(false)
            .with_require_reconciliation(false);
        let plan = AlgoRecoveryPlan::new(checkpoint, policy).expect("plan");

        assert_eq!(plan.action(), AlgoRecoveryAction::Resume);
        assert!(!plan.reconciliation_required());
    }

    #[test]
    fn recovery_plan_completes_finished_progress() {
        let parent = parent();
        let child = ChildOrderPlan::new(
            ChildOrderId::new("rec-child").expect("child"),
            parent.id(),
            parent.build_order_request(
                ClientOrderId::new("rec-cl").expect("client"),
                parent.total_qty(),
                1,
            ),
            1,
        )
        .expect("child");
        let mut progress = AlgoProgress::new(parent.id(), parent.total_qty());
        progress.on_child_released(&child).expect("release");
        progress.on_execution_event(&ExecutionEvent {
            exec_type: of_execution_core::ExecutionType::Trade,
            order_status: OrderStatus::Filled,
            client_order_id: child.request().client_order_id,
            orig_client_order_id: ClientOrderId::empty(),
            venue_order_id: VenueOrderId::new("rec-venue").expect("venue"),
            execution_id: ExecutionId::new("rec-exec").expect("exec"),
            account_id: parent.account_id(),
            route_id: parent.route_id(),
            symbol: parent.symbol(),
            last_qty: parent.total_qty(),
            last_price: parent.limit_price(),
            cumulative_qty: parent.total_qty(),
            leaves_qty: OrderQty(0),
            average_price: parent.limit_price(),
            ts_exchange_ns: 2,
            ts_recv_ns: 3,
            reason: RiskRejectReason::None,
            text: of_execution_core::ExecutionText::empty(),
        });
        let checkpoint = AlgoCheckpoint::new(parent, progress, 10, 99).expect("checkpoint");
        let plan = AlgoRecoveryPlan::new(checkpoint, AlgoRecoveryPolicy::default()).expect("plan");

        assert_eq!(plan.action(), AlgoRecoveryAction::CompleteParent);
    }

    #[test]
    fn recovery_plan_escalates_terminal_parent() {
        let parent = parent().with_status(ParentOrderStatus::Failed);
        let progress = AlgoProgress::new(parent.id(), parent.total_qty());
        let checkpoint = AlgoCheckpoint::new(parent, progress, 10, 99).expect("checkpoint");
        let policy = AlgoRecoveryPolicy::default()
            .with_pause_on_recovery(false)
            .with_require_reconciliation(false);
        let plan = AlgoRecoveryPlan::new(checkpoint, policy).expect("plan");

        assert_eq!(plan.action(), AlgoRecoveryAction::EscalateRisk);
    }

    #[test]
    fn simulator_fills_child_and_updates_progress() {
        let parent = parent();
        let child = ChildOrderPlan::new(
            ChildOrderId::new("sim-fill").expect("child"),
            parent.id(),
            parent.build_order_request(
                ClientOrderId::new("sim-fill-cl").expect("client"),
                OrderQty(10),
                1,
            ),
            1,
        )
        .expect("child");
        let simulator = AlgoSimulator::new(
            AlgoSimMarket::new(OrderQty(10), OrderPrice(500_025), false, false, 25)
                .expect("market"),
        );
        let step = simulator.simulate_child(&child, 1).expect("step");
        let mut progress = AlgoProgress::new(parent.id(), parent.total_qty());
        progress.on_child_released(&child).expect("release");
        progress.on_execution_event(&step.event());

        assert_eq!(step.outcome(), AlgoSimOutcome::Filled);
        assert_eq!(step.filled_qty(), OrderQty(10));
        assert_eq!(step.event().order_status, OrderStatus::Filled);
        assert_eq!(step.event().ts_recv_ns, 26);
        assert_eq!(progress.completed_qty(), OrderQty(10));
        assert_eq!(progress.open_qty(), OrderQty(0));
    }

    #[test]
    fn simulator_partially_fills_child() {
        let parent = parent();
        let child = ChildOrderPlan::new(
            ChildOrderId::new("sim-partial").expect("child"),
            parent.id(),
            parent.build_order_request(
                ClientOrderId::new("sim-partial-cl").expect("client"),
                OrderQty(25),
                1,
            ),
            1,
        )
        .expect("child");
        let simulator = AlgoSimulator::new(
            AlgoSimMarket::new(OrderQty(5), OrderPrice(500_000), false, false, 0).expect("market"),
        );
        let step = simulator.simulate_child(&child, 7).expect("step");

        assert_eq!(step.outcome(), AlgoSimOutcome::PartiallyFilled);
        assert_eq!(step.filled_qty(), OrderQty(5));
        assert_eq!(step.leaves_qty(), OrderQty(20));
        assert_eq!(step.event().order_status, OrderStatus::PartiallyFilled);
    }

    #[test]
    fn simulator_rejects_child() {
        let parent = parent();
        let child = ChildOrderPlan::new(
            ChildOrderId::new("sim-reject").expect("child"),
            parent.id(),
            parent.build_order_request(
                ClientOrderId::new("sim-reject-cl").expect("client"),
                OrderQty(10),
                1,
            ),
            1,
        )
        .expect("child");
        let simulator = AlgoSimulator::new(
            AlgoSimMarket::new(OrderQty(0), OrderPrice(0), true, false, 0).expect("market"),
        );
        let step = simulator.simulate_child(&child, 2).expect("step");

        assert_eq!(step.outcome(), AlgoSimOutcome::Rejected);
        assert_eq!(step.event().exec_type, ExecutionType::Reject);
        assert_eq!(step.event().order_status, OrderStatus::Rejected);
        assert_eq!(step.event().leaves_qty, OrderQty(10));
    }

    #[test]
    fn simulator_reports_decision_totals() {
        let parent = parent();
        let mut decision = AlgoDecision::<2>::new(1);
        for index in 1..=2 {
            let child = ChildOrderPlan::new(
                ChildOrderId::new(&format!("sim-d-{index}")).expect("child"),
                parent.id(),
                parent.build_order_request(
                    ClientOrderId::new(&format!("sim-d-cl-{index}")).expect("client"),
                    OrderQty(10),
                    index,
                ),
                index,
            )
            .expect("child");
            decision.push(AlgoAction::SubmitChild(child)).expect("push");
        }
        let simulator = AlgoSimulator::new(
            AlgoSimMarket::new(OrderQty(10), OrderPrice(500_000), false, true, 0).expect("market"),
        );
        let report = simulator
            .simulate_decision::<1, 2>(&decision, 10)
            .expect("report");

        assert!(report.truncated());
        assert_eq!(report.len(), 1);
        assert_eq!(report.total_filled_qty(), OrderQty(20));
        assert_eq!(report.cancelled_children(), 0);
    }

    #[test]
    fn metrics_accumulate_fill_quality() {
        let parent = parent();
        let child = ChildOrderPlan::new(
            ChildOrderId::new("met-fill").expect("child"),
            parent.id(),
            parent.build_order_request(
                ClientOrderId::new("met-fill-cl").expect("client"),
                OrderQty(10),
                1_000,
            ),
            1_000,
        )
        .expect("child");
        let mut metrics = AlgoMetricsAccumulator::new(
            &parent,
            AlgoTcaBenchmark::new(
                OrderPrice(500_000),
                OrderPrice(502_500),
                OrderPrice(501_000),
            )
            .expect("benchmark"),
        )
        .expect("metrics");
        metrics.on_child_submitted(&child);
        let step = AlgoSimulator::new(
            AlgoSimMarket::new(OrderQty(10), OrderPrice(505_000), false, false, 25)
                .expect("market"),
        )
        .simulate_child(&child, 1)
        .expect("step");
        metrics.on_execution_event(&step.event());
        let snapshot = metrics.snapshot();

        assert_eq!(snapshot.submitted_children(), 1);
        assert_eq!(snapshot.filled_children(), 1);
        assert_eq!(snapshot.completed_qty(), OrderQty(10));
        assert_eq!(snapshot.completion_bps(), 1_000);
        assert_eq!(snapshot.average_price(), OrderPrice(505_000));
        assert_eq!(snapshot.arrival_slippage_bps(), 100);
        assert_eq!(snapshot.average_latency_ns(), 25);
    }

    #[test]
    fn metrics_record_rejects_and_cancels() {
        let parent = parent();
        let rejected_child = ChildOrderPlan::new(
            ChildOrderId::new("met-reject").expect("child"),
            parent.id(),
            parent.build_order_request(
                ClientOrderId::new("met-reject-cl").expect("client"),
                OrderQty(10),
                1,
            ),
            1,
        )
        .expect("child");
        let cancelled_child = ChildOrderPlan::new(
            ChildOrderId::new("met-cancel").expect("child"),
            parent.id(),
            parent.build_order_request(
                ClientOrderId::new("met-cancel-cl").expect("client"),
                OrderQty(10),
                2,
            ),
            2,
        )
        .expect("child");
        let mut metrics = AlgoMetricsAccumulator::new(
            &parent,
            AlgoTcaBenchmark::new(OrderPrice(500_000), OrderPrice(0), OrderPrice(0))
                .expect("benchmark"),
        )
        .expect("metrics");
        metrics.on_child_submitted(&rejected_child);
        metrics.on_child_submitted(&cancelled_child);
        let reject = AlgoSimulator::new(
            AlgoSimMarket::new(OrderQty(0), OrderPrice(0), true, false, 0).expect("market"),
        )
        .simulate_child(&rejected_child, 1)
        .expect("reject");
        let cancel = AlgoSimulator::new(
            AlgoSimMarket::new(OrderQty(0), OrderPrice(500_000), false, true, 0).expect("market"),
        )
        .simulate_child(&cancelled_child, 2)
        .expect("cancel");
        metrics.on_execution_event(&reject.event());
        metrics.on_execution_event(&cancel.event());
        let snapshot = metrics.snapshot();

        assert_eq!(snapshot.submitted_children(), 2);
        assert_eq!(snapshot.rejected_children(), 1);
        assert_eq!(snapshot.cancelled_children(), 1);
        assert_eq!(snapshot.completed_qty(), OrderQty(0));
    }

    #[test]
    fn metrics_preserve_favorable_sell_slippage() {
        let parent = sell_parent("met-sell", OrderQty(100), OrderQty(10), OrderQty(25));
        let child = ChildOrderPlan::new(
            ChildOrderId::new("met-sell-child").expect("child"),
            parent.id(),
            parent.build_order_request(
                ClientOrderId::new("met-sell-cl").expect("client"),
                OrderQty(10),
                1,
            ),
            1,
        )
        .expect("child");
        let mut metrics = AlgoMetricsAccumulator::new(
            &parent,
            AlgoTcaBenchmark::new(OrderPrice(500_000), OrderPrice(0), OrderPrice(0))
                .expect("benchmark"),
        )
        .expect("metrics");
        metrics.on_child_submitted(&child);
        let step = AlgoSimulator::new(
            AlgoSimMarket::new(OrderQty(10), OrderPrice(505_000), false, false, 0).expect("market"),
        )
        .simulate_child(&child, 1)
        .expect("step");
        metrics.on_execution_event(&step.event());

        assert_eq!(metrics.snapshot().arrival_slippage_bps(), -100);
    }

    #[test]
    fn algo_config_builds_parent_and_policies() {
        let parent = parent();
        let config_parent = AlgoParentConfig::from_parent(parent);
        let risk_limits = AlgoRiskLimits::new(
            OrderQty(100),
            OrderQty(25),
            10_000_000,
            1_500,
            100,
            OrderQty(50),
            2,
            10,
        )
        .expect("risk");
        let recovery = AlgoRecoveryPolicy::default()
            .with_pause_on_recovery(false)
            .with_require_reconciliation(false);
        let config = AlgoConfig::new(AlgoKind::Twap, config_parent)
            .with_risk_limits(risk_limits)
            .with_recovery_policy(recovery);

        assert_eq!(config.kind(), AlgoKind::Twap);
        assert_eq!(config.to_parent_order().expect("parent"), parent);
        assert_eq!(config.to_risk_policy().limits(), risk_limits);
        assert_eq!(config.recovery_policy(), recovery);
    }

    #[test]
    fn algo_parent_config_rejects_invalid_schedule() {
        assert_eq!(
            AlgoParentConfig::new(
                ParentOrderId::new("cfg-bad").expect("id"),
                AccountId::new("acct").expect("account"),
                RouteId::new("sim").expect("route"),
                StrategyId::new("cfg").expect("strategy"),
                ExecutionSymbol::new("SIM", "ESZ6").expect("symbol"),
                OrderSide::Buy,
                OrderType::Limit,
                TimeInForce::Day,
                OrderQty(100),
                OrderPrice(500_000),
                OrderPrice(0),
                1_000,
                1_000,
                OrderQty(10),
                OrderQty(25),
                0,
            ),
            Err(AlgoError::InvalidTimeWindow)
        );
    }

    #[test]
    fn algo_config_supports_custom_kind() {
        let config = AlgoConfig::new(AlgoKind::Custom, AlgoParentConfig::from_parent(parent()));

        assert_eq!(config.kind(), AlgoKind::Custom);
        assert_eq!(
            config.recovery_policy(),
            AlgoRecoveryPolicy::new(true, true, true)
        );
        assert_eq!(config.risk_limits(), AlgoRiskLimits::unbounded());
    }

    #[test]
    fn progress_folds_fill_events() {
        let parent = parent();
        let mut progress = AlgoProgress::new(parent.id(), parent.total_qty());
        let plan = ChildOrderPlan::new(
            ChildOrderId::new("child-1").expect("child"),
            parent.id(),
            parent.build_order_request(
                ClientOrderId::new("cl-1").expect("client"),
                OrderQty(10),
                1,
            ),
            1,
        )
        .expect("plan");
        progress.on_child_released(&plan).expect("release");

        progress.on_execution_event(&ExecutionEvent {
            exec_type: of_execution_core::ExecutionType::Trade,
            order_status: OrderStatus::Filled,
            client_order_id: plan.request().client_order_id,
            orig_client_order_id: ClientOrderId::empty(),
            venue_order_id: VenueOrderId::new("venue-1").expect("venue"),
            execution_id: ExecutionId::new("exec-1").expect("exec"),
            account_id: parent.account_id(),
            route_id: parent.route_id(),
            symbol: parent.symbol(),
            last_qty: OrderQty(10),
            last_price: OrderPrice(500_000),
            cumulative_qty: OrderQty(10),
            leaves_qty: OrderQty(0),
            average_price: OrderPrice(500_000),
            ts_exchange_ns: 2,
            ts_recv_ns: 3,
            reason: RiskRejectReason::None,
            text: of_execution_core::ExecutionText::empty(),
        });

        assert_eq!(progress.completed_qty(), OrderQty(10));
        assert_eq!(progress.open_qty(), OrderQty(0));
        assert_eq!(progress.terminal_children(), 1);
    }

    #[test]
    fn invalid_parent_schedule_is_rejected() {
        assert_eq!(
            ParentOrder::new(
                ParentOrderId::new("parent-1").expect("id"),
                AccountId::new("acct").expect("account"),
                RouteId::new("sim").expect("route"),
                StrategyId::new("twap").expect("strategy"),
                ExecutionSymbol::new("SIM", "ESZ6").expect("symbol"),
                OrderSide::Buy,
                OrderType::Limit,
                TimeInForce::Day,
                OrderQty(100),
                OrderPrice(500_000),
                OrderPrice(0),
                10,
                10,
                OrderQty(10),
                OrderQty(25),
                0,
            ),
            Err(AlgoError::InvalidTimeWindow)
        );
    }

    #[test]
    fn replay_twap_is_deterministic() {
        let parent = parent();
        let planner = TwapSlicePlanner::new(1_000);
        let inputs = [
            AlgoReplayInput::new(
                1,
                AlgoReplayEvent::Timer {
                    timestamp_ns: 1_000,
                },
            ),
            AlgoReplayInput::new(
                2,
                AlgoReplayEvent::Timer {
                    timestamp_ns: 2_000,
                },
            ),
            AlgoReplayInput::new(
                3,
                AlgoReplayEvent::Timer {
                    timestamp_ns: 3_000,
                },
            ),
        ];
        let mut first_steps = Vec::new();
        let mut second_steps = Vec::new();
        let first = replay_twap_into::<DEFAULT_ALGO_DECISION_CAPACITY>(
            parent,
            planner,
            &inputs,
            AlgoReplayIdScheme::default(),
            &mut first_steps,
        )
        .expect("first replay");
        let second = replay_twap_into::<DEFAULT_ALGO_DECISION_CAPACITY>(
            parent,
            planner,
            &inputs,
            AlgoReplayIdScheme::default(),
            &mut second_steps,
        )
        .expect("second replay");

        assert_eq!(first, second);
        assert_eq!(first_steps, second_steps);
        assert_eq!(first.input_events(), 3);
        assert_eq!(first.submitted_children(), 3);
        assert_eq!(first.final_progress().released_qty(), OrderQty(30));
    }

    #[test]
    fn replay_folds_execution_events() {
        let parent = parent();
        let planner = TwapSlicePlanner::new(1_000);
        let fill = ExecutionEvent {
            exec_type: of_execution_core::ExecutionType::Trade,
            order_status: OrderStatus::Filled,
            client_order_id: ClientOrderId::new("cl-1").expect("client"),
            orig_client_order_id: ClientOrderId::empty(),
            venue_order_id: VenueOrderId::new("venue-1").expect("venue"),
            execution_id: ExecutionId::new("exec-1").expect("exec"),
            account_id: parent.account_id(),
            route_id: parent.route_id(),
            symbol: parent.symbol(),
            last_qty: OrderQty(10),
            last_price: OrderPrice(500_000),
            cumulative_qty: OrderQty(10),
            leaves_qty: OrderQty(0),
            average_price: OrderPrice(500_000),
            ts_exchange_ns: 2,
            ts_recv_ns: 3,
            reason: RiskRejectReason::None,
            text: of_execution_core::ExecutionText::empty(),
        };
        let inputs = [
            AlgoReplayInput::new(
                1,
                AlgoReplayEvent::Timer {
                    timestamp_ns: 1_000,
                },
            ),
            AlgoReplayInput::new(2, AlgoReplayEvent::Execution(fill)),
        ];
        let mut steps = Vec::new();
        let summary = replay_twap_into::<DEFAULT_ALGO_DECISION_CAPACITY>(
            parent,
            planner,
            &inputs,
            AlgoReplayIdScheme::default(),
            &mut steps,
        )
        .expect("replay");

        assert_eq!(summary.final_progress().released_qty(), OrderQty(10));
        assert_eq!(summary.final_progress().completed_qty(), OrderQty(10));
        assert_eq!(summary.final_progress().open_qty(), OrderQty(0));
        assert_eq!(steps[0].decision().len(), 1);
        assert!(steps[1].decision().is_empty());
    }

    #[test]
    fn replay_reports_decision_capacity_errors() {
        let parent = parent();
        let inputs = [AlgoReplayInput::new(
            1,
            AlgoReplayEvent::Timer {
                timestamp_ns: 1_000,
            },
        )];
        let mut steps = Vec::new();
        assert_eq!(
            replay_twap_into::<0>(
                parent,
                TwapSlicePlanner::new(1_000),
                &inputs,
                AlgoReplayIdScheme::default(),
                &mut steps,
            ),
            Err(AlgoError::DecisionFull { capacity: 0 })
        );
        assert!(steps.is_empty());
    }

    #[test]
    fn pov_plans_from_observed_volume() {
        let parent = parent();
        let planner = PovSlicePlanner::new(1_000, 1_500);
        let progress = AlgoProgress::new(parent.id(), parent.total_qty());

        let child = planner
            .plan_volume_slice(
                &parent,
                progress,
                OrderQty(1_000),
                2_000,
                ChildOrderId::new("child-pov").expect("child"),
                ClientOrderId::new("cl-pov").expect("client"),
                2_000,
            )
            .expect("plan")
            .expect("due");

        assert_eq!(child.request().quantity, parent.max_clip());
    }

    #[test]
    fn pov_waits_when_due_quantity_is_below_min_clip() {
        let parent = parent();
        let planner = PovSlicePlanner::new(1_000, 1_500);
        let progress = AlgoProgress::new(parent.id(), parent.total_qty());

        let child = planner
            .plan_volume_slice(
                &parent,
                progress,
                OrderQty(50),
                2_000,
                ChildOrderId::new("child-small").expect("child"),
                ClientOrderId::new("cl-small").expect("client"),
                2_000,
            )
            .expect("plan");

        assert!(child.is_none());
    }

    #[test]
    fn pov_rejects_parent_cap_below_target() {
        let capped_parent = parent().with_status(ParentOrderStatus::Active);
        let capped_parent = ParentOrder::new(
            capped_parent.id(),
            capped_parent.account_id(),
            capped_parent.route_id(),
            capped_parent.strategy_id(),
            capped_parent.symbol(),
            capped_parent.side(),
            capped_parent.order_type(),
            capped_parent.time_in_force(),
            capped_parent.total_qty(),
            capped_parent.limit_price(),
            capped_parent.stop_price(),
            capped_parent.start_ns(),
            capped_parent.end_ns(),
            capped_parent.min_clip(),
            capped_parent.max_clip(),
            500,
        )
        .expect("capped parent");
        let planner = PovSlicePlanner::new(1_000, 1_500);
        let progress = AlgoProgress::new(capped_parent.id(), capped_parent.total_qty());

        assert_eq!(
            planner.plan_volume_slice(
                &capped_parent,
                progress,
                OrderQty(1_000),
                2_000,
                ChildOrderId::new("child-cap").expect("child"),
                ClientOrderId::new("cl-cap").expect("client"),
                2_000,
            ),
            Err(AlgoError::InvalidParticipationRate)
        );
    }

    #[test]
    fn vwap_plans_from_cumulative_curve() {
        let parent = parent();
        let curve = VwapVolumeCurve::new(1_000, 1_000, &[10, 30, 60, 100]).expect("curve");
        let planner = VwapSlicePlanner::new(curve);
        let progress = AlgoProgress::new(parent.id(), parent.total_qty());

        let child = planner
            .plan_curve_slice(
                &parent,
                progress,
                2_000,
                ChildOrderId::new("child-vwap").expect("child"),
                ClientOrderId::new("cl-vwap").expect("client"),
                2_000,
            )
            .expect("plan")
            .expect("due");

        assert_eq!(child.request().quantity, OrderQty(25));
    }

    #[test]
    fn vwap_waits_for_min_clip() {
        let parent = parent();
        let curve = VwapVolumeCurve::new(1_000, 1_000, &[1, 2, 100]).expect("curve");
        let planner = VwapSlicePlanner::new(curve);
        let progress = AlgoProgress::new(parent.id(), parent.total_qty());

        let child = planner
            .plan_curve_slice(
                &parent,
                progress,
                1_000,
                ChildOrderId::new("child-small").expect("child"),
                ClientOrderId::new("cl-small").expect("client"),
                1_000,
            )
            .expect("plan");

        assert!(child.is_none());
    }

    #[test]
    fn vwap_rejects_invalid_curve() {
        assert_eq!(
            VwapVolumeCurve::new(1, 1, &[10, 9]),
            Err(AlgoError::InvalidVolumeProfile)
        );
        assert_eq!(
            VwapVolumeCurve::new(1, 0, &[10]),
            Err(AlgoError::InvalidVolumeProfile)
        );
    }

    #[test]
    fn iceberg_replenishes_when_open_quantity_is_at_threshold() {
        let parent = parent();
        let planner = IcebergSlicePlanner::new(OrderQty(20), OrderQty(0));
        let progress = AlgoProgress::new(parent.id(), parent.total_qty());

        let child = planner
            .plan_replenishment(
                &parent,
                progress,
                1_000,
                ChildOrderId::new("child-ice").expect("child"),
                ClientOrderId::new("cl-ice").expect("client"),
                1_000,
            )
            .expect("plan")
            .expect("due");

        assert_eq!(child.request().quantity, OrderQty(20));
    }

    #[test]
    fn iceberg_waits_while_display_quantity_is_working() {
        let parent = parent();
        let planner = IcebergSlicePlanner::new(OrderQty(20), OrderQty(0));
        let mut progress = AlgoProgress::new(parent.id(), parent.total_qty());
        let working = ChildOrderPlan::new(
            ChildOrderId::new("child-ice").expect("child"),
            parent.id(),
            parent.build_order_request(
                ClientOrderId::new("cl-ice").expect("client"),
                OrderQty(20),
                1,
            ),
            1,
        )
        .expect("child");
        progress.on_child_released(&working).expect("release");

        let child = planner
            .plan_replenishment(
                &parent,
                progress,
                2_000,
                ChildOrderId::new("child-next").expect("child"),
                ClientOrderId::new("cl-next").expect("client"),
                2_000,
            )
            .expect("plan");

        assert!(child.is_none());
    }

    #[test]
    fn iceberg_rejects_invalid_display_settings() {
        assert_eq!(
            IcebergSlicePlanner::try_new(OrderQty(0), OrderQty(0)),
            Err(AlgoError::InvalidDisplayQuantity)
        );
        assert_eq!(
            IcebergSlicePlanner::try_new(OrderQty(10), OrderQty(11)),
            Err(AlgoError::InvalidDisplayQuantity)
        );
    }

    #[test]
    fn passive_queue_joins_when_fill_probability_is_good() {
        let parent = parent();
        let planner = PassiveQueuePlanner::new(
            PassiveQueueConfig::new(PassivePegMode::SameSide, OrderPrice(25)).expect("config"),
        );
        let context = PassiveQueueContext::new(
            OrderPrice(499_975),
            OrderPrice(500_025),
            OrderQty(25),
            OrderQty(100),
            10,
        )
        .expect("context");
        let progress = AlgoProgress::new(parent.id(), parent.total_qty());

        let decision = planner
            .plan_passive_slice(
                &parent,
                progress,
                2_000,
                context,
                ChildOrderId::new("child-pq").expect("child"),
                ClientOrderId::new("cl-pq").expect("client"),
                2_000,
            )
            .expect("decision");

        assert_eq!(decision.action(), PassiveQueueAction::JoinQueue);
        let child = decision.child().expect("child");
        assert_eq!(child.request().limit_price, context.best_bid());
        assert_eq!(child.request().quantity, parent.max_clip());
        assert!(decision.estimate().fill_probability_bps() >= 2_500);
    }

    #[test]
    fn passive_queue_improves_when_queue_is_unlikely_to_fill() {
        let parent = parent();
        let config = PassiveQueueConfig::new(PassivePegMode::SameSide, OrderPrice(25))
            .expect("config")
            .with_thresholds(2_500, 250, 1_500)
            .expect("thresholds")
            .with_max_improvement_ticks(1);
        let planner = PassiveQueuePlanner::new(config);
        let context = PassiveQueueContext::new(
            OrderPrice(499_950),
            OrderPrice(500_050),
            OrderQty(10_000),
            OrderQty(10),
            10,
        )
        .expect("context");
        let progress = AlgoProgress::new(parent.id(), parent.total_qty());

        let decision = planner
            .plan_passive_slice(
                &parent,
                progress,
                2_000,
                context,
                ChildOrderId::new("child-imp").expect("child"),
                ClientOrderId::new("cl-imp").expect("client"),
                2_000,
            )
            .expect("decision");

        assert_eq!(decision.action(), PassiveQueueAction::ImprovePrice);
        let child = decision.child().expect("child");
        assert_eq!(child.request().limit_price, OrderPrice(499_975));
        assert!(child.request().limit_price.0 < context.best_ask().0);
    }

    #[test]
    fn passive_queue_waits_when_adverse_selection_is_high() {
        let parent = parent();
        let planner = PassiveQueuePlanner::new(
            PassiveQueueConfig::new(PassivePegMode::SameSide, OrderPrice(25)).expect("config"),
        );
        let context = PassiveQueueContext::new(
            OrderPrice(499_975),
            OrderPrice(500_025),
            OrderQty(0),
            OrderQty(100),
            1_000,
        )
        .expect("context");

        let decision = planner
            .plan_passive_slice(
                &parent,
                AlgoProgress::new(parent.id(), parent.total_qty()),
                2_000,
                context,
                ChildOrderId::new("child-wait").expect("child"),
                ClientOrderId::new("cl-wait").expect("client"),
                2_000,
            )
            .expect("decision");

        assert_eq!(decision.action(), PassiveQueueAction::Wait);
        assert!(decision.child().is_none());
    }

    #[test]
    fn passive_queue_can_cross_when_allowed_and_late() {
        let parent = parent();
        let config = PassiveQueueConfig::new(PassivePegMode::SameSide, OrderPrice(25))
            .expect("config")
            .with_crossing(true, 8_000)
            .expect("crossing");
        let planner = PassiveQueuePlanner::new(config);
        let context = PassiveQueueContext::new(
            OrderPrice(499_975),
            OrderPrice(500_025),
            OrderQty(10_000),
            OrderQty(0),
            10,
        )
        .expect("context");

        let decision = planner
            .plan_passive_slice(
                &parent,
                AlgoProgress::new(parent.id(), parent.total_qty()),
                10_000,
                context,
                ChildOrderId::new("child-cross").expect("child"),
                ClientOrderId::new("cl-cross").expect("client"),
                10_000,
            )
            .expect("decision");

        assert_eq!(decision.action(), PassiveQueueAction::CrossSpread);
        assert_eq!(
            decision.child().expect("child").request().limit_price,
            context.best_ask()
        );
    }

    #[test]
    fn passive_queue_rejects_invalid_context() {
        assert_eq!(
            PassiveQueueConfig::new(PassivePegMode::SameSide, OrderPrice(0)),
            Err(AlgoError::InvalidPassiveQueueParameters)
        );
        assert_eq!(
            PassiveQueueContext::new(OrderPrice(10), OrderPrice(10), OrderQty(0), OrderQty(0), 0),
            Err(AlgoError::InvalidPassiveQueueParameters)
        );
    }

    #[test]
    fn sor_prefers_better_scored_route() {
        let parent = parent();
        let planner = SorPlanner::new(SorConfig::default());
        let candidates = [
            SorRouteCandidate::new(
                RouteId::new("slow").expect("route"),
                OrderPrice(500_050),
                OrderQty(25),
            )
            .expect("candidate")
            .with_metrics(SorRouteMetrics::new(0, 2_000, 200, 4_000, 100, 9_000).expect("metrics")),
            SorRouteCandidate::new(
                RouteId::new("fast").expect("route"),
                OrderPrice(499_975),
                OrderQty(25),
            )
            .expect("candidate")
            .with_metrics(SorRouteMetrics::new(0, 100, 0, 9_000, 10, 10_000).expect("metrics")),
        ];
        let child_ids = [
            ChildOrderId::new("child-sor-1").expect("child"),
            ChildOrderId::new("child-sor-2").expect("child"),
        ];
        let client_ids = [
            ClientOrderId::new("cl-sor-1").expect("client"),
            ClientOrderId::new("cl-sor-2").expect("client"),
        ];

        let decision = planner
            .plan_routes::<2>(
                &parent,
                AlgoProgress::new(parent.id(), parent.total_qty()),
                2_000,
                &candidates,
                &child_ids,
                &client_ids,
                2_000,
            )
            .expect("decision");

        let first = decision.allocations().next().expect("allocation");
        assert_eq!(
            first.plan().request().route_id,
            RouteId::new("fast").expect("route")
        );
        assert_eq!(first.plan().request().limit_price, OrderPrice(499_975));
    }

    #[test]
    fn sor_splits_across_routes_until_max_clip_is_reached() {
        let parent = parent();
        let planner = SorPlanner::new(SorConfig::new(3, SorScoreWeights::default()).expect("cfg"));
        let candidates = [
            SorRouteCandidate::new(
                RouteId::new("r1").expect("route"),
                OrderPrice(499_975),
                OrderQty(10),
            )
            .expect("candidate")
            .with_metrics(SorRouteMetrics::new(0, 0, 0, 10_000, 0, 10_000).expect("metrics")),
            SorRouteCandidate::new(
                RouteId::new("r2").expect("route"),
                OrderPrice(499_980),
                OrderQty(30),
            )
            .expect("candidate")
            .with_metrics(SorRouteMetrics::new(0, 0, 0, 1_000, 0, 10_000).expect("metrics")),
        ];
        let child_ids = [
            ChildOrderId::new("child-r1").expect("child"),
            ChildOrderId::new("child-r2").expect("child"),
            ChildOrderId::new("child-r3").expect("child"),
        ];
        let client_ids = [
            ClientOrderId::new("cl-r1").expect("client"),
            ClientOrderId::new("cl-r2").expect("client"),
            ClientOrderId::new("cl-r3").expect("client"),
        ];

        let decision = planner
            .plan_routes::<3>(
                &parent,
                AlgoProgress::new(parent.id(), parent.total_qty()),
                2_000,
                &candidates,
                &child_ids,
                &client_ids,
                2_000,
            )
            .expect("decision");

        let qty: i64 = decision
            .allocations()
            .map(|allocation| allocation.plan().request().quantity.0)
            .sum();
        assert_eq!(decision.len(), 2);
        assert_eq!(qty, parent.max_clip().0);
    }

    #[test]
    fn sor_skips_blocked_and_unsupported_routes() {
        let parent = parent();
        let planner = SorPlanner::new(SorConfig::default());
        let candidates = [
            SorRouteCandidate::new(
                RouteId::new("blocked").expect("route"),
                OrderPrice(499_900),
                OrderQty(25),
            )
            .expect("candidate")
            .with_status(SorRouteStatus::Blocked),
            SorRouteCandidate::new(
                RouteId::new("market-only").expect("route"),
                OrderPrice(499_925),
                OrderQty(25),
            )
            .expect("candidate")
            .with_capability(SorRouteCapability::new(false, true)),
            SorRouteCandidate::new(
                RouteId::new("limit-ok").expect("route"),
                OrderPrice(500_000),
                OrderQty(25),
            )
            .expect("candidate"),
        ];
        let child_ids = [ChildOrderId::new("child-ok").expect("child")];
        let client_ids = [ClientOrderId::new("cl-ok").expect("client")];

        let decision = planner
            .plan_routes::<1>(
                &parent,
                AlgoProgress::new(parent.id(), parent.total_qty()),
                2_000,
                &candidates,
                &child_ids,
                &client_ids,
                2_000,
            )
            .expect("decision");

        let allocation = decision.allocations().next().expect("allocation");
        assert_eq!(
            allocation.plan().request().route_id,
            RouteId::new("limit-ok").expect("route")
        );
    }

    #[test]
    fn sor_requires_enough_caller_owned_ids() {
        let parent = parent();
        let planner = SorPlanner::new(SorConfig::default());
        let candidates = [SorRouteCandidate::new(
            RouteId::new("route").expect("route"),
            OrderPrice(500_000),
            OrderQty(25),
        )
        .expect("candidate")];

        assert_eq!(
            planner.plan_routes::<1>(
                &parent,
                AlgoProgress::new(parent.id(), parent.total_qty()),
                2_000,
                &candidates,
                &[],
                &[],
                2_000,
            ),
            Err(AlgoError::InvalidSorParameters)
        );
    }

    #[test]
    fn liquidity_seeker_takes_high_fill_route() {
        let parent = parent();
        let config =
            LiquiditySeekingConfig::new(2, OrderQty(5), 0, 7_500, 1_500, 3, 4).expect("config");
        let planner = LiquiditySeekingPlanner::new(config, SorConfig::default());
        let route = SorRouteCandidate::new(
            RouteId::new("lit").expect("route"),
            OrderPrice(499_975),
            OrderQty(25),
        )
        .expect("route")
        .with_metrics(SorRouteMetrics::new(0, 100, 0, 9_000, 100, 10_000).expect("metrics"));
        let candidates =
            [LiquiditySeekingCandidate::new(route, 500, 25, OrderQty(0)).expect("candidate")];
        let child_ids = [ChildOrderId::new("liq-child").expect("child")];
        let client_ids = [ClientOrderId::new("liq-cl").expect("client")];

        let decision = planner
            .plan_liquidity::<1>(
                &parent,
                AlgoProgress::new(parent.id(), parent.total_qty()),
                2_000,
                &candidates,
                &child_ids,
                &client_ids,
                2_000,
            )
            .expect("decision");

        let allocation = decision.allocations().next().expect("allocation");
        assert_eq!(allocation.action(), LiquiditySeekingAction::Take);
        assert_eq!(allocation.plan().request().quantity, parent.max_clip());
        assert_eq!(allocation.plan().request().route_id, route.route_id());
    }

    #[test]
    fn liquidity_seeker_probes_lower_fill_hidden_route() {
        let parent = parent();
        let config =
            LiquiditySeekingConfig::new(1, OrderQty(10), 0, 7_500, 1_500, 3, 4).expect("config");
        let planner = LiquiditySeekingPlanner::new(config, SorConfig::default());
        let route = SorRouteCandidate::new(
            RouteId::new("dark").expect("route"),
            OrderPrice(500_000),
            OrderQty(100),
        )
        .expect("route")
        .with_metrics(SorRouteMetrics::new(0, 200, 0, 4_000, 100, 9_000).expect("metrics"));
        let candidates =
            [LiquiditySeekingCandidate::new(route, 2_500, 50, OrderQty(10)).expect("candidate")];
        let child_ids = [ChildOrderId::new("probe-child").expect("child")];
        let client_ids = [ClientOrderId::new("probe-cl").expect("client")];

        let decision = planner
            .plan_liquidity::<1>(
                &parent,
                AlgoProgress::new(parent.id(), parent.total_qty()),
                2_000,
                &candidates,
                &child_ids,
                &client_ids,
                2_000,
            )
            .expect("decision");

        let allocation = decision.allocations().next().expect("allocation");
        assert_eq!(allocation.action(), LiquiditySeekingAction::Probe);
        assert_eq!(allocation.plan().request().quantity, OrderQty(10));
    }

    #[test]
    fn liquidity_seeker_skips_toxic_routes() {
        let parent = parent();
        let planner = LiquiditySeekingPlanner::new(
            LiquiditySeekingConfig::new(1, OrderQty(10), 0, 7_500, 500, 3, 4).expect("config"),
            SorConfig::default(),
        );
        let route = SorRouteCandidate::new(
            RouteId::new("toxic").expect("route"),
            OrderPrice(499_975),
            OrderQty(100),
        )
        .expect("route")
        .with_metrics(SorRouteMetrics::new(0, 100, 0, 9_000, 1_000, 10_000).expect("metrics"));
        let candidates =
            [LiquiditySeekingCandidate::new(route, 0, 0, OrderQty(0)).expect("candidate")];
        let child_ids = [ChildOrderId::new("skip-child").expect("child")];
        let client_ids = [ClientOrderId::new("skip-cl").expect("client")];

        let decision = planner
            .plan_liquidity::<1>(
                &parent,
                AlgoProgress::new(parent.id(), parent.total_qty()),
                2_000,
                &candidates,
                &child_ids,
                &client_ids,
                2_000,
            )
            .expect("decision");

        assert!(decision.is_empty());
        assert_eq!(decision.skipped_routes(), 1);
    }

    #[test]
    fn liquidity_seeker_rejects_invalid_inputs() {
        assert_eq!(
            LiquiditySeekingConfig::new(0, OrderQty(1), 0, 0, 0, 0, 0),
            Err(AlgoError::InvalidLiquiditySeekingParameters)
        );
        let route = SorRouteCandidate::new(
            RouteId::new("route").expect("route"),
            OrderPrice(500_000),
            OrderQty(1),
        )
        .expect("route");
        assert_eq!(
            LiquiditySeekingCandidate::new(route, 10_001, 0, OrderQty(0)),
            Err(AlgoError::InvalidLiquiditySeekingParameters)
        );
    }

    #[test]
    fn sweep_walks_buy_levels_until_clip_or_collar() {
        let parent = parent();
        let planner =
            SweepPlanner::new(SweepConfig::new(3, OrderPrice(500_025), OrderQty(0)).expect("cfg"));
        let candidates = [
            SorRouteCandidate::new(
                RouteId::new("r2").expect("route"),
                OrderPrice(500_000),
                OrderQty(10),
            )
            .expect("candidate"),
            SorRouteCandidate::new(
                RouteId::new("r1").expect("route"),
                OrderPrice(499_975),
                OrderQty(10),
            )
            .expect("candidate"),
            SorRouteCandidate::new(
                RouteId::new("r3").expect("route"),
                OrderPrice(500_050),
                OrderQty(10),
            )
            .expect("candidate"),
        ];
        let child_ids = [
            ChildOrderId::new("sw-1").expect("child"),
            ChildOrderId::new("sw-2").expect("child"),
            ChildOrderId::new("sw-3").expect("child"),
        ];
        let client_ids = [
            ClientOrderId::new("sw-cl-1").expect("client"),
            ClientOrderId::new("sw-cl-2").expect("client"),
            ClientOrderId::new("sw-cl-3").expect("client"),
        ];

        let decision = planner
            .plan_sweep::<3>(
                &parent,
                AlgoProgress::new(parent.id(), parent.total_qty()),
                2_000,
                &candidates,
                &child_ids,
                &client_ids,
                2_000,
            )
            .expect("decision");

        assert_eq!(decision.len(), 2);
        assert_eq!(decision.total_qty(), OrderQty(20));
        assert!(decision.collar_reached());
        let prices: Vec<i64> = decision
            .allocations()
            .map(|allocation| allocation.plan().request().limit_price.0)
            .collect();
        assert_eq!(prices, vec![499_975, 500_000]);
    }

    #[test]
    fn sweep_respects_sell_side_collar() {
        let sell_parent = ParentOrder::new(
            ParentOrderId::new("parent-sweep-sell").expect("id"),
            AccountId::new("acct").expect("account"),
            RouteId::new("sim").expect("route"),
            StrategyId::new("sweep").expect("strategy"),
            ExecutionSymbol::new("SIM", "ESZ6").expect("symbol"),
            OrderSide::Sell,
            OrderType::Limit,
            TimeInForce::Day,
            OrderQty(100),
            OrderPrice(500_000),
            OrderPrice(0),
            1_000,
            11_000,
            OrderQty(10),
            OrderQty(25),
            0,
        )
        .expect("parent");
        let planner =
            SweepPlanner::new(SweepConfig::new(2, OrderPrice(499_975), OrderQty(0)).expect("cfg"));
        let candidates = [
            SorRouteCandidate::new(
                RouteId::new("sell-good").expect("route"),
                OrderPrice(500_025),
                OrderQty(25),
            )
            .expect("candidate"),
            SorRouteCandidate::new(
                RouteId::new("sell-bad").expect("route"),
                OrderPrice(499_950),
                OrderQty(25),
            )
            .expect("candidate"),
        ];
        let child_ids = [
            ChildOrderId::new("sell-sw-1").expect("child"),
            ChildOrderId::new("sell-sw-2").expect("child"),
        ];
        let client_ids = [
            ClientOrderId::new("sell-cl-1").expect("client"),
            ClientOrderId::new("sell-cl-2").expect("client"),
        ];

        let decision = planner
            .plan_sweep::<2>(
                &sell_parent,
                AlgoProgress::new(sell_parent.id(), sell_parent.total_qty()),
                2_000,
                &candidates,
                &child_ids,
                &client_ids,
                2_000,
            )
            .expect("decision");

        assert_eq!(decision.len(), 1);
        assert_eq!(
            decision
                .allocations()
                .next()
                .expect("allocation")
                .plan()
                .request()
                .limit_price,
            OrderPrice(500_025)
        );
        assert!(decision.collar_reached());
    }

    #[test]
    fn sweep_suppresses_decision_below_min_fill() {
        let parent = parent();
        let planner =
            SweepPlanner::new(SweepConfig::new(1, OrderPrice(500_000), OrderQty(20)).expect("cfg"));
        let candidates = [SorRouteCandidate::new(
            RouteId::new("small").expect("route"),
            OrderPrice(499_975),
            OrderQty(10),
        )
        .expect("candidate")];
        let child_ids = [ChildOrderId::new("small-sw").expect("child")];
        let client_ids = [ClientOrderId::new("small-cl").expect("client")];

        let decision = planner
            .plan_sweep::<1>(
                &parent,
                AlgoProgress::new(parent.id(), parent.total_qty()),
                2_000,
                &candidates,
                &child_ids,
                &client_ids,
                2_000,
            )
            .expect("decision");

        assert!(decision.is_empty());
    }

    #[test]
    fn sweep_rejects_invalid_config() {
        assert_eq!(
            SweepConfig::new(0, OrderPrice(1), OrderQty(0)),
            Err(AlgoError::InvalidSweepParameters)
        );
        assert_eq!(
            SweepConfig::new(1, OrderPrice(0), OrderQty(0)),
            Err(AlgoError::InvalidSweepParameters)
        );
    }

    #[test]
    fn basket_plans_synchronized_due_legs() {
        let first = BasketLeg::new(parent(), BasketLegRole::Primary, 10_000).expect("leg");
        let second_parent = ParentOrder::new(
            ParentOrderId::new("parent-2").expect("id"),
            AccountId::new("acct").expect("account"),
            RouteId::new("hedge").expect("route"),
            StrategyId::new("basket").expect("strategy"),
            ExecutionSymbol::new("SIM", "NQZ6").expect("symbol"),
            OrderSide::Sell,
            OrderType::Limit,
            TimeInForce::Day,
            OrderQty(50),
            OrderPrice(1_800_000),
            OrderPrice(0),
            1_000,
            11_000,
            OrderQty(5),
            OrderQty(20),
            0,
        )
        .expect("parent");
        let second = BasketLeg::new(second_parent, BasketLegRole::Hedge, -5_000).expect("leg");
        let legs = [first, second];
        let progresses = [
            AlgoProgress::new(first.parent().id(), first.parent().total_qty()),
            AlgoProgress::new(second.parent().id(), second.parent().total_qty()),
        ];
        let child_ids = [
            ChildOrderId::new("child-b1").expect("child"),
            ChildOrderId::new("child-b2").expect("child"),
        ];
        let client_ids = [
            ClientOrderId::new("cl-b1").expect("client"),
            ClientOrderId::new("cl-b2").expect("client"),
        ];

        let decision = BasketPlanner::new()
            .plan_synchronized_slice::<2>(&legs, &progresses, 6_000, &child_ids, &client_ids, 6_000)
            .expect("decision");

        assert_eq!(decision.len(), 2);
        let quantities: Vec<i64> = decision
            .allocations()
            .map(|allocation| allocation.plan().request().quantity.0)
            .collect();
        assert_eq!(quantities, vec![25, 20]);
    }

    #[test]
    fn basket_blocks_terminal_legs_without_releasing() {
        let terminal_parent = parent().with_status(ParentOrderStatus::Cancelled);
        let leg = BasketLeg::new(terminal_parent, BasketLegRole::Primary, 10_000).expect("leg");
        let progress = AlgoProgress::new(terminal_parent.id(), terminal_parent.total_qty());
        let child_ids = [ChildOrderId::new("child-b").expect("child")];
        let client_ids = [ClientOrderId::new("cl-b").expect("client")];

        let decision = BasketPlanner::new()
            .plan_synchronized_slice::<1>(
                &[leg],
                &[progress],
                6_000,
                &child_ids,
                &client_ids,
                6_000,
            )
            .expect("decision");

        assert!(decision.is_empty());
        assert_eq!(decision.blocked_legs(), 1);
    }

    #[test]
    fn basket_rejects_mismatched_inputs() {
        let leg = BasketLeg::new(parent(), BasketLegRole::Primary, 10_000).expect("leg");
        assert_eq!(
            BasketPlanner::new().plan_synchronized_slice::<1>(&[leg], &[], 6_000, &[], &[], 6_000),
            Err(AlgoError::InvalidBasketParameters)
        );
        assert_eq!(
            BasketLeg::new(parent(), BasketLegRole::Primary, 0),
            Err(AlgoError::InvalidBasketParameters)
        );
    }

    #[test]
    fn spread_plans_when_edge_meets_limit() {
        let buy_parent = parent();
        let sell_parent = sell_parent("spread-sell-1", OrderQty(100), OrderQty(10), OrderQty(25));
        let planner = SpreadPlanner::new(SpreadConfig::new(10_000, 50).expect("config"));
        let decision = planner
            .plan_spread(
                &buy_parent,
                AlgoProgress::new(buy_parent.id(), buy_parent.total_qty()),
                &sell_parent,
                AlgoProgress::new(sell_parent.id(), sell_parent.total_qty()),
                2_000,
                SpreadQuote::new(OrderPrice(500_000), OrderPrice(505_000)).expect("quote"),
                ChildOrderId::new("sp-buy").expect("child"),
                ClientOrderId::new("sp-buy-cl").expect("client"),
                ChildOrderId::new("sp-sell").expect("child"),
                ClientOrderId::new("sp-sell-cl").expect("client"),
                2_000,
            )
            .expect("decision");

        assert!(decision.estimate().executable());
        assert_eq!(decision.estimate().edge_bps(), 100);
        let buy = decision.buy().expect("buy");
        let sell = decision.sell().expect("sell");
        assert_eq!(buy.request().side, OrderSide::Buy);
        assert_eq!(sell.request().side, OrderSide::Sell);
        assert_eq!(buy.request().quantity, OrderQty(25));
        assert_eq!(sell.request().quantity, OrderQty(25));
        assert_eq!(buy.request().limit_price, OrderPrice(500_000));
        assert_eq!(sell.request().limit_price, OrderPrice(505_000));
    }

    #[test]
    fn spread_waits_when_edge_is_below_limit() {
        let buy_parent = parent();
        let sell_parent = sell_parent("spread-sell-2", OrderQty(100), OrderQty(10), OrderQty(25));
        let planner = SpreadPlanner::new(SpreadConfig::new(10_000, 50).expect("config"));
        let decision = planner
            .plan_spread(
                &buy_parent,
                AlgoProgress::new(buy_parent.id(), buy_parent.total_qty()),
                &sell_parent,
                AlgoProgress::new(sell_parent.id(), sell_parent.total_qty()),
                2_000,
                SpreadQuote::new(OrderPrice(500_000), OrderPrice(500_500)).expect("quote"),
                ChildOrderId::new("sp-wait-buy").expect("child"),
                ClientOrderId::new("sp-wait-buy-cl").expect("client"),
                ChildOrderId::new("sp-wait-sell").expect("child"),
                ClientOrderId::new("sp-wait-sell-cl").expect("client"),
                2_000,
            )
            .expect("decision");

        assert!(!decision.estimate().executable());
        assert!(decision.buy().is_none());
        assert!(decision.sell().is_none());
    }

    #[test]
    fn spread_sizes_by_ratio_and_available_leaves() {
        let buy_parent = parent();
        let sell_parent = sell_parent("spread-sell-3", OrderQty(8), OrderQty(1), OrderQty(8));
        let planner = SpreadPlanner::new(SpreadConfig::new(5_000, 100).expect("config"));
        let decision = planner
            .plan_spread(
                &buy_parent,
                AlgoProgress::new(buy_parent.id(), buy_parent.total_qty()),
                &sell_parent,
                AlgoProgress::new(sell_parent.id(), sell_parent.total_qty()),
                2_000,
                SpreadQuote::new(OrderPrice(500_000), OrderPrice(1_100_000)).expect("quote"),
                ChildOrderId::new("sp-ratio-buy").expect("child"),
                ClientOrderId::new("sp-ratio-buy-cl").expect("client"),
                ChildOrderId::new("sp-ratio-sell").expect("child"),
                ClientOrderId::new("sp-ratio-sell-cl").expect("client"),
                2_000,
            )
            .expect("decision");

        assert_eq!(decision.estimate().buy_qty(), OrderQty(16));
        assert_eq!(decision.estimate().sell_qty(), OrderQty(8));
        assert_eq!(
            decision.buy().expect("buy").request().quantity,
            OrderQty(16)
        );
        assert_eq!(
            decision.sell().expect("sell").request().quantity,
            OrderQty(8)
        );
    }

    #[test]
    fn spread_rejects_invalid_inputs() {
        assert_eq!(
            SpreadConfig::new(0, 0),
            Err(AlgoError::InvalidSpreadParameters)
        );
        assert_eq!(
            SpreadQuote::new(OrderPrice(0), OrderPrice(1)),
            Err(AlgoError::InvalidSpreadParameters)
        );
        let buy_parent = parent();
        let wrong_side_parent = ParentOrder::new(
            ParentOrderId::new("spread-wrong").expect("id"),
            AccountId::new("acct").expect("account"),
            RouteId::new("sim").expect("route"),
            StrategyId::new("spread").expect("strategy"),
            ExecutionSymbol::new("SIM", "NQZ6").expect("symbol"),
            OrderSide::Buy,
            OrderType::Limit,
            TimeInForce::Day,
            OrderQty(100),
            OrderPrice(1_000_000),
            OrderPrice(0),
            1_000,
            11_000,
            OrderQty(10),
            OrderQty(25),
            0,
        )
        .expect("wrong side");

        assert_eq!(
            SpreadPlanner::new(SpreadConfig::new(10_000, 0).expect("config")).estimate(
                &buy_parent,
                AlgoProgress::new(buy_parent.id(), buy_parent.total_qty()),
                &wrong_side_parent,
                AlgoProgress::new(wrong_side_parent.id(), wrong_side_parent.total_qty()),
                SpreadQuote::new(OrderPrice(500_000), OrderPrice(505_000)).expect("quote"),
            ),
            Err(AlgoError::InvalidSpreadParameters)
        );
    }

    #[test]
    fn market_maker_quotes_both_sides_around_fair_value() {
        let template = parent();
        let config = MarketMakerConfig::new(
            OrderPrice(25),
            OrderQty(5),
            20,
            2,
            1_000,
            1_000,
            5_000,
            5_000,
        )
        .expect("config");
        let planner = MarketMakerPlanner::new(config);
        let context = MarketMakerContext::new(
            OrderPrice(500_000),
            OrderPrice(499_975),
            OrderPrice(500_025),
            OrderQty(0),
            OrderQty(100),
            10,
            10,
        )
        .expect("context");

        let decision = planner
            .plan_quotes(
                &template,
                2_000,
                context,
                ChildOrderId::new("mm-bid").expect("child"),
                ClientOrderId::new("mm-bid-cl").expect("client"),
                ChildOrderId::new("mm-ask").expect("child"),
                ClientOrderId::new("mm-ask-cl").expect("client"),
                2_000,
            )
            .expect("decision");

        let bid = decision.bid().expect("bid");
        let ask = decision.ask().expect("ask");
        assert_eq!(bid.request().side, OrderSide::Buy);
        assert_eq!(ask.request().side, OrderSide::Sell);
        assert!(bid.request().limit_price.0 < ask.request().limit_price.0);
        assert_eq!(bid.request().quantity, OrderQty(5));
        assert_eq!(ask.request().quantity, OrderQty(5));
    }

    #[test]
    fn market_maker_suppresses_bid_at_long_inventory_limit() {
        let template = parent();
        let planner = MarketMakerPlanner::new(MarketMakerConfig::default());
        let context = MarketMakerContext::new(
            OrderPrice(500_000),
            OrderPrice(499_975),
            OrderPrice(500_025),
            OrderQty(100),
            OrderQty(100),
            0,
            0,
        )
        .expect("context");

        let decision = planner
            .plan_quotes(
                &template,
                2_000,
                context,
                ChildOrderId::new("mm-bid").expect("child"),
                ClientOrderId::new("mm-bid-cl").expect("client"),
                ChildOrderId::new("mm-ask").expect("child"),
                ClientOrderId::new("mm-ask-cl").expect("client"),
                2_000,
            )
            .expect("decision");

        assert!(decision.bid().is_none());
        assert!(decision.ask().is_some());
        assert!(decision.estimate().adjusted_fair_value().0 < context.fair_value().0);
    }

    #[test]
    fn market_maker_rejects_invalid_parameters() {
        assert_eq!(
            MarketMakerConfig::new(OrderPrice(0), OrderQty(1), 10, 1, 100, 0, 0, 0),
            Err(AlgoError::InvalidMarketMakingParameters)
        );
        assert_eq!(
            MarketMakerContext::new(
                OrderPrice(1),
                OrderPrice(10),
                OrderPrice(9),
                OrderQty(0),
                OrderQty(1),
                0,
                0
            ),
            Err(AlgoError::InvalidMarketMakingParameters)
        );
    }

    #[test]
    fn shortfall_front_loads_on_adverse_buy_move() {
        let parent = parent();
        let planner = ImplementationShortfallPlanner::new(ImplementationShortfallConfig::default());
        let context = ImplementationShortfallContext::new(
            OrderPrice(500_000),
            OrderPrice(510_000),
            200,
            20,
            10,
        )
        .expect("context");
        let progress = AlgoProgress::new(parent.id(), parent.total_qty());
        let estimate = planner
            .estimate(&parent, progress, 1_000, context)
            .expect("estimate");

        assert!(estimate.adverse_move_bps() > 0);
        assert!(estimate.urgency_bps() > 1_000);
        assert!(estimate.target_release_qty().0 > 0);
        let child = planner
            .plan_shortfall_slice(
                &parent,
                progress,
                1_000,
                context,
                ChildOrderId::new("child-is").expect("child"),
                ClientOrderId::new("cl-is").expect("client"),
                1_000,
            )
            .expect("plan")
            .expect("due");
        assert!(child.request().quantity.0 >= parent.min_clip().0);
        assert!(child.request().quantity.0 <= parent.max_clip().0);
    }

    #[test]
    fn shortfall_high_impact_can_wait_below_min_clip() {
        let parent = parent();
        let config =
            ImplementationShortfallConfig::new(100, 1_000, 0, 0, 0, 10_000).expect("config");
        let planner = ImplementationShortfallPlanner::new(config);
        let context = ImplementationShortfallContext::new(
            OrderPrice(500_000),
            OrderPrice(500_000),
            0,
            0,
            500,
        )
        .expect("context");
        let progress = AlgoProgress::new(parent.id(), parent.total_qty());

        let child = planner
            .plan_shortfall_slice(
                &parent,
                progress,
                1_000,
                context,
                ChildOrderId::new("child-wait").expect("child"),
                ClientOrderId::new("cl-wait").expect("client"),
                1_000,
            )
            .expect("plan");

        assert!(child.is_none());
    }

    #[test]
    fn shortfall_detects_adverse_sell_move() {
        let sell_parent = ParentOrder::new(
            ParentOrderId::new("parent-sell").expect("id"),
            AccountId::new("acct").expect("account"),
            RouteId::new("sim").expect("route"),
            StrategyId::new("is").expect("strategy"),
            ExecutionSymbol::new("SIM", "ESZ6").expect("symbol"),
            OrderSide::Sell,
            OrderType::Limit,
            TimeInForce::Day,
            OrderQty(100),
            OrderPrice(500_000),
            OrderPrice(0),
            1_000,
            11_000,
            OrderQty(10),
            OrderQty(25),
            0,
        )
        .expect("parent");
        let planner = ImplementationShortfallPlanner::new(ImplementationShortfallConfig::default());
        let context = ImplementationShortfallContext::new(
            OrderPrice(500_000),
            OrderPrice(490_000),
            50,
            10,
            0,
        )
        .expect("context");
        let estimate = planner
            .estimate(
                &sell_parent,
                AlgoProgress::new(sell_parent.id(), sell_parent.total_qty()),
                2_000,
                context,
            )
            .expect("estimate");

        assert!(estimate.adverse_move_bps() > 0);
        assert!(estimate.target_release_qty().0 > 10);
    }

    #[test]
    fn shortfall_rejects_invalid_parameters() {
        assert_eq!(
            ImplementationShortfallConfig::new(8_000, 7_000, 0, 0, 0, 0),
            Err(AlgoError::InvalidShortfallParameters)
        );
        assert_eq!(
            ImplementationShortfallContext::new(OrderPrice(0), OrderPrice(1), 0, 0, 0),
            Err(AlgoError::InvalidShortfallParameters)
        );
    }
}