ironcondor 0.5.0

High-performance backtesting engine for options trading strategies with order-book-level fill simulation. Built on OptionStratLib.
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
//! The realistic fill model: the `option-chain-orderbook` adapter (v0.2,
//! feature `orderbook`, issue #22).
//!
//! [`RealisticFill`] routes each `Submit` intent through a real options
//! matching engine ([`option_chain_orderbook`] on top of `orderbook-rs`), so
//! queue position, per-strike depth, and market impact are **properties of the
//! matching**, not configured offsets
//! ([docs/04 §5](../../../docs/04-execution-models.md),
//! [ADR-0002](../../../docs/adr/0002-order-book-level-fill-simulation.md)). It
//! is the **only** seam where `option_chain_orderbook` newtypes appear and
//! **no raw `f64` crosses it** — everything is integer cents scaled to the
//! book's `u128` ticks.
//!
//! # What this issue (#22) builds
//!
//! The adapter foundation: leaf-book construction, seeded `OrderId` generation
//! from disjoint ranges, cents↔tick scaling, the side+action→Buy/Sell mapping,
//! marketable-limit conversion, submission + per-level fill capture, and the
//! `option_chain_orderbook::Error` → [`BacktestError`] mapping. Per-strike book
//! **seeding from a snapshot** (#023) and queue/impact goldens (#024) build on
//! top; the **between-snapshot refresh** (#025, [`RealisticFill::refresh_books`])
//! rebuilds the seeded liquidity every step and captures refresh-generated fills;
//! the mode switch (#026) is next. [`RealisticFill::seed_maker_limit`] and
//! [`RealisticFill::next_maker_order_id`] are the seeding primitives #023
//! consumes.
//!
//! # Both modes emit the identical [`Fill`] shape
//!
//! Every fill is stamped by the shared [`assemble_fill`] exactly as the naive
//! model's is, so a naive fill and a realistic fill of the same intent are
//! byte-shape identical and only their values differ. A marketable order that
//! walks several price levels yields **one [`Fill`] per level** (each at that
//! level's executed price and size), the first carrying the once-per-order fee
//! ([`FeeCharge::FirstFill`]) and every later level only per-contract fees
//! ([`FeeCharge::LaterFill`]) — this is `LaterFill`'s first production use.
//!
//! # Determinism
//!
//! `OrderId`s come from **seeded [`Id::Sequential`] counters**, never
//! `Id::new`/`new_uuid` (which are random —
//! [rules/global_rules.md](../../../rules/global_rules.md) "Determinism"). Leaf
//! books live in a `BTreeMap` (never a `HashMap`), submission order is fixed,
//! and the fill path is synchronous with **no `.await`** — the book is driven
//! in-process (`nats`/`sequencer` features off). Same `(seed, config, data)` ⇒
//! byte-identical fills.
//!
//! # DEVIATIONS from the v0.7.0-era spec (for architect review)
//!
//! The pinned [`docs/specs/option-chain-orderbook.md`] describes v0.7.0; the
//! resolved crate is **0.9.1**. Two deliberate deviations:
//!
//! 1. **Capture via `add_limit_order_full`, not
//!    `arm_trade_capture`/`last_trade_result`.** The `_full` methods (0.8.0+)
//!    return *this call's own* [`TradeResult`] directly, avoiding the
//!    single-slot last-write-wins footgun of the shared-capture API. The
//!    per-level fill data is identical (the `TradeResult` trade list); the
//!    `_full` path is simply race-free and needs no arm/poll dance.
//! 2. **Marketable submits use GTC + explicit `cancel_order`, not an IOC
//!    time-in-force.** This matches the spec's literal "cancel the unfilled
//!    remainder (IOC)" wording and is *forced* by upstream capture semantics:
//!    on an unfillable **IOC** remainder the `_full`/`_with_result` methods
//!    return a typed error and route the fills to the trade listener **only**,
//!    so a partial marketable walk submitted IOC would lose its captured fills.
//!    Submitting **GTC** fills up to the aggressive-limit cap, rests the
//!    remainder, and returns `Ok` with every fill in the call's own
//!    [`TradeResult`]; the adapter then discards the resting remainder with
//!    `cancel_order` when the intent is IOC. Deterministic, and no fill is lost.
//!
//! # optionstratlib version shim (for architect review)
//!
//! `OptionOrderBook::new(symbol, OptionStyle)` takes an
//! `optionstratlib::OptionStyle` **by value**, and the published crate (0.9.1)
//! pins optionstratlib `^0.17` while `ironcondor` is on 0.18. The resolver
//! keeps two optionstratlib copies; this module names the 0.17 `OptionStyle`
//! (aliased [`ObOptionStyle`]) **only** to construct leaf books, converting from
//! the crate's 0.18 [`OptionStyle`] with a trivial `Call`/`Put` match. Remove
//! the `optionstratlib_ob` shim once the matching crate republishes on
//! optionstratlib 0.18 (or re-exports `OptionStyle`).

use std::collections::BTreeMap;
use std::collections::btree_map::Entry;

use option_chain_orderbook::{OptionOrderBook, OrderId as ObOrderId, Side as ObSide, TradeResult};
use optionstratlib::{OptionStyle, Side};
use optionstratlib_ob::OptionStyle as ObOptionStyle;

use crate::config::{FeeSchedule, LiquidityProfile};
use crate::domain::{
    ChainSnapshot, ContractKey, ExecutionMode, Fill, OrderCommand, OrderId, OrderIntent,
    PriceCents, Quantity, QuoteView, TimeInForce,
};
use crate::error::BacktestError;

use super::{
    CarryGroup, ExecutionModel, FeeCharge, FillDraft, FillGroup, assemble_fill, liquidity,
};

/// The first strategy `OrderId`. Strategy ids occupy the low range
/// `[STRATEGY_ID_BASE, MAKER_ID_BASE)`; a handle at or above [`MAKER_ID_BASE`]
/// is out of the strategy's range and rejected.
const STRATEGY_ID_BASE: u64 = 1;

/// The first seeded-maker `OrderId`. Seeded-maker ids occupy the high range
/// `[MAKER_ID_BASE, u64::MAX]`, **disjoint** from strategy ids, so #023's
/// liquidity never collides with strategy orders. `1 << 48` leaves ~2.8·10¹⁴
/// strategy ids below and ~2.1·10¹⁴ maker ids above.
pub(crate) const MAKER_ID_BASE: u64 = 1 << 48;

/// The realistic fill model: routes intents through per-contract leaf
/// [`OptionOrderBook`]s and reads fills back as the shared [`Fill`].
///
/// Holds the two config values it needs ([`FeeSchedule`], the marketable price
/// cap), the run `seed` (the reproducibility anchor), two **disjoint** seeded
/// `OrderId` counters, and a `BTreeMap` of leaf books keyed by [`ContractKey`]
/// (deterministic iteration; #023 seeds these). It does **not** derive
/// `Clone`/`PartialEq`: an [`OptionOrderBook`] carries live matching state that
/// must not be duplicated.
pub struct RealisticFill {
    /// The fee schedule stamped onto each fill.
    fees: FeeSchedule,
    /// Marketable price cap in ticks off the touch (`config.marketable_cap_ticks`).
    marketable_cap_ticks: u32,
    /// The run seed — the reproducibility anchor. #023's ladder seeding is a
    /// pure function of the profile, quotes, and tick and draws no RNG; the
    /// seed is retained for any later seeded-RNG liquidity model.
    seed: u64,
    /// Next strategy `OrderId` (low, disjoint range).
    next_strategy_id: u64,
    /// Next seeded-maker `OrderId` (high, disjoint range).
    next_maker_id: u64,
    /// The per-strike book-seeding profile (#023). `None` is the **raw
    /// adapter** — no auto-seeding or refresh, books are hand-built via
    /// [`Self::seed_maker_limit`]; `Some` reseeds from **every** snapshot
    /// [`Self::fill`] sees (#025). The config-driven engine path always supplies
    /// `Some(config.liquidity_profile)` (reproducible from the manifest).
    liquidity_profile: Option<LiquidityProfile>,
    /// The seeded-maker order ids still **resting** in each leaf book, in stable
    /// key order — the exact set the next snapshot's refresh cancels (#025). A
    /// snapshot is the only ground truth for depth, so every step cancels these
    /// and reseeds fresh. Reused across steps: each `Vec` is **cleared in place**
    /// (capacity retained) at cancel time, then refilled by the reseed, so this
    /// tracking state itself allocates nothing steady-state
    /// ([docs/07 §4](../../../docs/07-performance-and-security.md)). (The reseed's
    /// per-order [`OptionOrderBook::add_limit_order_full`] still returns an owned
    /// `TradeResult` whose `symbol` `String` allocates per call upstream — the one
    /// residual per-step allocation on this path, profiled and addressed in #029;
    /// the realistic path is not covered by the naive zero-alloc gate.) Only the
    /// **auto-reseed** path records here; hand-seeded depth
    /// ([`Self::seed_maker_limit`]) is untracked and never auto-cancelled.
    resting_seed_ids: BTreeMap<ContractKey, Vec<u64>>,
    /// Metadata for **strategy** limit orders currently resting in a leaf book,
    /// keyed by their book-`OrderId` sequence value (strategy-id range). Just
    /// enough to assemble a refresh-generated [`Fill`] when a reseed order
    /// crosses one (#025): its trade side, its decision-time mid (the slippage
    /// reference), how much is still resting, and whether its first fill has
    /// been charged the per-order fee. Never a `HashMap` — a `BTreeMap` keeps the
    /// refresh deterministic. An entry is removed once fully consumed **by a
    /// refresh cross** (the e1 path).
    resting_strategy: BTreeMap<u64, RestingStrategyOrder>,
    /// The engine-`OrderId` → book-sequence bridge for resting strategy orders
    /// (#110): `Cancel`/`Replace` name the engine id, the book knows only its
    /// own `Sequential` value, and this map joins them. Entries live exactly as
    /// long as the mirrored [`RestingStrategyOrder`] they point at.
    order_index: BTreeMap<OrderId, u64>,
    /// The refresh-fill → resting-order correlation for the most recent
    /// [`Self::fill`] call — one [`CarryGroup`] per refresh-generated fill, in
    /// emission order (the contiguous e1 prefix of `out_fills`). **Reusable
    /// scratch:** cleared in place each `fill` (capacity retained).
    carry_groups: Vec<CarryGroup>,
    /// Count of live resting strategy orders per contract — the incremental
    /// membership index the eviction predicate consults in O(log L) instead of
    /// scanning `resting_strategy` per book (#110 review: keeps a rolling
    /// universe linear in the live set). Maintained at mirror insert/remove;
    /// an entry is dropped at count 0.
    live_orders: BTreeMap<ContractKey, u32>,
    /// Reusable scratch for the per-step reseed plan — sized once, cleared in
    /// place by [`liquidity::plan_seed_into`] each refresh, so the refresh's own
    /// plan buffer never reallocates ([docs/07 §4](../../../docs/07-performance-and-security.md)).
    seed_plan: Vec<liquidity::SeedOrder>,
    /// The fill→order grouping for the most recent [`Self::fill`] call — one
    /// [`FillGroup`] per `Submit` (e2) that produced at least one fill, in
    /// command order (the fill→order correlation channel the engine reads via
    /// [`Self::fill_groups`]). A marketable order walking `n` price levels appends
    /// `n` fills and one group of `fill_count = n`, so the engine mints one
    /// order/position for it and assigns `fill_seq = 0..n`. **Reusable scratch:**
    /// cleared in place each `fill` (capacity retained), so it adds no
    /// steady-state allocation. Refresh-generated fills (e1) carry **no** group
    /// (they belong to a prior-step resting order, not a current command).
    fill_groups: Vec<FillGroup>,
    /// Per-contract leaf books, in stable key order (never a `HashMap`).
    books: BTreeMap<ContractKey, OptionOrderBook>,
}

/// A resting **strategy** limit order the refresh must be able to fill when a
/// later snapshot's reseed depth crosses it (#025).
///
/// The book owns the order's identity, price, and queue position; this carries
/// only what the shared [`assemble_fill`] needs that the book cannot re-derive —
/// the trade `side` and the original `decision_mid` — plus the `remaining`
/// resting size (to know when the order is exhausted) and `first_fill_done` (so
/// the once-per-order fee is charged exactly once, on the order's first fill,
/// whether that happened at submit or on a later refresh).
#[derive(Debug, Clone, PartialEq, Eq)]
struct RestingStrategyOrder {
    /// The engine-minted domain [`OrderId`] this resting order answers to — the
    /// identity a [`CarryGroup`] names so the engine can apply a refresh fill to
    /// the leg the order opens or closes (#110).
    order_id: OrderId,
    /// The order's contract — locates its leaf book for `Cancel`/`Replace` and
    /// gates eviction (a book holding a live strategy order is never evicted).
    contract: ContractKey,
    /// The order's trade side (`Long` = buy, `Short` = sell) — the slippage sign
    /// and the assembled fill's side.
    side: Side,
    /// The decision-time mid the order was submitted against — the slippage
    /// reference, invariant across refreshes.
    decision_mid: PriceCents,
    /// Contracts still resting (decremented as refresh fills consume it).
    remaining: u64,
    /// Whether the order's first fill has already carried the per-order fee.
    first_fill_done: bool,
}

impl std::fmt::Debug for RealisticFill {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // `OptionOrderBook` holds live matching state with no useful `Debug`;
        // report the book count, not the books.
        f.debug_struct("RealisticFill")
            .field("fees", &self.fees)
            .field("marketable_cap_ticks", &self.marketable_cap_ticks)
            .field("seed", &self.seed)
            .field("next_strategy_id", &self.next_strategy_id)
            .field("next_maker_id", &self.next_maker_id)
            .field("liquidity_profile", &self.liquidity_profile)
            .field("resting_seed_ids", &self.resting_seed_ids.len())
            .field("resting_strategy", &self.resting_strategy.len())
            .field("order_index", &self.order_index.len())
            .field("carry_groups", &self.carry_groups.len())
            .field("fill_groups", &self.fill_groups.len())
            .field("books", &self.books.len())
            .finish()
    }
}

impl RealisticFill {
    /// Build a **raw-adapter** realistic fill model — no automatic book
    /// seeding.
    ///
    /// The seeded `OrderId` counters start at their disjoint range bases; the
    /// leaf-book map starts empty. With no [`LiquidityProfile`], [`Self::fill`]
    /// routes against whatever depth the caller hand-builds via
    /// [`Self::seed_maker_limit`] — the constructor tests and the raw #022
    /// adapter path use. For the config-driven, snapshot-seeded model use
    /// [`Self::with_liquidity_profile`]. `marketable_cap_ticks` must be `> 0` —
    /// [`crate::config::BacktestConfig::validate`] guarantees it.
    #[must_use = "the constructed fill model must be used to produce fills"]
    pub fn new(fees: FeeSchedule, marketable_cap_ticks: u32, seed: u64) -> Self {
        Self {
            fees,
            marketable_cap_ticks,
            seed,
            next_strategy_id: STRATEGY_ID_BASE,
            next_maker_id: MAKER_ID_BASE,
            liquidity_profile: None,
            resting_seed_ids: BTreeMap::new(),
            resting_strategy: BTreeMap::new(),
            order_index: BTreeMap::new(),
            carry_groups: Vec::new(),
            live_orders: BTreeMap::new(),
            seed_plan: Vec::new(),
            fill_groups: Vec::new(),
            books: BTreeMap::new(),
        }
    }

    /// Build a realistic fill model that **reseeds** each strike's book from
    /// **every** snapshot per `profile` (#023 first-seed + #025 refresh).
    ///
    /// Identical to [`Self::new`] but carries the [`LiquidityProfile`] the
    /// engine reads from `config.liquidity_profile`, so [`Self::fill`] seeds the
    /// per-strike ladders (touch + `L` deeper levels, geometric decay) **before**
    /// routing the step's commands — a strategy order then queues behind the
    /// seeded depth at its entry step ([docs/04 §6](../../../docs/04-execution-models.md)).
    /// On every later snapshot the stale seed is cancelled and fresh depth is
    /// reseeded from that snapshot's quotes, so synthetic depth never accumulates
    /// ([docs/04 §6.1](../../../docs/04-execution-models.md)). The profile is
    /// recorded in the run config, so the seeded book is reproducible from the
    /// manifest.
    #[must_use = "the constructed fill model must be used to produce fills"]
    pub fn with_liquidity_profile(
        fees: FeeSchedule,
        marketable_cap_ticks: u32,
        seed: u64,
        profile: LiquidityProfile,
    ) -> Self {
        Self {
            fees,
            marketable_cap_ticks,
            seed,
            next_strategy_id: STRATEGY_ID_BASE,
            next_maker_id: MAKER_ID_BASE,
            liquidity_profile: Some(profile),
            resting_seed_ids: BTreeMap::new(),
            resting_strategy: BTreeMap::new(),
            order_index: BTreeMap::new(),
            carry_groups: Vec::new(),
            live_orders: BTreeMap::new(),
            seed_plan: Vec::new(),
            fill_groups: Vec::new(),
            books: BTreeMap::new(),
        }
    }

    /// The run seed — the reproducibility anchor. #023's ladder seeding draws
    /// no RNG; the seed is retained for a later seeded-RNG liquidity model.
    #[must_use]
    pub const fn seed(&self) -> u64 {
        self.seed
    }

    /// Mint the next **strategy** `OrderId` from the low seeded range.
    ///
    /// # Errors
    ///
    /// Returns [`BacktestError::Execution`] when the strategy range is
    /// exhausted (the counter reached [`MAKER_ID_BASE`]) — a strategy handle
    /// must never stray into the seeded-maker range.
    fn next_strategy_order_id(&mut self) -> Result<ObOrderId, BacktestError> {
        let id = self.next_strategy_id;
        if id >= MAKER_ID_BASE {
            return Err(BacktestError::Execution(format!(
                "strategy order id range exhausted at {id} (maker range begins at {MAKER_ID_BASE})"
            )));
        }
        // `id < MAKER_ID_BASE`, so `+ 1` cannot overflow `u64`.
        self.next_strategy_id = id + 1;
        Ok(ObOrderId::Sequential(id))
    }

    /// Mint the next **seeded-maker** `OrderId` from the high seeded range —
    /// the id source #023's liquidity seeding draws from.
    ///
    /// # Errors
    ///
    /// Returns [`BacktestError::Execution`] when the maker range is exhausted
    /// (the `u64` counter would wrap).
    pub(crate) fn next_maker_order_id(&mut self) -> Result<ObOrderId, BacktestError> {
        let id = self.next_maker_id;
        let next = id.checked_add(1).ok_or_else(|| {
            BacktestError::Execution("seeded-maker order id range exhausted".to_string())
        })?;
        self.next_maker_id = next;
        Ok(ObOrderId::Sequential(id))
    }

    /// Get (or lazily construct) the leaf [`OptionOrderBook`] for `contract`.
    ///
    /// The book is keyed by the contract's identity and constructed with its
    /// canonical `contract_id` symbol and 0.18→0.17 [`OptionStyle`] conversion.
    ///
    /// # Errors
    ///
    /// Returns [`BacktestError::Conversion`] when the contract's expiration is
    /// unresolved (cannot form a `contract_id`).
    fn leaf_book(&mut self, contract: &ContractKey) -> Result<&OptionOrderBook, BacktestError> {
        leaf_book_in(&mut self.books, contract)
    }

    /// Seed one resting maker limit into `contract`'s leaf book — the #023
    /// liquidity primitive, and how tests hand-build depth.
    ///
    /// `is_ask` rests a sell (ask) at `price`; `!is_ask` a bid (buy). The order
    /// carries a seeded-maker `OrderId` from the disjoint high range, rests
    /// (`TimeInForce::Gtc`), and — into an empty side — produces no fill.
    /// Prices are integer cents scaled to the book's `u128` ticks via
    /// `tick_size_cents`. (Refresh-generated fills from a seed crossing a
    /// resting strategy order are #025 scope, not this primitive's.)
    ///
    /// # Errors
    ///
    /// Returns [`BacktestError::PriceNotTickAligned`] when `price` is not a
    /// multiple of `tick_size_cents`, [`BacktestError::Execution`] when the
    /// maker id range is exhausted or the tick is zero,
    /// [`BacktestError::Conversion`] when the contract's expiration is
    /// unresolved, and [`BacktestError::OrderBook`] when the book rejects the
    /// order.
    pub fn seed_maker_limit(
        &mut self,
        contract: &ContractKey,
        is_ask: bool,
        price: PriceCents,
        quantity: Quantity,
        tick_size_cents: PriceCents,
    ) -> Result<(), BacktestError> {
        let tick = tick_size_cents.value();
        let price_ticks = cents_to_ticks(price, tick)?;
        let qty = u64::from(quantity.value());
        let side = if is_ask { ObSide::Sell } else { ObSide::Buy };
        let id = self.next_maker_order_id()?;
        let book = self.leaf_book(contract)?;
        book.add_limit_order(id, side, price_ticks, qty)?;
        Ok(())
    }

    /// The between-snapshot book refresh — phase **e1** of the step, run before
    /// the step's command fills (#025,
    /// [docs/04 §6.1](../../../docs/04-execution-models.md),
    /// [docs/02 §3.2](../../../docs/02-engine-architecture.md)).
    ///
    /// A snapshot is the only ground truth for depth, so when a
    /// [`LiquidityProfile`] is configured this **cancels every seeded-maker order
    /// still resting from the previous snapshot** and **reseeds fresh depth from
    /// `snap`**, in the fixed plan order (ascending [`ContractKey`], bid side
    /// before ask side). A reseed order that **crosses** a resting strategy limit
    /// matches it on add; each such match is captured from the reseed call's own
    /// `TradeResult` and appended to `out_fills` as a step-`n` refresh fill —
    /// this is how a resting order fills as the market moves onto it between
    /// steps. On the **first** snapshot the cancel step finds nothing resting, so
    /// it degenerates to the initial seed (#023). A no-op for the raw adapter
    /// (`liquidity_profile = None`): its hand-seeded depth is left untouched.
    ///
    /// **Strategy orders are never cancelled or reinserted** here — only their
    /// seeded-maker neighbours are — so a resting strategy order keeps its
    /// original `OrderId` and rest timestamp, and therefore its **aged price-time
    /// priority ahead of** the freshly reseeded depth ([docs/04 §6.1](../../../docs/04-execution-models.md) step 5).
    ///
    /// The ladder is a deterministic function of `(profile, quotes, tick)`; no
    /// RNG is drawn, so the run `seed` is not consumed here.
    ///
    /// # Errors
    ///
    /// Returns [`BacktestError::Execution`] when the tick is zero or a maker id
    /// range is exhausted, [`BacktestError::PriceNotTickAligned`] for a
    /// mis-aligned quote, [`BacktestError::ArithmeticOverflow`] on cents/size
    /// overflow, [`BacktestError::OrderBook`] when the book rejects an order, and
    /// [`BacktestError::Conversion`] for an unresolved expiration.
    fn refresh_books(
        &mut self,
        snap: &ChainSnapshot,
        out_fills: &mut Vec<Fill>,
    ) -> Result<(), BacktestError> {
        // Raw adapter: no auto-reseed, and no auto-tracked seed to cancel — the
        // hand-built book is left exactly as the caller left it.
        let Some(profile) = self.liquidity_profile else {
            return Ok(());
        };
        let tick = snap.spec.tick_size_cents.value();
        if tick == 0 {
            // Defence in depth: `InstrumentSpec` validates `tick > 0` at ingest.
            return Err(BacktestError::Execution(
                "instrument tick_size_cents is zero at the realistic refresh".to_string(),
            ));
        }
        // 1. Cancel every stale seeded-maker order (empty on the first snapshot
        //    ⇒ a plain initial seed). Strategy ids are never touched.
        self.cancel_stale_seed()?;
        // 1b. Evict departed contracts (#110): a book whose contract left the
        //     snapshot universe AND holds no live resting strategy order is
        //     removed (with its seed-id slot), so a rolling option universe
        //     bounds per-refresh work at O(active universe + live orders). A
        //     book with a live strategy order is NEVER evicted — the working
        //     order (and its aged price-time priority) lives inside it. The
        //     retain predicates scan `resting_strategy` per key instead of
        //     building a scratch set: allocation-free, and both maps are
        //     bounded by the active universe after this very step.
        {
            let Self {
                books,
                resting_seed_ids,
                live_orders,
                ..
            } = self;
            books.retain(|contract, _| {
                snap.quotes.contains_key(contract) || live_orders.contains_key(contract)
            });
            resting_seed_ids.retain(|contract, _| {
                snap.quotes.contains_key(contract) || live_orders.contains_key(contract)
            });
        }
        // 2. Reseed fresh depth in the fixed plan order, capturing any
        //    refresh-generated fills of resting strategy limits the reseed
        //    crosses. The scratch plan buffer is moved out and back so the
        //    reseed can drive `&mut self` freely without a self-borrow clash;
        //    the buffer's capacity is retained across steps.
        let mut plan = std::mem::take(&mut self.seed_plan);
        let outcome = self.reseed(&mut plan, snap, &profile, tick, out_fills);
        self.seed_plan = plan;
        outcome
    }

    /// Cancel every seeded-maker order still resting from the previous snapshot,
    /// clearing each per-book id list **in place** (capacity retained) so the
    /// reseed can refill it without allocating.
    ///
    /// Only seeded-maker ids are cancelled (strategy ids never enter
    /// `resting_seed_ids`); an id the book already consumed cancels to
    /// `Ok(false)`, which is fine.
    ///
    /// # Errors
    ///
    /// Returns [`BacktestError::OrderBook`] when a cancel is rejected by the book.
    fn cancel_stale_seed(&mut self) -> Result<(), BacktestError> {
        let Self {
            books,
            resting_seed_ids,
            ..
        } = self;
        for (contract, ids) in resting_seed_ids.iter_mut() {
            if let Some(book) = books.get(contract) {
                for &id in ids.iter() {
                    // `Ok(false)` = already gone (fully filled); `Err` propagates.
                    let _cancelled = book.cancel_order(ObOrderId::Sequential(id))?;
                }
            }
            ids.clear();
        }
        Ok(())
    }

    /// Reseed fresh depth from `snap` in the fixed plan order, recording each
    /// resting reseed order for the next snapshot's cancel and capturing any
    /// refresh-generated fills of resting strategy limits the reseed crosses.
    ///
    /// # Errors
    ///
    /// Propagates every [`liquidity::plan_seed_into`], scaling, book, and fill
    /// assembly error.
    fn reseed(
        &mut self,
        plan: &mut Vec<liquidity::SeedOrder>,
        snap: &ChainSnapshot,
        profile: &LiquidityProfile,
        tick: u64,
        out_fills: &mut Vec<Fill>,
    ) -> Result<(), BacktestError> {
        liquidity::plan_seed_into(snap, profile, plan)?;
        for order in plan.iter() {
            let price_ticks = cents_to_ticks(order.price, tick)?;
            let side = if order.is_ask {
                ObSide::Sell
            } else {
                ObSide::Buy
            };
            let qty = u64::from(order.size.value());
            // Mint the seeded-maker id BEFORE borrowing the book (disjoint borrows).
            let id = self.next_maker_order_id()?;
            let trade_result: TradeResult = {
                let book = leaf_book_in(&mut self.books, &order.contract)?;
                book.add_limit_order_full(id, side, price_ticks, qty)?
            };
            // A reseed order can only cross a RESTING STRATEGY limit (stale seed
            // was cancelled above, and same-side reseed levels never cross each
            // other), so each trade fills a strategy maker — capture it against
            // `snap` (one `Fill` per level).
            for trade in trade_result.match_result.trades().as_vec() {
                self.capture_refresh_fill(
                    trade.maker_order_id(),
                    trade.price().as_u128(),
                    trade.quantity().as_u64(),
                    &order.contract,
                    tick,
                    snap,
                    out_fills,
                )?;
            }
            // Record the reseed order as resting seed liquidity when any of it
            // rests, so the next snapshot's refresh cancels exactly it. A reseed
            // order fully consumed by a strategy cross rests nothing and is not
            // tracked (there is nothing to cancel).
            if trade_result.match_result.remaining_quantity().as_u64() > 0
                && let ObOrderId::Sequential(seq) = id
            {
                self.resting_seed_ids
                    .entry(order.contract.clone())
                    .or_default()
                    .push(seq);
            }
        }
        Ok(())
    }

    /// Assemble and append one refresh-generated [`Fill`] for the strategy limit
    /// a reseed order just crossed, identified by the trade's **maker** id.
    ///
    /// The trade executes at the resting strategy order's own price (price-time
    /// priority), so `trade_price_ticks` scales straight to the fill price and
    /// the stored `side` / `decision_mid` fix the slippage. The once-per-order
    /// fee rides the strategy order's **first** fill (whether at submit or here),
    /// tracked by `first_fill_done`; the entry is dropped once fully consumed.
    /// A trade whose maker is not a tracked strategy order (e.g. a seeded id) is
    /// ignored.
    ///
    /// # Errors
    ///
    /// Returns [`BacktestError::ArithmeticOverflow`] on tick→cents or size
    /// narrowing overflow, [`BacktestError::Execution`] when a matched quantity
    /// exceeds the strategy order's tracked resting size (a book/tracking
    /// desync), and propagates fee/slippage errors from [`assemble_fill`].
    #[allow(clippy::too_many_arguments)]
    fn capture_refresh_fill(
        &mut self,
        maker_id: ObOrderId,
        trade_price_ticks: u128,
        trade_qty: u64,
        contract: &ContractKey,
        tick: u64,
        snap: &ChainSnapshot,
        out_fills: &mut Vec<Fill>,
    ) -> Result<(), BacktestError> {
        let ObOrderId::Sequential(maker_seq) = maker_id else {
            return Ok(());
        };
        if !self.resting_strategy.contains_key(&maker_seq) {
            // Not a tracked strategy order — nothing to record.
            return Ok(());
        }
        let exec_price = ticks_to_cents(trade_price_ticks, tick)?;
        let matched = u32::try_from(trade_qty).map_err(|_| BacktestError::ArithmeticOverflow)?;
        let quantity = Quantity::new(matched)?;
        // Read + update the strategy order's state in a scoped borrow so the fee
        // schedule (a disjoint field) is free for `assemble_fill` afterwards.
        let (engine_order_id, side, decision_mid, charge, exhausted) = {
            let Some(meta) = self.resting_strategy.get_mut(&maker_seq) else {
                return Ok(());
            };
            let charge = if meta.first_fill_done {
                FeeCharge::LaterFill
            } else {
                FeeCharge::FirstFill
            };
            meta.first_fill_done = true;
            // `checked_sub`, not `saturating_sub`: a match larger than the resting
            // size is a book/tracking desync, and must surface as a typed error
            // rather than being silently clamped to 0 (global_rules.md — never
            // saturating on a counter). `trade_qty <= remaining` always holds while
            // the book and this mirror agree.
            meta.remaining = meta.remaining.checked_sub(trade_qty).ok_or_else(|| {
                BacktestError::Execution(
                    "refresh matched more than the strategy order's resting size \
                     (book/tracking desync)"
                        .to_string(),
                )
            })?;
            (
                meta.order_id,
                meta.side,
                meta.decision_mid,
                charge,
                meta.remaining == 0,
            )
        };
        let draft = FillDraft {
            ts: snap.ts,
            step: snap.step,
            contract: contract.clone(),
            side,
            quantity,
            price: exec_price,
            decision_mid,
        };
        out_fills.push(assemble_fill(
            draft,
            ExecutionMode::Realistic,
            &self.fees,
            charge,
        )?);
        // Coalesce contiguous same-order refresh fills into ONE carry group
        // (one resting order crossed by several reseed levels in a single
        // refresh — its crossings are contiguous in `out_fills` because a
        // contract's ladder is contiguous in the plan): the engine then
        // VWAP-aggregates the group into one leg / one close, matching the e2
        // command path's granularity.
        if let Some(last) = self.carry_groups.last_mut()
            && last.order_id == engine_order_id
        {
            last.fill_count = last
                .fill_count
                .checked_add(1)
                .ok_or(BacktestError::ArithmeticOverflow)?;
        } else {
            self.carry_groups.push(CarryGroup {
                order_id: engine_order_id,
                fill_count: 1,
            });
        }
        if exhausted {
            if let Some(meta) = self.resting_strategy.remove(&maker_seq) {
                Self::release_live_order(&mut self.live_orders, &meta.contract)?;
            }
            self.order_index.remove(&engine_order_id);
        }
        Ok(())
    }

    /// Route one `Submit` intent through its leaf book and append one
    /// [`Fill`] per executed price level to `out_fills`.
    ///
    /// # Errors
    ///
    /// Returns [`BacktestError::Execution`] when a marketable intent's contract
    /// is not quoted (no touch to price off) or the tick is zero,
    /// [`BacktestError::PriceNotTickAligned`] when a limit price is off the tick
    /// grid, [`BacktestError::ArithmeticOverflow`] on cents/size overflow,
    /// [`BacktestError::OrderBook`] when the book rejects the order, and
    /// propagates fee/slippage errors from [`assemble_fill`].
    fn fill_submit(
        &mut self,
        intent: &OrderIntent,
        engine_order_id: OrderId,
        snap: &ChainSnapshot,
        out_fills: &mut Vec<Fill>,
    ) -> Result<(), BacktestError> {
        let tick = snap.spec.tick_size_cents.value();
        if tick == 0 {
            // Defence in depth: `InstrumentSpec` validates `tick > 0` at ingest.
            return Err(BacktestError::Execution(
                "instrument tick_size_cents is zero at the realistic seam".to_string(),
            ));
        }
        let ob_side = ob_side(intent.side);
        let qty = u64::from(intent.quantity.value());

        // Marketable (`limit = None`) → tick-aligned aggressive limit off the
        // CURRENT snapshot's touch, capped at `marketable_cap_ticks`.
        let limit_cents = match intent.limit {
            Some(limit) => limit,
            None => {
                let quote = snap.quotes.get(&intent.contract).ok_or_else(|| {
                    BacktestError::Execution(format!(
                        "realistic fill: marketable intent for strike {} not quoted at step {}",
                        intent.contract.strike.value(),
                        snap.step.value()
                    ))
                })?;
                marketable_limit_cents(intent.side, quote, tick, self.marketable_cap_ticks)?
            }
        };
        let price_ticks = cents_to_ticks(limit_cents, tick)?;

        // Mint the strategy id BEFORE borrowing the book (disjoint borrows).
        let order_id = self.next_strategy_order_id()?;
        // Submit **GTC** and capture this call's own `TradeResult`. GTC (never
        // IOC) at the seam is deliberate: on an unfillable IOC remainder the
        // upstream `_full`/`_with_result` methods return a typed error and route
        // the fills to the trade listener only, so a partial marketable walk
        // would lose its fills. GTC fills up to the aggressive-limit cap, rests
        // the remainder, and returns Ok with every fill — then IOC semantics are
        // applied explicitly below via `cancel_order` (docs/04 §5.2).
        let trade_result: TradeResult = {
            let book = self.leaf_book(&intent.contract)?;
            book.add_limit_order_full(order_id, ob_side, price_ticks, qty)?
        };
        let remaining = trade_result.match_result.remaining_quantity().as_u64();
        // IOC (marketable, or an explicit IOC limit): discard any resting
        // remainder past the cap — cancelled at end of step, never chased. GTC
        // strategy limits keep their resting remainder (a working order).
        if matches!(intent.tif, TimeInForce::Ioc) && remaining > 0 {
            let book = self.leaf_book(&intent.contract)?;
            // Ok(false) = nothing left to cancel (fully filled); Err propagates.
            let _cancelled = book.cancel_order(order_id)?;
        }

        // One `Fill` per executed price level, in queue-consumption order:
        // fill 0 carries the once-per-order fee, later fills only per-contract.
        // Fail closed on a strategy self-cross (#110), BEFORE emitting any of
        // this order's fills: a taker intent whose trade consumed a RESTING
        // STRATEGY maker would leave that maker's mirror desynced (its
        // maker-side fill has no emission slot in the e2 stream — the carry
        // channel is an e1-prefix contract). No shipped strategy crosses its own
        // resting orders; surface it as a typed error rather than a silent
        // desync until maker-side e2 capture is designed.
        for trade in trade_result.match_result.trades().as_vec() {
            if let ObOrderId::Sequential(maker_seq) = trade.maker_order_id()
                && self.resting_strategy.contains_key(&maker_seq)
            {
                return Err(BacktestError::Execution(
                    "taker intent crossed a resting strategy order (strategy \
                     self-cross); maker-side e2 capture is unsupported"
                        .to_string(),
                ));
            }
        }
        for (level, trade) in trade_result
            .match_result
            .trades()
            .as_vec()
            .iter()
            .enumerate()
        {
            let exec_price = ticks_to_cents(trade.price().as_u128(), tick)?;
            let matched = u32::try_from(trade.quantity().as_u64())
                .map_err(|_| BacktestError::ArithmeticOverflow)?;
            let quantity = Quantity::new(matched)?;
            let charge = if level == 0 {
                FeeCharge::FirstFill
            } else {
                FeeCharge::LaterFill
            };
            let draft = FillDraft {
                ts: snap.ts,
                step: snap.step,
                contract: intent.contract.clone(),
                side: intent.side,
                quantity,
                price: exec_price,
                decision_mid: intent.decision_mid,
            };
            out_fills.push(assemble_fill(
                draft,
                ExecutionMode::Realistic,
                &self.fees,
                charge,
            )?);
        }

        // A GTC strategy limit with a resting remainder is a working order the
        // market can move onto between steps: track just enough to assemble its
        // refresh-generated fill (#025) when a later snapshot's reseed crosses it
        // — its trade side, decision mid, resting size, and whether its first
        // fill already carried the per-order fee (`remaining < qty` ⇒ it filled
        // some contracts on submit). IOC remainders were cancelled above and rest
        // nothing, so only GTC working orders are tracked.
        if matches!(intent.tif, TimeInForce::Gtc)
            && remaining > 0
            && let ObOrderId::Sequential(seq) = order_id
        {
            self.resting_strategy.insert(
                seq,
                RestingStrategyOrder {
                    order_id: engine_order_id,
                    contract: intent.contract.clone(),
                    side: intent.side,
                    decision_mid: intent.decision_mid,
                    remaining,
                    first_fill_done: remaining < qty,
                },
            );
            self.order_index.insert(engine_order_id, seq);
            let count = self.live_orders.entry(intent.contract.clone()).or_insert(0);
            *count = count
                .checked_add(1)
                .ok_or(BacktestError::ArithmeticOverflow)?;
        }
        Ok(())
    }

    /// Cancel the resting strategy order the engine knows as `order_id`: cancel
    /// it in its leaf book, then drop the mirror and the id-bridge entry.
    ///
    /// An id with no live resting entry is a **benign no-op**: the engine
    /// validates ownership against its pending registry at the top of the step,
    /// so an absent entry here means the order was consumed by this very step's
    /// refresh (e1 runs before the commands) or by a taker cross — not a caller
    /// error.
    ///
    /// # Errors
    ///
    /// Returns [`BacktestError::OrderBook`] when the book rejects the cancel.
    fn cancel_resting(&mut self, order_id: OrderId) -> Result<(), BacktestError> {
        let Some(seq) = self.order_index.get(&order_id).copied() else {
            return Ok(());
        };
        if let Some(meta) = self.resting_strategy.get(&seq)
            && let Some(book) = self.books.get(&meta.contract)
        {
            // `Ok(false)` = already gone in the book (a benign race); `Err`
            // propagates as a typed book rejection.
            let _cancelled = book.cancel_order(ObOrderId::Sequential(seq))?;
        }
        if let Some(meta) = self.resting_strategy.remove(&seq) {
            Self::release_live_order(&mut self.live_orders, &meta.contract)?;
        }
        self.order_index.remove(&order_id);
        Ok(())
    }

    /// Decrement (and drop at zero) the live-order count for `contract` — the
    /// eviction index's remove half. An absent entry is a mirror/index desync
    /// and surfaces as a typed error, never a silent wrong count.
    fn release_live_order(
        live_orders: &mut BTreeMap<ContractKey, u32>,
        contract: &ContractKey,
    ) -> Result<(), BacktestError> {
        let Some(count) = live_orders.get_mut(contract) else {
            return Err(BacktestError::Execution(
                "live-order index missing an entry for a tracked resting order".to_string(),
            ));
        };
        *count = count.checked_sub(1).ok_or_else(|| {
            BacktestError::Execution(
                "live-order index underflow for a tracked resting order".to_string(),
            )
        })?;
        if *count == 0 {
            live_orders.remove(contract);
        }
        Ok(())
    }
}

impl ExecutionModel for RealisticFill {
    /// Refresh the seeded book from `snap` (e1) and then route the step's
    /// commands (e2), appending every fill — refresh-generated first, then
    /// intent — to `out_fills`, all against `snap`
    /// ([docs/04 §6.1](../../../docs/04-execution-models.md),
    /// [docs/02 §3.2](../../../docs/02-engine-architecture.md)).
    ///
    /// **e1 (refresh) precedes e2 (intents).** The between-snapshot refresh
    /// (#025) cancels the stale seed, reseeds fresh depth from `snap`, and
    /// appends any refresh-generated fills of resting strategy limits the reseed
    /// crosses — **before** the step's own command fills — so a resting order the
    /// market moved onto fills exactly once, in this step, ahead of the new
    /// intents. See [`Self::refresh_books`].
    ///
    /// **`Cancel`/`Replace` are live (#110).** A `Cancel` resolves the engine
    /// [`OrderId`] through the id bridge and cancels the resting order in its
    /// leaf book; a `Replace` cancels the old order and routes its replacement as
    /// a fresh submit under the replacement's own pre-minted id. An id with no
    /// live resting entry is a benign no-op — the engine validates ownership
    /// against its pending registry, so absence here means the order was consumed
    /// by this very step's refresh (e1 runs first). Lifecycle commands are
    /// processed in command order alongside submits; the refresh never touches
    /// strategy orders, so a resting strategy limit keeps its price-time priority
    /// across steps until filled, cancelled, or replaced.
    ///
    /// # Errors
    ///
    /// Propagates every error from [`Self::refresh_books`],
    /// [`Self::fill_submit`], and [`Self::cancel_resting`], and returns
    /// [`BacktestError::Execution`] when `submit_ids` under-covers the step's
    /// `Submit`/`Replace` commands.
    fn fill(
        &mut self,
        commands: &[OrderCommand],
        submit_ids: &[OrderId],
        snap: &ChainSnapshot,
        out_fills: &mut Vec<Fill>,
    ) -> Result<(), BacktestError> {
        // Both correlation channels are rebuilt every call: clear in place
        // (capacity retained ⇒ no steady-state allocation). Refresh fills (e1)
        // record one CarryGroup each; command fills (e2) record FillGroups.
        self.fill_groups.clear();
        self.carry_groups.clear();
        // e1: refresh the per-strike books from `snap` (cancel the stale seed,
        // reseed fresh depth) and append any refresh-generated fills BEFORE the
        // intent fills. On the first snapshot this degenerates to the #023
        // initial seed; a no-op for the raw adapter (no profile).
        self.refresh_books(snap, out_fills)?;
        // e2: route the step's commands against the freshly reseeded book. For
        // each `Submit` (or `Replace` replacement), record how many fills it
        // produced so the engine can group them back to one order and assign each
        // fill its `fill_seq` (an order walking `n` levels ⇒ one group of
        // `fill_count = n`). `submit_ids` carries one pre-minted engine id per
        // `Submit`/`Replace` in command order — the identity the resting mirror
        // records (#110).
        // Phase 1 — lifecycle first (the trait's ordered-command contract):
        // every Cancel, and every Replace's cancel half, is applied BEFORE any
        // Submit reaches the book, so a cancel frees queue space and removes
        // liquidity a same-step Submit must not consume. Order within the
        // class follows the queue.
        for command in commands {
            match command {
                OrderCommand::Cancel(order_id) | OrderCommand::Replace { order_id, .. } => {
                    self.cancel_resting(*order_id)?;
                }
                OrderCommand::Submit(_) => {}
            }
        }
        // Phase 2 — submits (and Replace replacements) in command order. The
        // pre-minted id ordinal counts one id per Submit/Replace in COMMAND
        // order — the same stream the engine minted — so phase splitting does
        // not perturb which order gets which id, and fill groups are pushed in
        // ascending command_index (the order the engine's group walk expects).
        let mut next_submit_id: usize = 0;
        for (command_index, command) in commands.iter().enumerate() {
            let intent = match command {
                OrderCommand::Submit(intent) => intent,
                // Cancel half already applied in phase 1; a Replace still
                // consumes its id slot below via the shared ordinal.
                OrderCommand::Replace { replacement, .. } => replacement,
                OrderCommand::Cancel(_) => continue,
            };
            let engine_order_id = submit_ids.get(next_submit_id).copied().ok_or_else(|| {
                BacktestError::Execution(
                    "submit_ids under-covers the step's Submit/Replace commands".to_string(),
                )
            })?;
            next_submit_id = next_submit_id
                .checked_add(1)
                .ok_or(BacktestError::ArithmeticOverflow)?;
            let before = out_fills.len();
            self.fill_submit(intent, engine_order_id, snap, out_fills)?;
            // `fill_submit` only appends, so `len >= before` always holds;
            // `checked_sub` (never `saturating_sub` on a counter, per the
            // repo's Category-E rule) surfaces any future refactor that
            // shrank the buffer as a typed error rather than a silent 0.
            let produced = out_fills.len().checked_sub(before).ok_or_else(|| {
                BacktestError::Execution("fill buffer shrank during fill_submit".to_string())
            })?;
            if produced > 0 {
                let fill_count =
                    u32::try_from(produced).map_err(|_| BacktestError::ArithmeticOverflow)?;
                self.fill_groups.push(FillGroup {
                    command_index,
                    fill_count,
                });
            }
        }
        Ok(())
    }

    #[inline]
    fn carry_fills(&self) -> &[CarryGroup] {
        // The e1 refresh-fill prefix correlation (#110): one group per refresh
        // fill, naming the prior-step resting order's engine id.
        &self.carry_groups
    }

    #[inline]
    fn fill_groups(&self) -> Option<&[FillGroup]> {
        // Realistic mode is the GROUPED correlation contract: one FillGroup per
        // filling Submit (empty when a step produced no command fills, e.g. a
        // refresh-only step). `Some` — never `None` — so a surplus refresh fill
        // is a typed error rather than being consumed one-per-Submit (F31).
        Some(&self.fill_groups)
    }

    #[inline]
    fn mode(&self) -> ExecutionMode {
        ExecutionMode::Realistic
    }
}

/// Get (or lazily construct) the leaf [`OptionOrderBook`] for `contract` inside
/// `books` — a free function so the refresh can drive it under a **disjoint
/// field borrow** of `self.books` (the reseed loop needs the rest of `self` at
/// the same time).
///
/// The book is keyed by the contract's identity and constructed with its
/// canonical `contract_id` symbol and 0.18→0.17 [`OptionStyle`] conversion.
///
/// # Errors
///
/// Returns [`BacktestError::Conversion`] when the contract's expiration is
/// unresolved (cannot form a `contract_id`).
fn leaf_book_in<'a>(
    books: &'a mut BTreeMap<ContractKey, OptionOrderBook>,
    contract: &ContractKey,
) -> Result<&'a OptionOrderBook, BacktestError> {
    match books.entry(contract.clone()) {
        Entry::Occupied(e) => Ok(&*e.into_mut()),
        Entry::Vacant(e) => {
            let symbol = contract.to_contract_id()?;
            let book = OptionOrderBook::new(symbol, ob_option_style(contract.style));
            Ok(&*e.insert(book))
        }
    }
}

/// Map an intent's **trade-direction** [`Side`] to the book's [`ObSide`] — the
/// **only** place this mapping lives.
///
/// `OrderIntent.side` is the **trade side**, not the position side: `Long` means
/// *buy*, `Short` means *sell*, for **both** opens and closes. The strategy's
/// `close_command` ([`crate::engine`], `strategy.rs`) already flips a leg's
/// position side to the trade side that flattens it — a long leg is closed by a
/// `Short` (sell) intent, a short leg by a `Long` (buy) intent — and the naive
/// model (the committed reference) interprets `intent.side` exactly this way
/// (`Long` fills up toward the ask, debits cash). So the book side follows
/// `side` alone; the intent's `action` must **not** re-flip it here. Re-flipping
/// on `Close` would **double-flip** a close and cross the wrong side of the book
/// (a buy-to-close crossing the bid), making the realised close price — and its
/// `Fill.slippage` sign ([01 §7.1](../../../docs/01-domain-model.md#71-sign-conventions-truth-table))
/// — dishonest.
///
/// | side (trade) | book side |
/// |--------------|-----------|
/// | `Long`  (buy)  | `Buy`   |
/// | `Short` (sell) | `Sell`  |
#[must_use]
const fn ob_side(side: Side) -> ObSide {
    match side {
        Side::Long => ObSide::Buy,
        Side::Short => ObSide::Sell,
    }
}

/// Convert the crate's 0.18 [`OptionStyle`] to the 0.17 [`ObOptionStyle`] the
/// leaf-book constructor takes (the version shim; see the module docs).
#[must_use]
fn ob_option_style(style: OptionStyle) -> ObOptionStyle {
    match style {
        OptionStyle::Call => ObOptionStyle::Call,
        OptionStyle::Put => ObOptionStyle::Put,
    }
}

/// Scale an integer-cents price to the book's `u128` tick grid:
/// `ticks = price_cents / tick_size_cents`, requiring an **exact** multiple.
///
/// # Errors
///
/// Returns [`BacktestError::PriceNotTickAligned`] when `price` is not a
/// multiple of `tick`, and [`BacktestError::Execution`] when `tick` is zero
/// (defence in depth — the tick is validated `> 0` at ingest).
#[must_use = "the scaled tick price must be submitted"]
fn cents_to_ticks(price: PriceCents, tick: u64) -> Result<u128, BacktestError> {
    let price = price.value();
    if tick == 0 {
        return Err(BacktestError::Execution(
            "tick_size_cents is zero in cents→tick scaling".to_string(),
        ));
    }
    if !price.is_multiple_of(tick) {
        return Err(BacktestError::PriceNotTickAligned { price, tick });
    }
    Ok(u128::from(price / tick))
}

/// Scale a book `u128` tick price back to integer cents:
/// `cents = ticks × tick_size_cents`. The lossless inverse of
/// [`cents_to_ticks`] for any tick the book actually executed at.
///
/// # Errors
///
/// Returns [`BacktestError::ArithmeticOverflow`] when the product exceeds the
/// `u64` cents range.
#[must_use = "the scaled cents price must be recorded on the fill"]
fn ticks_to_cents(ticks: u128, tick: u64) -> Result<PriceCents, BacktestError> {
    let cents = ticks
        .checked_mul(u128::from(tick))
        .ok_or(BacktestError::ArithmeticOverflow)?;
    let cents = u64::try_from(cents).map_err(|_| BacktestError::ArithmeticOverflow)?;
    Ok(PriceCents::new(cents))
}

/// The tick-aligned aggressive limit for a marketable intent, off the current
/// snapshot's touch, capped at `cap` ticks
/// ([docs/04 §5.2](../../../docs/04-execution-models.md)):
///
/// - **Buy:** `ask + cap × tick` — walks up to `cap` ticks through the touch.
/// - **Sell:** `bid − cap × tick`, **floored at `0`** (a premium cannot be
///   negative — an explicit floor, never a silent `saturating_sub`).
///
/// The touch is tick-aligned at ingest and `cap × tick` is a tick multiple, so
/// the result is tick-aligned by construction.
///
/// # Errors
///
/// Returns [`BacktestError::ArithmeticOverflow`] when `cap × tick` or the buy
/// price exceeds the `u64` cents range.
#[must_use = "the marketable limit price must be submitted"]
fn marketable_limit_cents(
    side: Side,
    quote: &QuoteView,
    tick: u64,
    cap: u32,
) -> Result<PriceCents, BacktestError> {
    let cap_offset = tick
        .checked_mul(u64::from(cap))
        .ok_or(BacktestError::ArithmeticOverflow)?;
    match ob_side(side) {
        ObSide::Buy => {
            let price = quote
                .ask
                .value()
                .checked_add(cap_offset)
                .ok_or(BacktestError::ArithmeticOverflow)?;
            Ok(PriceCents::new(price))
        }
        ObSide::Sell => {
            // Explicit floor at zero (a premium cannot be negative) via `i128`
            // `max(0)` — the repo idiom (see `naive::naive_fill_price`), never a
            // silent `saturating_sub` on money. `bid − cap_offset ∈ [−u64, u64]`
            // fits `i128`; the floored result is in `[0, bid]` and fits `u64`.
            let price = i128::from(quote.bid.value()) - i128::from(cap_offset);
            let price =
                u64::try_from(price.max(0)).map_err(|_| BacktestError::ArithmeticOverflow)?;
            Ok(PriceCents::new(price))
        }
    }
}

#[cfg(test)]
mod tests {
    /// Pre-minted engine order ids for driving `fill` directly in tests: ample
    /// for any test's Submit/Replace count; values are arbitrary identities.
    const TEST_SUBMIT_IDS: &[OrderId] = &[
        OrderId::new(9001),
        OrderId::new(9002),
        OrderId::new(9003),
        OrderId::new(9004),
        OrderId::new(9005),
        OrderId::new(9006),
        OrderId::new(9007),
        OrderId::new(9008),
    ];

    use std::collections::BTreeMap;

    use chrono::DateTime;
    use optionstratlib::{ExpirationDate, OptionStyle, Side};
    use rust_decimal_macros::dec;

    use option_chain_orderbook::{OrderId as ObOrderId, Side as ObSide};

    use super::{
        MAKER_ID_BASE, RealisticFill, cents_to_ticks, marketable_limit_cents, ob_side,
        ticks_to_cents,
    };
    use crate::config::{FeeSchedule, LiquidityProfile, TouchSize};
    use crate::domain::{
        ChainSnapshot, ContractKey, ExecutionMode, Fill, InstrumentSpec, OrderCommand, OrderId,
        OrderIntent, PositionAction, PositionId, PriceCents, Quantity, QuoteView, SimTime,
        StepIndex, TimeInForce, Underlying,
    };
    use crate::error::BacktestError;
    use crate::execution::{CarryGroup, ExecutionModel};

    const TS0: i64 = 1_750_291_200_000_000_000;
    const TICK: u64 = 5;

    fn qty(n: u32) -> Quantity {
        let Ok(q) = Quantity::new(n) else {
            panic!("{n} is a valid quantity");
        };
        q
    }

    fn contract() -> ContractKey {
        let Ok(underlying) = Underlying::new("SPX") else {
            panic!("SPX is a valid underlying");
        };
        ContractKey {
            underlying,
            expiration: ExpirationDate::DateTime(DateTime::from_timestamp_nanos(TS0)),
            strike: PriceCents::new(510_000),
            style: OptionStyle::Call,
        }
    }

    fn fees() -> FeeSchedule {
        FeeSchedule {
            per_contract_cents: 65,
            per_order_cents: 100,
        }
    }

    fn quote(bid: u64, ask: u64) -> QuoteView {
        QuoteView {
            contract: contract(),
            bid: PriceCents::new(bid),
            ask: PriceCents::new(ask),
            mid: PriceCents::new((bid + ask) / 2),
            bid_size: qty(10),
            ask_size: qty(10),
            implied_volatility: dec!(0.2),
            delta: dec!(0.5),
            gamma: dec!(0.01),
            theta: dec!(-0.05),
            vega: dec!(0.1),
        }
    }

    fn snapshot(bid: u64, ask: u64) -> ChainSnapshot {
        let Ok(underlying) = Underlying::new("SPX") else {
            panic!("SPX is a valid underlying");
        };
        let Ok(spec) = InstrumentSpec::new(PriceCents::new(TICK), 100) else {
            panic!("valid spec");
        };
        let mut quotes = BTreeMap::new();
        quotes.insert(contract(), quote(bid, ask));
        ChainSnapshot {
            ts: SimTime::new(TS0),
            step: StepIndex::new(0),
            underlying,
            underlying_price: PriceCents::new(510_000),
            spec,
            quotes,
        }
    }

    fn seq(id: ObOrderId) -> u64 {
        let ObOrderId::Sequential(n) = id else {
            panic!("adapter must mint Id::Sequential, never a random id");
        };
        n
    }

    /// A quote with explicit per-side sizes (the #025 refresh tests vary depth
    /// across snapshots to observe cancel/reseed).
    fn quote_full(bid: u64, ask: u64, bid_size: u32, ask_size: u32) -> QuoteView {
        QuoteView {
            contract: contract(),
            bid: PriceCents::new(bid),
            ask: PriceCents::new(ask),
            mid: PriceCents::new((bid + ask) / 2),
            bid_size: qty(bid_size),
            ask_size: qty(ask_size),
            implied_volatility: dec!(0.2),
            delta: dec!(0.5),
            gamma: dec!(0.01),
            theta: dec!(-0.05),
            vega: dec!(0.1),
        }
    }

    /// A one-contract snapshot at `step` with explicit per-side sizes — the
    /// consecutive-snapshot fixture the #025 refresh tests drive.
    fn snapshot_full(step: u32, bid: u64, ask: u64, bid_size: u32, ask_size: u32) -> ChainSnapshot {
        let Ok(underlying) = Underlying::new("SPX") else {
            panic!("SPX is a valid underlying");
        };
        let Ok(spec) = InstrumentSpec::new(PriceCents::new(TICK), 100) else {
            panic!("valid spec");
        };
        let mut quotes = BTreeMap::new();
        quotes.insert(contract(), quote_full(bid, ask, bid_size, ask_size));
        ChainSnapshot {
            ts: SimTime::new(TS0 + i64::from(step)),
            step: StepIndex::new(step),
            underlying,
            underlying_price: PriceCents::new(510_000),
            spec,
            quotes,
        }
    }

    /// A snapshot with NO quoted contracts at `step` — the departed-universe
    /// case the eviction path (#110) reacts to.
    fn empty_snapshot_step(step: u32) -> ChainSnapshot {
        let Ok(underlying) = Underlying::new("SPX") else {
            panic!("SPX is a valid underlying");
        };
        let Ok(spec) = InstrumentSpec::new(PriceCents::new(TICK), 100) else {
            panic!("valid spec");
        };
        ChainSnapshot {
            ts: SimTime::new(TS0 + i64::from(step)),
            step: StepIndex::new(step),
            underlying,
            underlying_price: PriceCents::new(510_000),
            spec,
            quotes: BTreeMap::new(),
        }
    }

    /// A GTC strategy buy limit at `limit` for `quantity`, decision mid
    /// `decision_mid` — the resting working order the refresh may later cross.
    fn gtc_buy(limit: u64, quantity: u32, decision_mid: u64) -> OrderCommand {
        OrderCommand::Submit(OrderIntent {
            contract: contract(),
            action: PositionAction::Open,
            side: Side::Long,
            quantity: qty(quantity),
            limit: Some(PriceCents::new(limit)),
            tif: TimeInForce::Gtc,
            decision_mid: PriceCents::new(decision_mid),
        })
    }

    /// The canonical single-touch profile (QuotedSize, `L = 0`) the refresh
    /// tests seed with — one resting level per side at the quoted touch.
    fn touch_only_profile() -> LiquidityProfile {
        profile(TouchSize::QuotedSize, 0, dec!(0.5))
    }

    /// A marketable (`limit = None`) submit for `quantity` on `side`/`action`.
    fn marketable(
        side: Side,
        action: PositionAction,
        quantity: u32,
        decision_mid: u64,
    ) -> OrderCommand {
        OrderCommand::Submit(OrderIntent {
            contract: contract(),
            action,
            side,
            quantity: qty(quantity),
            limit: None,
            tif: TimeInForce::Ioc,
            decision_mid: PriceCents::new(decision_mid),
        })
    }

    // --- trade-side → Buy/Sell (both directions) -----------------------------
    //
    // `intent.side` is the TRADE side (Long = buy, Short = sell) for BOTH opens
    // and closes: the strategy's `close_command` flips a leg's position side to
    // the flattening trade side, so the book side follows `side` alone and
    // `action` never re-flips it (a double flip would cross the wrong side).

    #[test]
    fn test_ob_side_long_is_buy() {
        // A buy — open-long OR close-short (both arrive as Side::Long).
        assert_eq!(ob_side(Side::Long), ObSide::Buy);
    }

    #[test]
    fn test_ob_side_short_is_sell() {
        // A sell — open-short OR close-long (both arrive as Side::Short).
        assert_eq!(ob_side(Side::Short), ObSide::Sell);
    }

    // --- cents ↔ tick scaling ------------------------------------------------

    #[test]
    fn test_cents_to_ticks_exact_multiple_ok() {
        assert!(matches!(
            cents_to_ticks(PriceCents::new(500), TICK),
            Ok(100)
        ));
        // lossless round-trip back to cents.
        assert!(matches!(ticks_to_cents(100, TICK), Ok(p) if p.value() == 500));
    }

    #[test]
    fn test_cents_to_ticks_non_aligned_rejected() {
        assert!(matches!(
            cents_to_ticks(PriceCents::new(501), TICK),
            Err(BacktestError::PriceNotTickAligned {
                price: 501,
                tick: 5
            })
        ));
    }

    #[test]
    fn test_ticks_to_cents_overflow_is_typed_error() {
        assert!(matches!(
            ticks_to_cents(u128::MAX, TICK),
            Err(BacktestError::ArithmeticOverflow)
        ));
    }

    // --- seeded-id determinism + disjoint ranges -----------------------------

    #[test]
    fn test_seeded_strategy_ids_are_deterministic_across_same_seed() {
        let mut a = RealisticFill::new(fees(), 10, 42);
        let mut b = RealisticFill::new(fees(), 10, 42);
        let mut ids_a = Vec::new();
        let mut ids_b = Vec::new();
        for _ in 0..5 {
            let (Ok(ia), Ok(ib)) = (a.next_strategy_order_id(), b.next_strategy_order_id()) else {
                panic!("strategy ids must mint");
            };
            ids_a.push(seq(ia));
            ids_b.push(seq(ib));
        }
        // same seed ⇒ identical OrderId sequence.
        assert_eq!(ids_a, ids_b);
        // the sequence is the low range, contiguous from the base.
        assert_eq!(ids_a, vec![1, 2, 3, 4, 5]);
    }

    #[test]
    fn test_strategy_and_maker_id_ranges_are_disjoint() {
        let mut model = RealisticFill::new(fees(), 10, 1);
        for _ in 0..8 {
            let (Ok(sid), Ok(mid)) = (model.next_strategy_order_id(), model.next_maker_order_id())
            else {
                panic!("both ranges must mint");
            };
            // strategy ids strictly below the maker base; maker ids at/above it.
            assert!(seq(sid) < MAKER_ID_BASE);
            assert!(seq(mid) >= MAKER_ID_BASE);
        }
    }

    // --- marketable-limit conversion + cap -----------------------------------

    #[test]
    fn test_marketable_limit_buy_is_ask_plus_cap_ticks() {
        // ask 500, cap 10, tick 5 → 500 + 50 = 550.
        let px = marketable_limit_cents(Side::Long, &quote(490, 500), TICK, 10);
        assert!(matches!(px, Ok(p) if p.value() == 550));
    }

    #[test]
    fn test_marketable_limit_sell_is_bid_minus_cap_ticks() {
        // bid 490, cap 10, tick 5 → 490 − 50 = 440.
        let px = marketable_limit_cents(Side::Short, &quote(490, 500), TICK, 10);
        assert!(matches!(px, Ok(p) if p.value() == 440));
    }

    #[test]
    fn test_marketable_limit_sell_floors_at_zero() {
        // bid 30, cap 10, tick 5 → 30 − 50 floors at 0 (premium ≥ 0).
        let px = marketable_limit_cents(Side::Short, &quote(30, 40), TICK, 10);
        assert!(matches!(px, Ok(p) if p.value() == 0));
    }

    // --- multi-level fill_seq (hand-seeded book) -----------------------------

    /// Route a marketable buy through a book hand-seeded with two ask levels
    /// and assert two fills at the two level prices, sharing the contract with
    /// the once-per-order fee only on the first (fill_seq 0), per-contract only
    /// on the second (fill_seq 1).
    #[test]
    fn test_marketable_buy_walks_two_levels_two_fills() {
        let mut model = RealisticFill::new(fees(), 10, 3);
        // ask ladder: 3 @ 500, 2 @ 505 (tick-aligned).
        let seeds = [(PriceCents::new(500), 3u32), (PriceCents::new(505), 2u32)];
        for (price, size) in seeds {
            let seeded =
                model.seed_maker_limit(&contract(), true, price, qty(size), PriceCents::new(TICK));
            assert!(matches!(seeded, Ok(())), "seed must rest");
        }
        // marketable buy for 5 (= 3 + 2) with mid 500; cap 10 reaches 505.
        let mut out: Vec<Fill> = Vec::new();
        let result = model.fill(
            &[marketable(Side::Long, PositionAction::Open, 5, 500)],
            TEST_SUBMIT_IDS,
            &snapshot(490, 500),
            &mut out,
        );
        assert!(matches!(result, Ok(())));
        assert_eq!(out.len(), 2, "two levels walked ⇒ two fills");

        let (Some(first), Some(second)) = (out.first(), out.get(1)) else {
            panic!("two fills expected");
        };
        // level 0: best ask 500, qty 3, once-per-order fee: 3×65 + 100 = 295.
        assert_eq!(first.price.value(), 500);
        assert_eq!(first.quantity.value(), 3);
        assert_eq!(first.fees.value(), 295);
        assert_eq!(first.mode, ExecutionMode::Realistic);
        // level 1: next ask 505, qty 2, per-contract only: 2×65 = 130.
        assert_eq!(second.price.value(), 505);
        assert_eq!(second.quantity.value(), 2);
        assert_eq!(second.fees.value(), 130);
        // both fills share the contract identity.
        assert_eq!(first.contract, second.contract);
        assert_eq!(first.side, Side::Long);
    }

    #[test]
    fn test_marketable_cap_stops_walk_and_discards_remainder() {
        let mut model = RealisticFill::new(fees(), 1, 9); // cap = 1 tick
        // three ask levels one tick apart: 500, 505, 510.
        for (price, size) in [(500u64, 3u32), (505, 3), (510, 3)] {
            let seeded = model.seed_maker_limit(
                &contract(),
                true,
                PriceCents::new(price),
                qty(size),
                PriceCents::new(TICK),
            );
            assert!(matches!(seeded, Ok(())));
        }
        // marketable buy for 9; cap 1 ⇒ limit = ask(500) + 1×5 = 505, so only
        // 500 and 505 are reachable, 510 is past the cap; the remainder (qty 3)
        // is discarded (IOC), never chased to 510.
        let mut out: Vec<Fill> = Vec::new();
        let result = model.fill(
            &[marketable(Side::Long, PositionAction::Open, 9, 500)],
            TEST_SUBMIT_IDS,
            &snapshot(490, 500),
            &mut out,
        );
        assert!(matches!(result, Ok(())));
        assert_eq!(out.len(), 2, "only two levels within the cap fill");
        assert!(out.iter().all(|f| f.price.value() <= 505));
    }

    // --- #024 honest close routing (trade side, no double flip) --------------

    /// A marketable **close of a short** (trade side `Long` = buy-to-close)
    /// crosses the **ask**, not the bid — the honest side. Under the old
    /// `action`-based double flip it would cross the bid and fill favourably
    /// (dishonest); crossing the ask makes the buy-back adverse, as it must be.
    #[test]
    fn test_close_of_short_crosses_ask_not_bid() {
        let mut model = RealisticFill::new(fees(), 10, 3);
        // asymmetric depth: bid @ 490, ask @ 510 (distinguishable by price).
        let bid = model.seed_maker_limit(
            &contract(),
            false,
            PriceCents::new(490),
            qty(5),
            PriceCents::new(TICK),
        );
        let ask = model.seed_maker_limit(
            &contract(),
            true,
            PriceCents::new(510),
            qty(5),
            PriceCents::new(TICK),
        );
        assert!(matches!((bid, ask), (Ok(()), Ok(()))));
        // Close a short: action = Close, trade side = Long (buy-to-close),
        // marketable, decision_mid = mid 500.
        let close = OrderCommand::Submit(OrderIntent {
            contract: contract(),
            action: PositionAction::Close(PositionId::new(1)),
            side: Side::Long,
            quantity: qty(1),
            limit: None,
            tif: TimeInForce::Ioc,
            decision_mid: PriceCents::new(500),
        });
        let mut out: Vec<Fill> = Vec::new();
        let result = model.fill(&[close], TEST_SUBMIT_IDS, &snapshot(490, 510), &mut out);
        assert!(matches!(result, Ok(())));
        let Some(fill) = out.first() else {
            panic!("the buy-to-close must fill against the ask");
        };
        // Crossed the ask (510), never the bid (490).
        assert_eq!(fill.price.value(), 510);
        assert_eq!(fill.side, Side::Long);
        // Buying back above mid is adverse: positive slippage.
        assert_eq!(fill.slippage.value(), 10);
    }

    /// A marketable **close of a long** (trade side `Short` = sell-to-close)
    /// crosses the **bid**, not the ask — selling below mid is adverse.
    #[test]
    fn test_close_of_long_crosses_bid_not_ask() {
        let mut model = RealisticFill::new(fees(), 10, 3);
        let bid = model.seed_maker_limit(
            &contract(),
            false,
            PriceCents::new(490),
            qty(5),
            PriceCents::new(TICK),
        );
        let ask = model.seed_maker_limit(
            &contract(),
            true,
            PriceCents::new(510),
            qty(5),
            PriceCents::new(TICK),
        );
        assert!(matches!((bid, ask), (Ok(()), Ok(()))));
        let close = OrderCommand::Submit(OrderIntent {
            contract: contract(),
            action: PositionAction::Close(PositionId::new(1)),
            side: Side::Short,
            quantity: qty(1),
            limit: None,
            tif: TimeInForce::Ioc,
            decision_mid: PriceCents::new(500),
        });
        let mut out: Vec<Fill> = Vec::new();
        let result = model.fill(&[close], TEST_SUBMIT_IDS, &snapshot(490, 510), &mut out);
        assert!(matches!(result, Ok(())));
        let Some(fill) = out.first() else {
            panic!("the sell-to-close must fill against the bid");
        };
        assert_eq!(fill.price.value(), 490);
        assert_eq!(fill.side, Side::Short);
        // Selling below mid is adverse: positive slippage.
        assert_eq!(fill.slippage.value(), 10);
    }

    // --- #024 queue position (strategy limit behind seeded depth) ------------

    /// A resting strategy limit at a **seeded price level** fills only after the
    /// depth ahead of it (added first) is consumed — same-price time priority,
    /// straight from the leaf book. Seed 3 @ 500 (ahead), rest a strategy sell
    /// of 2 @ 500 behind it, then a marketable buy for 5 walks the queue: the
    /// per-maker trades come back **seeded-3 first, strategy-2 second**, proving
    /// the strategy order queued behind the seeded depth at its level.
    #[test]
    fn test_queue_position_strategy_limit_fills_behind_seeded_depth() {
        // Pre-#110 this scenario let the marketable buy silently consume the
        // strategy's own resting sell (queue position observable, mirror left
        // desynced). With the resting-order lifecycle the self-cross fails
        // CLOSED: the maker-side fill has no e2 emission slot, so the model
        // rejects the taker with a typed error before emitting anything. The
        // book's price-time queue priority itself remains covered by the e1
        // aging test (`test_resting_strategy_limit_fills_exactly_when_later_
        // snapshot_crosses`) and upstream's own matching tests.
        let mut model = RealisticFill::new(fees(), 10, 5);
        let seeded = model.seed_maker_limit(
            &contract(),
            true,
            PriceCents::new(500),
            qty(3),
            PriceCents::new(TICK),
        );
        assert!(matches!(seeded, Ok(())));
        let rest_then_walk = [
            OrderCommand::Submit(OrderIntent {
                contract: contract(),
                action: PositionAction::Open,
                side: Side::Short, // sell → rests on the ask at 500, no cross
                quantity: qty(2),
                limit: Some(PriceCents::new(500)),
                tif: TimeInForce::Gtc,
                decision_mid: PriceCents::new(500),
            }),
            marketable(Side::Long, PositionAction::Open, 5, 500),
        ];
        let mut out: Vec<Fill> = Vec::new();
        let result = model.fill(
            &rest_then_walk,
            TEST_SUBMIT_IDS,
            &snapshot(490, 500),
            &mut out,
        );
        let Err(BacktestError::Execution(message)) = result else {
            panic!("a strategy self-cross must fail closed, got {result:?}");
        };
        assert!(
            message.contains("self-cross"),
            "the error names the self-cross: {message}"
        );
    }

    // --- #024 partial / empty / deep fills -----------------------------------

    /// A thin strike fills **less than the intent**: a marketable buy for 5 into
    /// a book with only 2 seeded contracts fills 2 and the remainder is
    /// discarded (IOC) — realistic mode fills partially, unlike naive.
    #[test]
    fn test_thin_strike_partial_fill_matched_less_than_intent() {
        let mut model = RealisticFill::new(fees(), 10, 5);
        let seeded = model.seed_maker_limit(
            &contract(),
            true,
            PriceCents::new(500),
            qty(2),
            PriceCents::new(TICK),
        );
        assert!(matches!(seeded, Ok(())));
        let mut out: Vec<Fill> = Vec::new();
        let result = model.fill(
            &[marketable(Side::Long, PositionAction::Open, 5, 500)],
            TEST_SUBMIT_IDS,
            &snapshot(490, 500),
            &mut out,
        );
        assert!(matches!(result, Ok(())));
        assert_eq!(out.len(), 1, "only the seeded depth fills");
        let matched: u32 = out.iter().map(|f| f.quantity.value()).sum();
        assert_eq!(matched, 2, "partial: 2 of 5 filled, 3 discarded (IOC)");
    }

    /// An empty (unseeded) strike leaves a **zero** fill: nothing crosses, so no
    /// `Fill` is appended — realistic mode can decline to fill entirely.
    #[test]
    fn test_empty_strike_yields_zero_fills() {
        let mut model = RealisticFill::new(fees(), 10, 5);
        let mut out: Vec<Fill> = Vec::new();
        let result = model.fill(
            &[marketable(Side::Long, PositionAction::Open, 5, 500)],
            TEST_SUBMIT_IDS,
            &snapshot(490, 500),
            &mut out,
        );
        assert!(matches!(result, Ok(())));
        assert!(out.is_empty(), "no seeded depth ⇒ zero fills");
    }

    /// A deep strike fills the **full intent** in a single level: a marketable
    /// buy for 5 into 100 seeded contracts fills 5 at the touch, one fill.
    #[test]
    fn test_deep_strike_fills_full_intent_single_level() {
        let mut model = RealisticFill::new(fees(), 10, 5);
        let seeded = model.seed_maker_limit(
            &contract(),
            true,
            PriceCents::new(500),
            qty(100),
            PriceCents::new(TICK),
        );
        assert!(matches!(seeded, Ok(())));
        let mut out: Vec<Fill> = Vec::new();
        let result = model.fill(
            &[marketable(Side::Long, PositionAction::Open, 5, 500)],
            TEST_SUBMIT_IDS,
            &snapshot(490, 500),
            &mut out,
        );
        assert!(matches!(result, Ok(())));
        assert_eq!(out.len(), 1, "deep touch fills the whole intent at once");
        let Some(fill) = out.first() else {
            panic!("one fill expected");
        };
        assert_eq!((fill.price.value(), fill.quantity.value()), (500, 5));
    }

    // --- #024 slippage sign + fee parity -------------------------------------

    /// A marketable buy that walks the ladder records **progressively more
    /// adverse** (larger positive) per-level slippage against the fixed
    /// decision-time mid — the emergent market-impact signal, sign per §7.1.
    #[test]
    fn test_realistic_per_level_slippage_is_progressively_adverse() {
        let mut model = RealisticFill::new(fees(), 10, 5);
        for (price, size) in [(500u64, 2u32), (505, 2), (510, 2)] {
            let seeded = model.seed_maker_limit(
                &contract(),
                true,
                PriceCents::new(price),
                qty(size),
                PriceCents::new(TICK),
            );
            assert!(matches!(seeded, Ok(())));
        }
        // decision_mid fixed at 500 (never re-read post-impact); buy 6 walks all.
        let mut out: Vec<Fill> = Vec::new();
        let result = model.fill(
            &[marketable(Side::Long, PositionAction::Open, 6, 500)],
            TEST_SUBMIT_IDS,
            &snapshot(490, 500),
            &mut out,
        );
        assert!(matches!(result, Ok(())));
        let slippage: Vec<i64> = out.iter().map(|f| f.slippage.value()).collect();
        // (500−500)·2 = 0, (505−500)·2 = +10, (510−500)·2 = +20 — non-decreasing,
        // adverse (≥ 0) as each deeper level fills worse than the decision mid.
        assert_eq!(slippage, vec![0, 10, 20]);
        assert!(slippage.windows(2).all(|w| w[1] >= w[0]));
    }

    /// Fees are charged identically to naive for the same filled contracts:
    /// `per_contract` on the fill plus `per_order` once on the first fill.
    #[test]
    fn test_realistic_fees_match_naive_for_same_filled_contracts() {
        let mut model = RealisticFill::new(fees(), 10, 5);
        let seeded = model.seed_maker_limit(
            &contract(),
            true,
            PriceCents::new(500),
            qty(10),
            PriceCents::new(TICK),
        );
        assert!(matches!(seeded, Ok(())));
        let mut out: Vec<Fill> = Vec::new();
        let result = model.fill(
            &[marketable(Side::Long, PositionAction::Open, 4, 500)],
            TEST_SUBMIT_IDS,
            &snapshot(490, 500),
            &mut out,
        );
        assert!(matches!(result, Ok(())));
        let Some(fill) = out.first() else {
            panic!("one fill of 4 contracts expected");
        };
        // Same rule as naive: 4 × per_contract(65) + per_order(100) = 360.
        assert_eq!(fill.quantity.value(), 4);
        assert_eq!(fill.fees.value(), 4 * 65 + 100);
    }

    // --- #023 auto-seeding wiring --------------------------------------------

    fn profile(
        touch: TouchSize,
        depth_levels: u32,
        decay: rust_decimal::Decimal,
    ) -> LiquidityProfile {
        LiquidityProfile {
            touch_size: touch,
            depth_levels,
            decay,
        }
    }

    /// `with_liquidity_profile` seeds the ask ladder from the snapshot BEFORE
    /// routing, so a marketable buy walks the auto-seeded depth (no hand-seed).
    #[test]
    fn test_with_liquidity_profile_auto_seeds_ask_ladder_before_routing() {
        // QuotedSize, L=2, r=0.5, ask_size 10 → ask ladder 10@500, 5@505, 2@510.
        let mut model = RealisticFill::with_liquidity_profile(
            fees(),
            10,
            7,
            profile(TouchSize::QuotedSize, 2, dec!(0.5)),
        );
        let mut out: Vec<Fill> = Vec::new();
        // marketable buy for 12 walks 10@500 then 2@505 (cap 10 reaches 510).
        let result = model.fill(
            &[marketable(Side::Long, PositionAction::Open, 12, 500)],
            TEST_SUBMIT_IDS,
            &snapshot(490, 500),
            &mut out,
        );
        assert!(matches!(result, Ok(())));
        assert_eq!(out.len(), 2, "the buy walks two auto-seeded ask levels");
        let (Some(first), Some(second)) = (out.first(), out.get(1)) else {
            panic!("two fills expected");
        };
        assert_eq!((first.price.value(), first.quantity.value()), (500, 10));
        assert_eq!((second.price.value(), second.quantity.value()), (505, 2));
    }

    /// The raw-adapter constructor (`new`) never auto-seeds: a marketable buy
    /// into an unseeded book fills nothing.
    #[test]
    fn test_new_raw_adapter_does_not_auto_seed() {
        let mut model = RealisticFill::new(fees(), 10, 7);
        let mut out: Vec<Fill> = Vec::new();
        let result = model.fill(
            &[marketable(Side::Long, PositionAction::Open, 5, 500)],
            TEST_SUBMIT_IDS,
            &snapshot(490, 500),
            &mut out,
        );
        assert!(matches!(result, Ok(())));
        assert!(out.is_empty(), "no seeded depth ⇒ nothing to fill");
    }

    /// Auto-seeding draws its ids from the seeded-maker range, leaving the
    /// strategy range untouched — the #022 disjointness holds through seeding.
    #[test]
    fn test_auto_seed_consumes_only_maker_ids() {
        let mut model = RealisticFill::with_liquidity_profile(
            fees(),
            10,
            7,
            profile(TouchSize::QuotedSize, 2, dec!(0.5)),
        );
        let mut out: Vec<Fill> = Vec::new();
        // A passive (non-crossing) buy limit: seeding runs, no strategy fill,
        // and the strategy id counter advances by exactly one submit.
        let submit = OrderCommand::Submit(OrderIntent {
            contract: contract(),
            action: PositionAction::Open,
            side: Side::Long,
            quantity: qty(1),
            limit: Some(PriceCents::new(400)), // well below ask, rests, no cross
            tif: TimeInForce::Gtc,
            decision_mid: PriceCents::new(495),
        });
        let result = model.fill(&[submit], TEST_SUBMIT_IDS, &snapshot(490, 500), &mut out);
        assert!(matches!(result, Ok(())));
        // Next maker id is in the high range (seeding consumed several);
        // next strategy id is in the low range and advanced past the base.
        let (Ok(next_maker), Ok(next_strategy)) =
            (model.next_maker_order_id(), model.next_strategy_order_id())
        else {
            panic!("both id ranges must still mint");
        };
        assert!(
            seq(next_maker) > MAKER_ID_BASE,
            "maker ids were consumed by seeding"
        );
        assert!(
            seq(next_strategy) < MAKER_ID_BASE,
            "strategy ids stay in the low range"
        );
    }

    // --- resting limit that does not cross yields no fill --------------------

    #[test]
    fn test_resting_gtc_limit_below_ask_appends_no_fill() {
        let mut model = RealisticFill::new(fees(), 10, 4);
        // an ask rests at 505; a passive buy limit at 500 (< 505) does not cross.
        let seeded = model.seed_maker_limit(
            &contract(),
            true,
            PriceCents::new(505),
            qty(2),
            PriceCents::new(TICK),
        );
        assert!(matches!(seeded, Ok(())));
        let submit = OrderCommand::Submit(OrderIntent {
            contract: contract(),
            action: PositionAction::Open,
            side: Side::Long,
            quantity: qty(2),
            limit: Some(PriceCents::new(500)),
            tif: TimeInForce::Gtc,
            decision_mid: PriceCents::new(502),
        });
        let mut out: Vec<Fill> = Vec::new();
        let result = model.fill(&[submit], TEST_SUBMIT_IDS, &snapshot(490, 505), &mut out);
        assert!(matches!(result, Ok(())));
        assert!(out.is_empty(), "a non-crossing resting limit does not fill");
    }

    // --- non-tick-aligned strategy limit rejected ----------------------------

    #[test]
    fn test_submit_non_tick_aligned_limit_rejected() {
        let mut model = RealisticFill::new(fees(), 10, 5);
        let submit = OrderCommand::Submit(OrderIntent {
            contract: contract(),
            action: PositionAction::Open,
            side: Side::Long,
            quantity: qty(1),
            limit: Some(PriceCents::new(501)), // not a multiple of tick 5
            tif: TimeInForce::Ioc,
            decision_mid: PriceCents::new(500),
        });
        let mut out: Vec<Fill> = Vec::new();
        let result = model.fill(&[submit], TEST_SUBMIT_IDS, &snapshot(490, 500), &mut out);
        assert!(matches!(
            result,
            Err(BacktestError::PriceNotTickAligned {
                price: 501,
                tick: 5
            })
        ));
        assert!(out.is_empty());
    }

    // --- marketable intent for an unquoted contract is an error --------------

    #[test]
    fn test_marketable_unquoted_contract_execution_error() {
        let mut model = RealisticFill::new(fees(), 10, 6);
        let mut snap = snapshot(490, 500);
        snap.quotes.clear();
        let mut out: Vec<Fill> = Vec::new();
        let result = model.fill(
            &[marketable(Side::Long, PositionAction::Open, 1, 500)],
            TEST_SUBMIT_IDS,
            &snap,
            &mut out,
        );
        assert!(matches!(result, Err(BacktestError::Execution(_))));
        assert!(out.is_empty());
    }

    // --- option_chain_orderbook::Error mapping -------------------------------

    #[test]
    fn test_orderbook_error_maps_to_backtest_orderbook() {
        let err = option_chain_orderbook::Error::NoDataAvailable {
            message: "seeded strike empty".to_string(),
        };
        let mapped = BacktestError::from(err);
        assert!(
            matches!(&mapped, BacktestError::OrderBook(msg) if msg.contains("no data available"))
        );
    }

    // --- mode + Cancel/Replace deferral --------------------------------------

    #[test]
    fn test_realistic_mode_returns_realistic() {
        let model = RealisticFill::new(fees(), 10, 1);
        assert_eq!(model.mode(), ExecutionMode::Realistic);
    }

    #[test]
    fn test_cancel_and_replace_append_no_fills_in_issue_22() {
        use crate::domain::OrderId;
        let mut model = RealisticFill::new(fees(), 10, 1);
        let commands = [
            OrderCommand::Cancel(OrderId::new(1)),
            OrderCommand::Replace {
                order_id: OrderId::new(2),
                replacement: OrderIntent {
                    contract: contract(),
                    action: PositionAction::Close(PositionId::new(9)),
                    side: Side::Short,
                    quantity: qty(1),
                    limit: Some(PriceCents::new(500)),
                    tif: TimeInForce::Gtc,
                    decision_mid: PriceCents::new(500),
                },
            },
        ];
        let mut out: Vec<Fill> = Vec::new();
        let result = model.fill(&commands, TEST_SUBMIT_IDS, &snapshot(490, 500), &mut out);
        assert!(matches!(result, Ok(())));
        assert!(
            out.is_empty(),
            "cancel/replace remain deferred; they append no fills"
        );
    }

    // --- #025 between-snapshot book refresh ----------------------------------

    /// Seeded depth from `S_{n-1}` never leaks into `S_n`: the refresh cancels
    /// every stale seeded-maker order before reseeding. `snap1` seeds a DEEP ask
    /// at 505; `snap2` a THIN ask (3) at 500. A marketable buy for 10 at `snap2`
    /// (cap reaches 505) must fill ONLY the 3 @ 500 — were the stale 505 depth
    /// still resting it would fill 7 more there.
    #[test]
    fn test_refresh_cancels_stale_seed_no_leak_into_next_snapshot() {
        let mut model = RealisticFill::with_liquidity_profile(fees(), 10, 5, touch_only_profile());
        let mut out: Vec<Fill> = Vec::new();
        // snap1: ask 505, deep ask_size 100 — seeded, no order routed.
        let r1 = model.fill(
            &[],
            TEST_SUBMIT_IDS,
            &snapshot_full(0, 495, 505, 100, 100),
            &mut out,
        );
        assert!(matches!(r1, Ok(())));
        assert!(out.is_empty(), "seeding snap1 alone produces no fill");
        // snap2: ask 500, thin ask_size 3. A marketable buy for 10.
        out.clear();
        let r2 = model.fill(
            &[marketable(Side::Long, PositionAction::Open, 10, 500)],
            TEST_SUBMIT_IDS,
            &snapshot_full(1, 490, 500, 3, 3),
            &mut out,
        );
        assert!(matches!(r2, Ok(())));
        let matched: u32 = out.iter().map(|f| f.quantity.value()).sum();
        assert_eq!(
            matched, 3,
            "only snap2's 3 @ 500 fills; every snap1 seeded order was cancelled"
        );
        assert_eq!(out.len(), 1, "one level — the stale 505 depth did not leak");
        let Some(fill) = out.first() else {
            panic!("one fill expected");
        };
        assert_eq!(fill.price.value(), 500);
    }

    /// A resting strategy limit fills **exactly** when a later snapshot's quotes
    /// cross it — via a refresh-generated fill on reseed — and not before. It
    /// fills at its own limit price (aged price-time priority), tagged to the
    /// crossing step, with the stored decision mid fixing the slippage sign.
    #[test]
    fn test_resting_strategy_limit_fills_exactly_when_later_snapshot_crosses() {
        let mut model = RealisticFill::with_liquidity_profile(fees(), 10, 5, touch_only_profile());
        // snap1: ask 600 (wide). A GTC strategy buy at 500 rests below it — no
        // cross, so no fill at snap1.
        let mut out: Vec<Fill> = Vec::new();
        let r1 = model.fill(
            &[gtc_buy(500, 1, 550)],
            TEST_SUBMIT_IDS,
            &snapshot_full(0, 490, 600, 20, 20),
            &mut out,
        );
        assert!(matches!(r1, Ok(())));
        assert!(out.is_empty(), "the buy at 500 does not cross the 600 ask");
        // snap2: ask moves down to 500. The reseed ask touch at 500 crosses the
        // resting strategy buy — a refresh-generated fill at the buy's price.
        out.clear();
        let r2 = model.fill(
            &[],
            TEST_SUBMIT_IDS,
            &snapshot_full(1, 490, 500, 20, 20),
            &mut out,
        );
        assert!(matches!(r2, Ok(())));
        assert_eq!(
            out.len(),
            1,
            "exactly one refresh fill when the market crosses"
        );
        let Some(fill) = out.first() else {
            panic!("one refresh fill expected");
        };
        assert_eq!(fill.side, Side::Long);
        assert_eq!(
            fill.price.value(),
            500,
            "fills at the resting limit's price"
        );
        assert_eq!(fill.quantity.value(), 1);
        assert_eq!(fill.step.value(), 1, "a step-1 fill, against snap2");
        assert_eq!(fill.mode, ExecutionMode::Realistic);
        // decision_mid 550, buy at 500 (below mid) ⇒ favourable: negative slippage.
        assert_eq!(fill.slippage.value(), -50);
    }

    /// The refresh does **not** cancel or reinsert strategy orders: an uncrossed
    /// resting strategy limit survives a full cancel-seed → reseed cycle and
    /// still fills only when a still-later snapshot finally crosses it.
    #[test]
    fn test_refresh_leaves_uncrossed_strategy_order_resting() {
        let mut model = RealisticFill::with_liquidity_profile(fees(), 10, 5, touch_only_profile());
        let mut out: Vec<Fill> = Vec::new();
        // snap0: rest a strategy buy at 500 under a wide 600 ask.
        let r0 = model.fill(
            &[gtc_buy(500, 1, 560)],
            TEST_SUBMIT_IDS,
            &snapshot_full(0, 490, 600, 20, 20),
            &mut out,
        );
        assert!(matches!(r0, Ok(())));
        assert!(out.is_empty());
        // snap1: ask still wide (580). The refresh cancels+reseeds the seed but
        // must NOT touch the strategy order, so it still does not fill.
        out.clear();
        let r1 = model.fill(
            &[],
            TEST_SUBMIT_IDS,
            &snapshot_full(1, 490, 580, 20, 20),
            &mut out,
        );
        assert!(matches!(r1, Ok(())));
        assert!(
            out.is_empty(),
            "the uncrossed strategy order survives the refresh unfilled"
        );
        // snap2: ask finally crosses at 500 — the surviving order fills now.
        out.clear();
        let r2 = model.fill(
            &[],
            TEST_SUBMIT_IDS,
            &snapshot_full(2, 490, 500, 20, 20),
            &mut out,
        );
        assert!(matches!(r2, Ok(())));
        assert_eq!(out.len(), 1);
        let Some(fill) = out.first() else {
            panic!("one fill expected");
        };
        assert_eq!(
            (fill.side, fill.price.value(), fill.step.value()),
            (Side::Long, 500, 2)
        );
    }

    /// Refresh-generated fills (e1) are appended **before** the step's intent
    /// fills (e2). At `snap2` the reseed crosses a resting buy (e1) and a
    /// marketable sell intent crosses the reseeded bid (e2); the refresh fill
    /// must come first in `out_fills`.
    #[test]
    fn test_refresh_fill_precedes_intent_fill_in_out_fills() {
        let mut model = RealisticFill::with_liquidity_profile(fees(), 10, 5, touch_only_profile());
        let mut out: Vec<Fill> = Vec::new();
        // snap1: rest a strategy buy at 500 under a wide 600 ask.
        let r1 = model.fill(
            &[gtc_buy(500, 1, 550)],
            TEST_SUBMIT_IDS,
            &snapshot_full(0, 490, 600, 20, 20),
            &mut out,
        );
        assert!(matches!(r1, Ok(())));
        assert!(out.is_empty());
        // snap2: ask crosses the resting buy (e1) AND route a marketable sell (e2).
        out.clear();
        let r2 = model.fill(
            &[marketable(Side::Short, PositionAction::Open, 2, 500)],
            TEST_SUBMIT_IDS,
            &snapshot_full(1, 490, 500, 20, 20),
            &mut out,
        );
        assert!(matches!(r2, Ok(())));
        assert_eq!(
            out.len(),
            2,
            "one refresh fill (e1) then one intent fill (e2)"
        );
        let (Some(first), Some(second)) = (out.first(), out.get(1)) else {
            panic!("two fills expected");
        };
        // e1: the refresh-generated fill of the resting buy, at its price 500.
        assert_eq!((first.side, first.price.value()), (Side::Long, 500));
        // e2: the marketable sell crosses snap2's reseeded bid at 490.
        assert_eq!((second.side, second.price.value()), (Side::Short, 490));
    }

    /// Two identical multi-snapshot refresh runs produce byte-identical fills —
    /// the refresh (cancel stale seed → reseed in fixed order → capture) is fully
    /// deterministic, seeded ids and all.
    #[test]
    fn test_refresh_is_deterministic_across_two_multi_snapshot_runs() {
        let run = || -> Vec<(u32, u64, u32, i64)> {
            let mut model =
                RealisticFill::with_liquidity_profile(fees(), 10, 5, touch_only_profile());
            let mut out: Vec<Fill> = Vec::new();
            let snaps = [
                snapshot_full(0, 490, 600, 20, 20),
                snapshot_full(1, 490, 540, 20, 20),
                snapshot_full(2, 490, 500, 20, 20),
            ];
            let cmds = [gtc_buy(500, 1, 550)];
            for (i, snap) in snaps.iter().enumerate() {
                out.clear();
                let step_cmds: &[OrderCommand] = if i == 0 { &cmds } else { &[] };
                match model.fill(step_cmds, TEST_SUBMIT_IDS, snap, &mut out) {
                    Ok(()) => {}
                    Err(e) => panic!("the refresh run must succeed: {e}"),
                }
            }
            out.iter()
                .map(|f| {
                    (
                        f.step.value(),
                        f.price.value(),
                        f.quantity.value(),
                        f.slippage.value(),
                    )
                })
                .collect()
        };
        assert_eq!(
            run(),
            run(),
            "the same tape yields byte-identical refresh fills"
        );
    }

    // --- #110 resting-order lifecycle (Cancel/Replace, eviction, carry ids) ---

    /// A cancelled resting GTC never fills, even when a later snapshot crosses
    /// its price: the cancel removes it from the book and the mirror, so the
    /// crossing refresh produces no fill and no carry group.
    #[test]
    fn test_cancel_then_cross_never_fills() {
        let mut model = RealisticFill::with_liquidity_profile(fees(), 10, 5, touch_only_profile());
        // Step 0: GTC buy 2 @ 500 rests under the 600 ask.
        let mut out: Vec<Fill> = Vec::new();
        let r0 = model.fill(
            &[gtc_buy(500, 2, 550)],
            TEST_SUBMIT_IDS,
            &snapshot_full(0, 480, 600, 5, 5),
            &mut out,
        );
        assert!(matches!(r0, Ok(())));
        assert!(out.is_empty(), "the buy rests, no fill");
        // Step 1 (no cross): the strategy cancels its order.
        let cancel = [OrderCommand::Cancel(TEST_SUBMIT_IDS[0])];
        let r1 = model.fill(&cancel, &[], &snapshot_full(1, 480, 600, 5, 5), &mut out);
        assert!(matches!(r1, Ok(())));
        assert!(out.is_empty());
        assert!(
            model.resting_strategy.is_empty(),
            "the mirror entry is gone"
        );
        assert!(model.order_index.is_empty(), "the id bridge entry is gone");
        // Step 2: the ask drops to 500 — the cancelled order must NOT fill.
        let r2 = model.fill(&[], &[], &snapshot_full(2, 480, 500, 5, 5), &mut out);
        assert!(matches!(r2, Ok(())));
        assert!(out.is_empty(), "a cancelled order never fills");
        assert!(model.carry_fills().is_empty());
    }

    /// Replace kills the old resting order and routes the replacement as a
    /// fresh submit under its own id: a cross at the OLD price no longer fills,
    /// a cross at the NEW price fills carrying the replacement's id.
    #[test]
    fn test_replace_moves_the_resting_order() {
        let mut model = RealisticFill::with_liquidity_profile(fees(), 10, 5, touch_only_profile());
        let mut out: Vec<Fill> = Vec::new();
        let r0 = model.fill(
            &[gtc_buy(500, 2, 550)],
            TEST_SUBMIT_IDS,
            &snapshot_full(0, 480, 600, 5, 5),
            &mut out,
        );
        assert!(matches!(r0, Ok(())));
        // Step 1: replace the 500 buy with a LOWER 480 buy (new identity).
        let OrderCommand::Submit(replacement_intent) = gtc_buy(480, 2, 550) else {
            panic!("gtc_buy builds a Submit");
        };
        let replace = [OrderCommand::Replace {
            order_id: TEST_SUBMIT_IDS[0],
            replacement: replacement_intent,
        }];
        // The Replace consumes the FIRST pre-minted id of ITS step.
        let step1_ids = [TEST_SUBMIT_IDS[1]];
        let r1 = model.fill(
            &replace,
            &step1_ids,
            &snapshot_full(1, 460, 600, 5, 5),
            &mut out,
        );
        assert!(matches!(r1, Ok(())));
        assert!(out.is_empty(), "the replacement rests at 480");
        // Step 2: ask drops to 500 — the OLD price would have crossed; the new
        // 480 limit must not fill.
        let r2 = model.fill(&[], &[], &snapshot_full(2, 460, 500, 5, 5), &mut out);
        assert!(matches!(r2, Ok(())));
        assert!(out.is_empty(), "the replaced-away 500 order is dead");
        // Step 3: ask reaches 480 — the replacement fills, carrying ITS id.
        let r3 = model.fill(&[], &[], &snapshot_full(3, 460, 480, 5, 5), &mut out);
        assert!(matches!(r3, Ok(())));
        assert_eq!(out.len(), 1, "the replacement fills once");
        let carries = model.carry_fills();
        assert_eq!(carries.len(), 1);
        let Some(carry) = carries.first() else {
            panic!("one carry group");
        };
        assert_eq!(carry.order_id, TEST_SUBMIT_IDS[1], "the REPLACEMENT id");
        assert_eq!(carry.fill_count, 1);
    }

    /// A departed contract with no live strategy order is evicted from `books`
    /// and `resting_seed_ids`; a departed contract WITH a live resting strategy
    /// order is retained.
    #[test]
    fn test_eviction_departed_contract_book_removed_live_order_book_retained() {
        let mut model = RealisticFill::with_liquidity_profile(fees(), 10, 5, touch_only_profile());
        let mut out: Vec<Fill> = Vec::new();
        // Step 0: the contract is quoted (book seeded) and a GTC rests in it.
        let r0 = model.fill(
            &[gtc_buy(500, 2, 550)],
            TEST_SUBMIT_IDS,
            &snapshot_full(0, 480, 600, 5, 5),
            &mut out,
        );
        assert!(matches!(r0, Ok(())));
        assert_eq!(model.books.len(), 1);
        // Step 1: the contract leaves the universe (empty snapshot) — the book
        // holds a live strategy order, so it is RETAINED.
        let r1 = model.fill(&[], &[], &empty_snapshot_step(1), &mut out);
        assert!(matches!(r1, Ok(())));
        assert_eq!(model.books.len(), 1, "a live-order book is never evicted");
        // Cancel the order; the next departed-universe refresh evicts the book.
        let cancel = [OrderCommand::Cancel(TEST_SUBMIT_IDS[0])];
        let r2 = model.fill(&cancel, &[], &empty_snapshot_step(2), &mut out);
        assert!(matches!(r2, Ok(())));
        let r3 = model.fill(&[], &[], &empty_snapshot_step(3), &mut out);
        assert!(matches!(r3, Ok(())));
        assert!(model.books.is_empty(), "the dead book is evicted");
        assert!(model.resting_seed_ids.is_empty());
        assert!(out.is_empty(), "no fill was ever produced");
    }

    /// One resting order crossed by SEVERAL reseed levels in a single refresh
    /// coalesces into ONE carry group (fill_count = levels), so the engine
    /// VWAP-aggregates it into one leg — the e2 command path's granularity.
    #[test]
    fn test_multi_level_refresh_cross_coalesces_into_one_carry_group() {
        // Ladder: touch + 1 deeper level, uniform size (decay 1) — the ask
        // seeds at 500 (size 2) and 505 (size 2), both under the 510 buy.
        let ladder = profile(TouchSize::QuotedSize, 1, dec!(1));
        let mut model = RealisticFill::with_liquidity_profile(fees(), 10, 5, ladder);
        let mut out: Vec<Fill> = Vec::new();
        // Step 0: GTC buy 4 @ 510 rests under the 600 ask.
        let r0 = model.fill(
            &[gtc_buy(510, 4, 550)],
            TEST_SUBMIT_IDS,
            &snapshot_full(0, 480, 600, 2, 2),
            &mut out,
        );
        assert!(matches!(r0, Ok(())));
        assert!(out.is_empty(), "the buy rests");
        // Step 1: ask drops to 500 — BOTH ladder levels (500, 505) cross the
        // 510 buy: two fills, ONE coalesced carry group.
        let r1 = model.fill(&[], &[], &snapshot_full(1, 480, 500, 2, 2), &mut out);
        assert!(matches!(r1, Ok(())));
        assert_eq!(out.len(), 2, "two levels crossed ⇒ two fills");
        let carries = model.carry_fills();
        assert_eq!(carries.len(), 1, "contiguous same-order fills coalesce");
        let Some(carry) = carries.first() else {
            panic!("one carry group");
        };
        assert_eq!(carry.order_id, TEST_SUBMIT_IDS[0]);
        assert_eq!(carry.fill_count, 2);
    }

    /// Review F3: lifecycle commands apply BEFORE submits — a queue carrying
    /// `[Submit marketable buy, Cancel(resting sell)]` cancels the sell first,
    /// so the buy crosses only seeded depth instead of self-crossing the
    /// strategy's own resting order.
    #[test]
    fn test_mixed_queue_cancel_applies_before_submit() {
        let mut model = RealisticFill::with_liquidity_profile(fees(), 30, 5, touch_only_profile());
        let mut out: Vec<Fill> = Vec::new();
        // Step 0: GTC sell 2 @ 500 rests on the ask (bid 480, quoted ask 600).
        let OrderCommand::Submit(mut sell) = gtc_buy(500, 2, 550) else {
            panic!("gtc_buy builds a Submit");
        };
        sell.side = Side::Short;
        let r0 = model.fill(
            &[OrderCommand::Submit(sell)],
            TEST_SUBMIT_IDS,
            &snapshot_full(0, 480, 600, 5, 5),
            &mut out,
        );
        assert!(matches!(r0, Ok(())));
        assert!(out.is_empty(), "the sell rests");
        // Step 1: RAW order is [marketable buy, Cancel(sell)] — without
        // lifecycle-first the buy would cross the resting sell at 500 and fail
        // closed as a self-cross. With phase 1 the cancel lands first and the
        // buy walks the reseeded 600 ask instead.
        let cmds = [
            marketable(Side::Long, PositionAction::Open, 2, 550),
            OrderCommand::Cancel(TEST_SUBMIT_IDS[0]),
        ];
        let step1_ids = [TEST_SUBMIT_IDS[1]];
        let r1 = model.fill(
            &cmds,
            &step1_ids,
            &snapshot_full(1, 480, 600, 5, 5),
            &mut out,
        );
        assert!(matches!(r1, Ok(())), "no self-cross: {r1:?}");
        assert_eq!(out.len(), 1, "the buy fills against seeded depth");
        let Some(fill) = out.first() else {
            panic!("one fill");
        };
        assert_eq!(fill.price.value(), 600, "filled at the seeded ask, not 500");
        assert!(model.resting_strategy.is_empty(), "the sell was cancelled");
    }

    /// The full lifecycle sequence is deterministic: two identically-driven
    /// models produce byte-identical fills and carry groups.
    #[test]
    fn test_lifecycle_sequence_is_deterministic_across_two_runs() {
        let run = || -> (Vec<Fill>, Vec<CarryGroup>) {
            let mut model =
                RealisticFill::with_liquidity_profile(fees(), 10, 5, touch_only_profile());
            let mut out: Vec<Fill> = Vec::new();
            let r0 = model.fill(
                &[gtc_buy(500, 3, 550)],
                TEST_SUBMIT_IDS,
                &snapshot_full(0, 480, 600, 5, 5),
                &mut out,
            );
            assert!(matches!(r0, Ok(())));
            let r1 = model.fill(&[], &[], &snapshot_full(1, 480, 500, 5, 5), &mut out);
            assert!(matches!(r1, Ok(())));
            (out, model.carry_fills().to_vec())
        };
        let (fills_a, carries_a) = run();
        let (fills_b, carries_b) = run();
        assert_eq!(fills_a, fills_b, "byte-identical fills");
        assert_eq!(carries_a, carries_b, "byte-identical carry groups");
    }
}