rustrade-execution 0.15.0

Stream private account data from financial venues, and execute (live or mock) orders.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
//! The simulated venue's state machine, independent of any transport that drives it.

use crate::{
    AccountEventKind, InstrumentAccountSnapshot, UnindexedAccountEvent, UnindexedAccountSnapshot,
    balance::AssetBalance,
    cash_flow::{CashFlow, CashFlowId, CashFlowKind, InterestTiming},
    client::mock::MockExecutionConfig,
    error::{ApiError, BorrowReject, BorrowRejectReason, UnindexedApiError, UnindexedOrderError},
    exchange::mock::{
        account::{AccountState, BalanceInsufficient, Committed, Credit, Debit, Delivery},
        orders::{AlreadyResting, OpenOrder, Reservation, RestingOrder},
    },
    fee::{FeeAssetConfig, FeeModel, FeeModelConfig, Liquidity, SpotFeeAsset},
    fill::{FillContext, FillModel, MarketOrderTiming, NextBarPrice, StaleMarketPolicy},
    holding_cost::{HeldPosition, HoldingCostModel},
    margin::{InterestDue, MarginEffect, MarginInterestModel, SpotMarginConfig},
    market::{MarketBar, MarketDepth, MarketObservation, MarketSnapshot},
    order::{
        Order, OrderKind, TimeInForce, UnindexedInactiveOrder, UnindexedOrder, UnindexedOrderKey,
        id::{ClientOrderId, OrderId, VenueOrderId},
        request::{OrderRequestCancel, OrderRequestOpen, UnindexedOrderResponseCancel},
        state::{Cancelled, Expired, Filled, Open, OrderState, UnindexedOrderState},
    },
    position::{Position, PositionReport},
    shortability::ShortabilityProvider,
    slippage::Slippage,
    trade::{AssetFees, Trade, TradeId, TradeOrigin},
};
use chrono::{DateTime, Utc};
use fnv::{FnvHashMap, FnvHashSet};
use itertools::Itertools;
use rust_decimal::Decimal;
use rustrade_instrument::{
    Side, Underlying,
    asset::name::AssetNameExchange,
    exchange::ExchangeId,
    instrument::{Instrument, kind::InstrumentKind, name::InstrumentNameExchange},
};
use rustrade_integration::collection::snapshot::Snapshot;
use smol_str::ToSmolStr;
use std::{sync::Arc, time::Duration};
use tracing::warn;

/// Everything one request obliges a driver to deliver, in the order it must deliver it.
///
/// # Ordering obligation
/// Every event in `events` must reach the client **before** `response`, and in the order given. A
/// [`SimulatedVenue`] balance is an absolute restatement, not a delta: successive fills report
/// `9_999_500`, then `9_999_000`, then `9_998_500`. Delivering two of them out of order therefore
/// does not merely reorder history, it leaves the client holding the wrong balance.
#[derive(Debug)]
pub struct VenueOutcome<Response> {
    /// Account events this request produced, in the order they must be delivered.
    pub events: Vec<UnindexedAccountEvent>,
    /// The response owed to whoever made the request.
    pub response: Response,
}

/// Response type of [`SimulatedVenue::open_order`].
pub type OpenOutcome = VenueOutcome<Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState>>;

/// Response type of [`SimulatedVenue::cancel_order`].
pub type CancelOutcome = VenueOutcome<UnindexedOrderResponseCancel>;

/// A venue's view of one instrument: what it is worth, how much of it is left to take, and when
/// that view was last replaced.
///
/// The instant is carried alongside the prices rather than inside them because a
/// [`MarketSnapshot`] says what the market is, not when it was observed — and a matching engine
/// needs both: an order resting since `T` may only be matched against a market at or after `T`.
/// The remaining depth is here for the same reason and one more: it is not even a property of the
/// market, but of what this account has already taken out of it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct VenueInstrumentMarket {
    /// Prices as of [`time_exchange`](Self::time_exchange).
    pub snapshot: MarketSnapshot,

    /// What is **left** of the size reported with [`snapshot`](Self::snapshot), after every taker
    /// fill this venue has struck against it.
    ///
    /// Reset wholesale by [`apply_market`](SimulatedVenue::apply_market), because a new
    /// observation is a new statement of what is on offer rather than an increment to the old
    /// one. Between two such observations it only ever falls, which is what stops two market
    /// orders arriving in the same tick from each taking the whole of a size that was only ever
    /// displayed once. Reading a size does not consume it; filling against it does.
    pub depth: MarketDepth,

    /// When this view was last replaced.
    pub time_exchange: DateTime<Utc>,

    /// The most recent bar this instrument was fed, or `None` if it was never fed one.
    ///
    /// Replaced only by an observation that carries a bar, so a tick between two bars leaves it
    /// standing. What [`MarketOrderTiming::NextBar`] needs to have seen before it accepts a market
    /// order to hold for the next one.
    pub bar: Option<MarketBar>,

    /// When this instrument was last observed [`fresh`](MarketObservation::fresh), or `None` if it
    /// never was.
    ///
    /// Moved only by a fresh observation, so a bar carrying a price forward with zero volume leaves
    /// it standing while it replaces [`snapshot`](Self::snapshot). What
    /// [`StaleMarketPolicy::Wait`] measures a market's age from.
    pub fresh_at: Option<DateTime<Utc>>,
}

/// Which price source a [`SimulatedVenue`] has, and therefore which orders it can accept.
///
/// A venue's regime is fixed at construction and is the gate on [`OrderKind::Limit`]. Without it a
/// limit order placed through a driver with no market feed would be accepted and then rest forever
/// with nothing that could ever match it — accepted-and-silently-never-filled, which is worse than
/// a flat rejection naming the reason.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VenueRegime {
    /// No market feed: a market order is priced from the snapshot its own request carries, and
    /// nothing can rest, so [`OrderKind::Limit`] is rejected.
    ///
    /// The regime of [`SimulatedVenue::new`], and what [`MockExchange::new`](super::MockExchange::new)
    /// drives.
    RequestPriced,

    /// A driver feeds [`apply_market`](SimulatedVenue::apply_market), so an order can rest and be
    /// matched against that feed later — and **every** fill, market orders included, is priced
    /// from that feed rather than from the snapshot a request carried.
    ///
    /// The regime of [`SimulatedVenue::new_market_driven`], and what `SimRunner` and
    /// [`MockExchange::new_market_driven`](super::MockExchange::new_market_driven) drive.
    MarketDriven,
}

/// Simulated venue state machine: synchronous, transport-free and latency-free.
///
/// Fills every market order immediately, rests limit orders that the market has not reached, and
/// keeps its own balance ledger. It has no channels and never sleeps, so a driver decides *when*
/// its output reaches a client while the venue decides *what* that output is and in which order it
/// must arrive — see [`VenueOutcome`].
///
/// # Which [`InstrumentKind`]s it accounts for
/// [`Spot`](InstrumentKind::Spot) and [`Cfd`](InstrumentKind::Cfd). A spot fill exchanges the two
/// underlying assets; a CFD fill is cash-settled in the quote asset in both directions, since there
/// is nothing to deliver and a short is a margin position rather than a stock loan — see
/// `# How a CFD is accounted`. Both carry the instrument's `contract_size` into the notional and
/// the fee, so this ledger and the engine's position accounting cannot disagree by that multiplier.
///
/// # How a spot fill is accounted
/// A spot fill exchanges the two assets. Which asset its fee is charged in is
/// [`spot_fee_asset`](Self::spot_fee_asset), a [`SpotFeeAsset`] rule; the amount comes from
/// [`fee_model`](Self::fee_model), priced in quote. Under the default,
/// [`SpotFeeAsset::Quote`], the fee is charged in quote on both sides:
/// - **A buy** pays `price × quantity` plus the fee in quote, and receives `quantity` of base.
/// - **A sell** delivers `quantity` of base, and receives `price × quantity` less the fee in quote.
///
/// Under [`SpotFeeAsset::Received`], a sell is the same, and **a buy** pays `price × quantity` in
/// quote and receives `quantity` less the fee in base, the quote fee divided by the price. A fill
/// at a price that is not positive cannot be converted, so its fee is in quote.
///
/// A fill whose fee exceeds what it receives, which only a flat per-unit fee on a near-worthless
/// fill can produce, takes the excess from the balance of the asset it receives, and is refused
/// if that cannot cover it.
///
/// With [`MockExecutionConfig::fee_asset`], a fill instead pays its fee, discounted, in a third
/// asset such as BNB, out of that asset's free balance and apart from what it exchanges: a buy
/// pays `price × quantity` in quote and receives `quantity` of base, and a sell delivers
/// `quantity` of base and receives `price × quantity`. It falls back to the rule above when that
/// balance is short, the asset has no price, or the instrument trades the asset itself. See
/// [`FeeAssetConfig`]. A fill paying in the fee asset restates that balance after the two it
/// exchanged.
///
/// The fee the fill reports in [`Trade::fees`] is the one the ledger charged, in the asset it
/// charged. So the base a fill moves is its quantity less any fee it reports in base, and the
/// engine's position, which nets a base fee from a spot quantity, agrees with this ledger's base
/// balance. A fill restates both balances it moved, the one it paid with first, before the
/// [`Trade`].
///
/// # Spot margin
/// By default this venue is a cash account: a spot order must be paid for with what the account
/// holds, so a sell of base it lacks is refused. Configured with
/// [`MockExecutionConfig::spot_margin`], it is a cross margin account instead. An order's
/// [`MarginEffect`] (its request's, else the configuration's) decides what it does to the loans: a
/// `Borrow` is lent the shortfall of the asset it pays with when the venue accepts it, and the
/// venue holds the loan against it and repays it if the order ends unfilled; a `Repay` repays
/// loans, interest first, from what its fill delivers; a `NoSideEffect` does neither. Every
/// balance then reports its loan in [`Balance::margin`], and the account's
/// holding of an asset is its `total` less what it owes. See
/// [`SpotMarginConfig`] for how much it lends and what it does not model.
///
/// Its loans are free unless it is given a [`MarginInterestModel`] through
/// [`with_margin_interest`](Self::with_margin_interest). Then each loan is charged when it is
/// taken, and at each of the model's boundaries while principal is owed in its asset:
/// - **At borrow**, on the amount lent, stamped at the instant the order was accepted. The
///   balance the order restates includes the interest, and an
///   [`AccountEventKind::CashFlow`] reporting it follows that order's balances.
/// - **At a boundary**, on the principal owed when it falls, as `[balance, cash flow]` stamped at the
///   boundary, when a driver moves the clock to or past it, as for holding costs (see
///   `# Holding costs`). A loan taken at a boundary's instant is charged at borrow, not again at
///   that boundary.
///
/// The interest is added to the loan, so `total` and `free` are unchanged and what a fill
/// delivers repays it first. Each cash flow is a
/// [`CashFlowKind::MarginInterest`], in the borrowed asset, negative, with no instrument, since a
/// cross margin loan belongs to the account rather than to a position. A charge on a new loan
/// carries [`InterestTiming::OnBorrow`] and one at a boundary [`InterestTiming::Periodic`]. A venue that books such
/// interest at the start of its hour stamps it earlier than this venue does.
///
/// [`Balance::margin`]: crate::balance::Balance::margin
///
/// # How a CFD is accounted
/// This venue keeps one net position per CFD instrument, in contracts, and splits every fill
/// against it: the part that opposes the position **closes** it, and the rest **opens** one. A
/// single fill can do both, flipping a long into a short.
/// - **Opening** posts the full notional, `price × quantity × contract_size`, as margin. This
///   venue models no leverage, so that is the conservative reading, and the requirement a spot buy
///   already carries.
/// - **Closing** pays back the margin of the quantity closed at its average entry, together with
///   the realised PnL: `closed × contract_size × (price − entry)` for a long, and the negative of
///   that for a short. The proceeds count towards what the same fill must pay, so a flip is funded
///   by the position it closes, and an account that opened with its whole balance can close.
/// - **The fee** is charged on the whole quantity.
///
/// Over a round trip the balance therefore moves by the realised PnL less the fees, as the
/// engine's own `Position` books it. The entry averages as the engine's does: an increase moves
/// it to the volume-weighted average, a reduction keeps it, and a flip enters at the fill price.
/// The position is reported by [`account_snapshot`](Self::account_snapshot), and a position that
/// a configured `initial_state` reports for a CFD is where this venue starts.
///
/// Not modelled: liquidation. A short closed at more than twice its entry has lost more than its
/// margin, and pays the shortfall as a debit. Carry is charged only when configured: see
/// `# Holding costs`.
///
/// [`Perpetual`](InstrumentKind::Perpetual), [`Future`](InstrumentKind::Future) and
/// [`Option`](InstrumentKind::Option) need funding, margin and expiry settlement, none of which this
/// venue models. They are **rejected at [`open_order`](Self::open_order)** with
/// [`ApiError::InstrumentInvalid`] rather than filled. The check lives here, not only in the
/// `rustrade` builder, because this type and its [`instruments`](Self::instruments) map are public:
/// a consumer that constructs one directly bypasses every upstream gate, and the alternative to
/// rejecting is filling a derivative as if it were deliverable stock.
///
/// # Holding costs
/// By default this venue charges no carrying cost, so a CFD position is held for free and the
/// balances and PnL of a run leave carry out. Configured with
/// [`with_holding_costs`](Self::with_holding_costs), it charges each CFD position what its
/// [`HoldingCostModel`]s say holding it costs: funding, a borrow fee, overnight financing.
/// - **When.** At each model's boundaries, as the clock reaches them. This venue has no timer, so
///   a boundary is charged when a driver next moves the clock to or past it, through
///   [`advance_time`](Self::advance_time) or [`apply_market`](Self::apply_market). Several
///   boundaries passed at once are each charged, in time order. A driver that moves the clock to
///   [`next_deadline`](Self::next_deadline) charges each one when it falls, as `SimRunner` does.
///   Charging starts at the instant the clock first moves, so a position a configured
///   `initial_state` seeds is charged from there, and never for the time before the run.
/// - **What.** The position held across the boundary, valued at the mid of this venue's market,
///   else its last price, else its entry price where there is no market, which is warned of
///   once. A position opened at a boundary's instant is not charged for it; one closed at that
///   instant is. Nothing is charged for part of a period: a position opened and closed between
///   two boundaries pays nothing, as one held past no venue cutoff would.
/// - **How.** Each charge moves the instrument's quote asset and is reported as
///   `[balance, cash flow]`: the restated balance, then an
///   [`AccountEventKind::CashFlow`] attributed to the instrument, both stamped at the boundary,
///   with a [`CashFlowId`] from this venue's own sequence. The engine adds the flow to the
///   position's `carry`, as it does a live venue's. A charge the account cannot cover is still
///   made, and takes `free` below zero, with a WARN on the charge that does so, since this venue
///   models no liquidation.
///
/// # Locates and the short-sale restriction
/// This venue lends no stock: a spot sell delivers base the account must hold, so a short sale of
/// a spot instrument is refused with [`ApiError::BalanceInsufficient`].
///
/// A CFD short is allowed without limit by default. Configured with
/// [`with_shortability`](Self::with_shortability), this venue asks its [`ShortabilityProvider`]
/// about every order that would open or increase one, at the venue's clock, and refuses it with
/// [`ApiError::BorrowRejected`] for the first of these that applies:
/// - [`NotShortable`](BorrowRejectReason::NotShortable): the provider says the instrument is not
///   shortable, or that it is delisted at or before the venue's clock
///   ([`Shortability::delisting_at`](crate::shortability::Shortability::delisting_at)).
/// - [`InventoryUnavailable`](BorrowRejectReason::InventoryUnavailable): the short would exceed
///   what the provider says is available. That is the lender's total, so the account's own short
///   counts against it, and so does every resting sell, as if it had filled. The refusal carries
///   what is left in [`BorrowReject::available`].
/// - [`ShortSaleRestricted`](BorrowRejectReason::ShortSaleRestricted): a short-sale restriction
///   is in effect and the order is marketable: a market order, or a sell limit at or below the
///   best bid (the last price, on a feed with no book). A limit above the bid rests, and so does
///   any sell limit when there is neither a bid nor a last price. A market order the
///   [`FillModel`] cannot price, such as one against a bid-only book under
///   [`MidpointFillModel`](crate::fill::MidpointFillModel), is refused as unpriceable, as it would
///   be unrestricted.
///
/// Only the short part of an order is gated: a flip from a long is measured by the short it
/// opens, and a buy, or a sell that only reduces a long once every resting sell has filled, is
/// never refused. Unknown values allow
/// the short. An order is checked once, on arrival: a resting order fills whatever the provider
/// says later, and the easy-to-borrow flag and fee rate are not read here, since a borrow fee is
/// charged by a [`HoldingCostModel`].
///
/// # ⚠️ Caller obligations and known limitations
/// - **Fund the quote asset of every instrument traded.** Every debit is quote-denominated except a
///   spot sell, which debits base, and the excess fee of a fill whose fee exceeds what it receives
///   (see `# How a spot fill is accounted`). A missing balance to debit is a **panic**, not an error: the
///   balances are this venue's own fixture, so an absent one is a mis-specified test rather than a
///   runtime condition. A margin account that lends the debit is the exception: it opens the
///   balance with the loan (see `# Spot margin`). A CFD settling in an account currency that is
///   not the quote asset still needs the **quote** asset funded — see below.
/// - **`CfdContract::settlement_asset` is not settled in.** A CFD routinely cash-settles in an
///   account currency that is not the quote asset (a GBP account trading a USD-quoted index), which
///   requires a quote→settlement conversion rate. This venue has no rate source and will not invent
///   one, so it debits and credits the quote asset and leaves the currency dimension unmodelled. The
///   field is carried on the instrument so its description stays faithful, and the engine's own
///   `InstrumentKind` — not this copy — drives PnL. A backtest whose result depends on the
///   settlement currency needs a real execution client.
/// - **The asset a spot fill receives is created at zero if the account never held it,** so only
///   the paying asset of a first order needs funding. A sell of base the account holds none of is
///   still a missing balance, since it is a debit.
/// - **Which order kinds are accepted depends on the [`VenueRegime`].** [`OrderKind::Market`]
///   always; [`OrderKind::Limit`] only on a [`MarketDriven`](VenueRegime::MarketDriven) venue;
///   every other kind never.
/// - **A resting order seeded by `initial_state` reserves nothing, because this venue never took
///   it.** An account snapshot says an order is resting and says what the balances are, but not
///   which order any held portion belongs to. Such an order still matches, and its fill debits the
///   ledger then — so the seeded balances must cover it, exactly as they must cover a market order.
///   They cannot? For spot that is a mis-specified fixture, and it **panics**, in the same class
///   as an absent balance; a CFD order is instead cancelled at fill, as described under the
///   reserved balances below. Cancelling one releases nothing and restates no balance, and neither does
///   retiring one at its deadline. Such an order may also arrive **part-filled**, carrying an
///   [`Open::filled_quantity`] this venue did not produce: only the remainder ever trades here,
///   and a fill that completes it reports no `avg_price`, because the price of the part that
///   traded elsewhere is not something this venue can know. An order **this** venue part-filled
///   before resting is the same shape, and reports no `avg_price` for the same reason — the two
///   fills were struck at different prices and this state carries one of them.
/// - **A CFD position seeded by `initial_state` is where the venue's ledger starts, and must carry
///   an entry price.** Closing it credits the margin and realised PnL measured from that price, so
///   a position with `entry_price: None` is a mis-specified fixture, and construction **panics**.
///
/// # How an order is priced
///
/// Every fill is priced from **one** market, and which market that is depends only on the
/// [`VenueRegime`]: this venue's own on a [`MarketDriven`](VenueRegime::MarketDriven) one, and the
/// snapshot the request carried
/// ([`RequestOpen::market`](crate::order::request::RequestOpen::market)) on a
/// [`RequestPriced`](VenueRegime::RequestPriced) one. A limit order is only ever accepted on a
/// `MarketDriven` venue, so it is always priced from the venue's own market; a market order follows
/// the regime.
///
/// That a `MarketDriven` venue prices a market order from its own book — rather than from the
/// sender's view at decision time — is what makes a driver's request latency price-relevant instead
/// of a pure delivery delay. The market may move between an order being decided and arriving, and a
/// fill is struck against the book it arrives to. `RequestOpen::market` is then decision-time
/// provenance and nothing else, which is what it is documented to be, and the difference between it
/// and the fill is implementation shortfall — a quantity that is identically zero when the two are
/// the same snapshot.
///
/// A `MarketDriven` venue that has not been fed an instrument **rejects** a market order in it as
/// unpriceable rather than falling back to the requester's snapshot: a venue with no market for an
/// instrument cannot fill a market order in it, and saying so is the observable failure. Silently
/// pricing from the requester's view would make the fill depend on which of the two happened to
/// hold a price, and would re-admit the very `RequestPriced` behaviour the regime exists to
/// distinguish.
///
/// Given that market, the three cases are:
/// - **A market order**, and **a limit order marketable on arrival** — priced by the [`FillModel`],
///   then moved against the order by the configured
///   [`slippage`](crate::client::mock::MockExecutionConfig::slippage). A limit order is then
///   *clamped* to its own limit: a buy never fills above it, a sell never below. Both are charged
///   [`Liquidity::Taker`].
/// - **A resting limit order** — fills at its own limit price exactly, and never reaches the
///   [`FillModel`] or the slippage. Deriving a better price from the book would credit price
///   improvement no resting order can obtain: a maker is paid the price it quoted, and improvement
///   accrues to the aggressor that crossed it. Charged [`Liquidity::Maker`].
/// - **A market order held for the next bar**, under
///   [`MarketOrderTiming::NextBar`] — priced like a market order, but from the next bar's
///   reference price rather than the market it arrived to: the [`FillModel`] is handed that price
///   as the only one there is, and the slippage moves it. Charged [`Liquidity::Taker`].
/// - **An order held on a stale market**, under
///   [`StaleMarketPolicy::Wait`] — priced as if it arrived just after the fresh observation that
///   releases it, by the rules above: a market order as a market order, a limit order as one
///   marketable on arrival if that market crosses it and as a resting one if not.
///
/// The marketable and resting rules agree exactly at the crossing point — an order arriving when
/// `best_ask == limit` fills at the limit either way — and diverge only where the order genuinely
/// is, or is not, marketable. Marketability is judged on `best_ask`/`best_bid`, falling back to
/// `last_price` when the feed supplies no book: with the default `LastPriceFillModel` and a
/// trades-only feed there is no book at all, so a book-only rule would never match anything.
///
/// # What matching does not model
/// - **No queue position.** Nothing rests ahead of this account's orders. [`OpenOrders`] ranks
///   them by price then arrival, so *which* of them fills first is reproducible, but they are
///   matched against a book with no other participants in it — an order that crosses is never
///   waiting behind anyone.
/// - **Only a taker is capped by size.** An order aggressing on arrival fills at most what
///   [`VenueInstrumentMarket::depth`] says is on offer, and draws that down as it takes it. A
///   **resting** order is not capped: when the market reaches it, it fills its whole remaining
///   quantity at its limit however little traded there. Capping it honestly would need the volume
///   that actually printed through the limit, which this venue's feed does not carry — a
///   [`MarketSnapshot`] is a view of the market, not a record of what traded — and capping it by
///   the size on the *opposite* side would be a number shaped like a cap that measures nothing a
///   cap should.
/// - **A capped taker's remainder is a maker, and makers are not capped.** So an order the book
///   could only partly fill rests the rest, and the very next tick that still crosses it fills
///   that remainder in full. The cap bounds what one order takes from one observation; it does not
///   make liquidity scarce for longer than that.
/// - **Absent size means unlimited, not unfillable.** A feed with no sizes — trades only, candles,
///   a price-only export, or a [`RequestPriced`](VenueRegime::RequestPriced) venue, which has no
///   market at all — caps nothing. See [`MarketDepth`].
/// - **Depth is this account's own bound, not the market's.** It is reset by each
///   [`apply_market`](Self::apply_market) rather than accumulated, so it stops two of this
///   account's orders double-spending one observation's size and claims nothing about anyone
///   else's.
///
/// # Which [`TimeInForce`] this venue honours
/// An unsupported one is **rejected**, never quietly treated as good-until-cancelled: that would
/// leave an order working that its sender asked to have cancelled.
///
/// | [`TimeInForce`] | [`OrderKind::Limit`] | [`OrderKind::Market`] |
/// |---|---|---|
/// | `GoodUntilCancelled { post_only: false }` | rests, or fills if marketable | fills |
/// | `GoodUntilCancelled { post_only: true }` | rests, or **cancels** if marketable | **rejected** |
/// | `ImmediateOrCancel` / `FillOrKill` | fills if marketable, else **cancels** | fills |
/// | `GoodTillDate { expiry }` | rests until `expiry`, then **expires** | fills |
/// | `GoodUntilEndOfDay` | **rejected** | fills |
/// | `AtOpen` / `AtClose` | **rejected** | **rejected** |
///
/// A market order works only on arrival, which honours every time in force that bounds *how long*
/// an order works — so most of the table is moot for one. (It fills in full wherever the book has
/// the size; what it cannot fill is cancelled, since it has no limit price to rest at.) The two
/// exceptions are real:
/// `post_only` on a market order is a promise never to take liquidity, which is all a market order
/// does; and `AtOpen`/`AtClose` say *when* an order executes rather than how long it lasts, so
/// honouring them needs a session calendar this venue has not got. Filling one on arrival would be
/// a wrong fill rather than an ignored flag.
///
/// ## A deadline is swept, not scheduled
/// This venue has no timer. A [`GoodTillDate`](TimeInForce::GoodTillDate) order is retired when a
/// driver next calls [`advance_time`](Self::advance_time) or [`apply_market`](Self::apply_market),
/// whichever comes first, and the sweep spans every instrument rather than only the one that
/// ticked. A deadline falling after the last such call is never reached at all — see
/// [`advance_time`](Self::advance_time) for what that means for a caller. A driver that keeps a
/// timeline of its own can advance the clock to each [`next_deadline`](Self::next_deadline) as it
/// falls, as `SimRunner` does, so that a deadline is reached at its own instant.
///
/// A deadline is an unconditional cutoff. An order reaching it is retired even if the very tick
/// that reached it would have crossed it, and an order that arrives already past its deadline is
/// retired without resting and without trading — otherwise whether an expired order traded would
/// depend on where the book happened to be.
///
/// # A client order id names one working order at a time
/// An open request whose [`ClientOrderId`] already names an order resting here is **rejected** with
/// [`ApiError::DuplicateClientOrderId`], whatever its kind, and the resting order is untouched: its
/// price, queue position, deadline and reservation stay as they were. Only an order that rests
/// holds its id; one that fills or is cancelled on arrival never does.
///
/// Once an order has ended its id is free, and the next order under it replaces what this venue
/// remembers of the earlier one. [`orders_ended`](Self::orders_ended), the rejection of a cancel
/// and [`account_snapshot`](Self::account_snapshot) therefore report the latest order under each
/// id.
///
/// The check follows the static ones on kind, time in force and instrument, so a malformed request
/// is reported as malformed, and comes before anything that touches the ledger.
///
/// [`OpenOrders`]: super::orders::OpenOrders
///
/// # Reserved balances
/// The ledger distinguishes held from spendable: `free` is what an order may draw on, `total` is
/// what the account holds, and the difference is held against something. An `initial_state` copied
/// from a live account with margin reserved is therefore usable as configured — it was rejected
/// outright while every order filled on arrival and the ledger could not represent the state.
///
/// Every arrival is **one** commitment against the ledger ([`AccountState::commit`]) and therefore
/// **one** balance restatement, whichever of the three shapes it has: an order that fills outright
/// settles and holds nothing; one that rests holds and settles nothing; one the book fills in part
/// does both at once, settling what traded and holding against the remainder it leaves resting. An
/// order that rests emits one more restatement later, when the market reaches it and the hold is
/// settled — never an intermediate balance the account did not hold. A configured reservation is
/// carried through untouched: settling lowers `total` by the settled amount and leaves the rest
/// held.
///
/// **An order is funded whole or refused whole.** The two legs of a part-filled arrival are asked
/// for together, so an account that cannot cover both has the order rejected with nothing moved.
/// It is not filled for the part it could afford: choosing that would be this venue substituting a
/// disposition for the one the sender asked for. Note the consequence, which is easy to be
/// surprised by — a capped order costs *more* than the same order filling outright, because its
/// remainder is held at the order's own limit while the fill struck a better price, so an order
/// can be refused for a size the book was willing to sell it.
///
/// For spot, the reservation is **exactly** what the fill will settle, not a conservative
/// over-estimate: both come from one computation at the order's own limit and its own liquidity
/// side. A conservative reservation would have to be released and re-debited on the fill,
/// producing two or three restatements for one fill and reporting balances the account never
/// held, while [`Balance::used`](crate::balance::Balance::used) misreported for the order's whole
/// life.
///
/// A resting CFD order holds only what its fill would cost **net of what the fill pays back**,
/// computed against the position when it rests. An order that only reduces a position therefore
/// holds nothing. The position can move before the order fills — another order may close what this
/// one was going to — so a CFD fill is costed again when it fills: its hold is released and the
/// fill settled afresh, still as one balance restatement. If the account can no longer afford it,
/// the order is **cancelled** rather than filled, as a venue re-checking margin at fill time would
/// cancel it. That includes an order a configured `initial_state` seeded, which for an ordinary
/// spot order would be a panic.
///
/// A resting spot order holds what it pays with, and nothing for a fee that comes out of what it
/// receives. A fill whose fee exceeds what it receives takes the excess from the asset it receives,
/// so it is costed afresh when it fills, as a CFD order is, and cancelled, seeded or not, if that
/// asset cannot cover the excess.
///
/// [`AccountState::commit`]: crate::exchange::mock::account::AccountState::commit
#[derive(Debug)]
pub struct SimulatedVenue {
    pub exchange: ExchangeId,
    pub fee_model: FeeModelConfig,
    /// Which asset a spot fill's fee is charged in. See `# How a spot fill is accounted`.
    pub spot_fee_asset: SpotFeeAsset,
    /// Prices each taker fill. Built from the configuration's
    /// [`fill_model`](MockExecutionConfig::fill_model) unless replaced by
    /// [`with_fill_model`](Self::with_fill_model).
    fill_model: Arc<dyn FillModel>,
    /// Moves each taker fill against the order, from its own seeded stream. Private: the stream's
    /// position is what makes a run reproducible from its seed, so nothing else may draw from it.
    slippage: Slippage,
    pub instruments: FnvHashMap<InstrumentNameExchange, Instrument<ExchangeId, AssetNameExchange>>,
    pub account: AccountState,
    /// This venue's own view of each instrument it trades, as of the last
    /// [`apply_market`](Self::apply_market).
    ///
    /// Empty unless a driver feeds it — see [`apply_market`](Self::apply_market) for which drivers
    /// do. Read through [`market`](Self::market).
    market: FnvHashMap<InstrumentNameExchange, VenueInstrumentMarket>,
    /// The net position of each cash-settled instrument this account holds one in.
    ///
    /// What decides how much of a CFD fill closes a position, returning its margin and realising
    /// its PnL, rather than posting new margin. Flat instruments have no entry. Private: the
    /// ledger's credits are computed from it, so editing it would pay out margin that was never
    /// posted. Reported through [`account_snapshot`](Self::account_snapshot).
    positions: FnvHashMap<InstrumentNameExchange, NetPosition>,
    /// Monotone `OrderId` source. Private: resetting it mints duplicate ids, which a consumer
    /// keying a position on an order would silently merge.
    ///
    /// Counts every order this venue booked, including those that retired without trading, so it
    /// is also what [`order_sequence`](Self::order_sequence) reports.
    order_sequence: u64,
    /// The `OrderId` the first booked order is minted with; each later one counts up from it.
    ///
    /// Zero, unless the seeded account state already carries a decimal id, in which case it is one
    /// past the highest such id, so no minted id can repeat a seeded one. A seeded id that is not
    /// decimal can never equal a minted one, so it is left out. `u128` so that one past a seeded
    /// `u64::MAX`, and every id counted up from it, stays representable.
    order_id_start: u128,
    /// Monotone `TradeId` source, independent of [`order_sequence`](Self::order_sequence).
    ///
    /// Separate because one order can print more than once — a taker the book fills in part rests
    /// the remainder and prints again when it is crossed — so an id derived from the order's would
    /// collide between the two. A real venue mints trade ids independently for the same reason;
    /// the link back to the order is [`Trade::order_id`], which is typed rather than parsed.
    trade_sequence: u64,
    /// Read via [`time_exchange`](Self::time_exchange), advanced only by
    /// [`advance_time`](Self::advance_time).
    time_exchange_latest: DateTime<Utc>,
    /// Which price source this venue has. Private: it is fixed at construction, and a consumer
    /// flipping it on a venue already holding resting orders would leave them unmatchable with no
    /// way to find out. Read through [`regime`](Self::regime).
    regime: VenueRegime,
    /// What holding a position costs over time. Empty unless set by
    /// [`with_holding_costs`](Self::with_holding_costs), and then fixed: swapping a model under
    /// a position mid-run would leave its charges to date priced by one and the rest by another.
    holding_costs: Vec<Arc<dyn HoldingCostModel>>,
    /// The instant up to which every holding-cost and interest boundary has been charged, or
    /// `None` before this venue's clock first moved.
    ///
    /// A boundary is charged when the clock first reaches it and never again, which is what makes
    /// a charge idempotent however often the clock is moved to one instant. It starts unset
    /// rather than at the epoch, so a venue charges from the first instant it is driven to, not
    /// for every boundary since 1970.
    accrued_through: Option<DateTime<Utc>>,
    /// The earliest holding-cost boundary after [`accrued_through`](Self::accrued_through) of any
    /// position held, or `None` if there is none.
    ///
    /// Cached because both [`accrue`](Self::accrue), on every input, and
    /// [`next_deadline`](Self::next_deadline) need it, and asking every model for its next
    /// boundary — a time-zone conversion for a daily cutoff — on every market tick would cost a
    /// long backtest real time. It can change only when a position does or a boundary is charged,
    /// so those are where it is recomputed.
    next_charge: Option<DateTime<Utc>>,
    /// Monotone [`CashFlowId`] source for the charges this venue posts.
    cash_flow_sequence: u64,
    /// Whether a holding cost has already been valued at a position's entry price for want of a
    /// market, which is warned of once per venue rather than at every boundary.
    valued_at_entry: bool,
    /// What this venue may lend for a CFD short, or `None` to lend without limit. Set by
    /// [`with_shortability`](Self::with_shortability).
    shortability: Option<Arc<dyn ShortabilityProvider>>,
    /// When a market order fills: on arrival, or held for its instrument's next bar. Fixed at
    /// construction from [`MockExecutionConfig::market_order_timing`]: switching it while orders
    /// are held would leave them waiting for a bar that no longer releases them.
    market_order_timing: MarketOrderTiming,
    /// What an order does on a stale market. Fixed at construction from
    /// [`MockExecutionConfig::stale_market`], for the same reason as
    /// [`market_order_timing`](Self::market_order_timing).
    stale_market: StaleMarketPolicy,
    /// What this venue lends a spot order, or `None` for a cash account. Fixed at construction
    /// from [`MockExecutionConfig::spot_margin`]: turning it off would strand the loans it made.
    spot_margin: Option<SpotMarginConfig>,
    /// The third asset this venue charges spot fees in, or `None` to charge every fee under
    /// [`spot_fee_asset`](Self::spot_fee_asset). Fixed at construction from
    /// [`MockExecutionConfig::fee_asset`].
    fee_asset: Option<FeeAssetConfig>,
    /// What this venue's loans cost in interest. `None` unless set by
    /// [`with_margin_interest`](Self::with_margin_interest), and then fixed, for the same reason
    /// as [`holding_costs`](Self::holding_costs).
    margin_interest: Option<Arc<dyn MarginInterestModel>>,
    /// The earliest interest boundary after [`accrued_through`](Self::accrued_through) of any
    /// asset the account owes principal in, or `None` if there is none.
    ///
    /// Cached, like [`next_charge`](Self::next_charge), and recomputed when a boundary is charged
    /// or when [`AccountState::loans_changed`] says which assets owe principal may have changed.
    next_interest: Option<DateTime<Utc>>,
    /// The [`AccountState::loans_changed`] count [`next_interest`](Self::next_interest) was
    /// computed at.
    next_interest_loans: u64,
}

impl SimulatedVenue {
    /// A venue with no market feed, which prices each market order from the snapshot its own
    /// request carries and accepts no [`OrderKind::Limit`].
    ///
    /// See [`VenueRegime::RequestPriced`], and [`new_market_driven`](Self::new_market_driven) for
    /// the regime that accepts limits.
    ///
    /// # Panics
    /// - If `initial_state` holds an open CFD position with no entry price: see the caller
    ///   obligations on [`SimulatedVenue`].
    /// - If `initial_state` lists one client order id more than once among its open and cancelled
    ///   orders: see [`DuplicateSeededOrder`](super::account::DuplicateSeededOrder).
    pub fn new(
        config: &MockExecutionConfig,
        instruments: FnvHashMap<InstrumentNameExchange, Instrument<ExchangeId, AssetNameExchange>>,
    ) -> Self {
        Self::with_regime(config, instruments, VenueRegime::RequestPriced)
    }

    /// A venue whose driver feeds [`apply_market`](Self::apply_market), so limit orders are
    /// accepted and a resting one is matched against that feed.
    ///
    /// Constructing one and then never calling `apply_market` produces a venue that accepts limit
    /// orders and can never match them, which is the state the regime exists to prevent — so this
    /// constructor is a driver's assertion that it will feed the venue, not a configuration knob.
    ///
    /// See [`VenueRegime::MarketDriven`].
    ///
    /// # Panics
    /// - If `initial_state` holds an open CFD position with no entry price: see the caller
    ///   obligations on [`SimulatedVenue`].
    /// - If `initial_state` lists one client order id more than once among its open and cancelled
    ///   orders: see [`DuplicateSeededOrder`](super::account::DuplicateSeededOrder).
    pub fn new_market_driven(
        config: &MockExecutionConfig,
        instruments: FnvHashMap<InstrumentNameExchange, Instrument<ExchangeId, AssetNameExchange>>,
    ) -> Self {
        Self::with_regime(config, instruments, VenueRegime::MarketDriven)
    }

    fn with_regime(
        config: &MockExecutionConfig,
        instruments: FnvHashMap<InstrumentNameExchange, Instrument<ExchangeId, AssetNameExchange>>,
        regime: VenueRegime,
    ) -> Self {
        let positions = seeded_positions(&config.initial_state, &instruments);
        let mut account = match AccountState::try_from(config.initial_state.clone()) {
            Ok(account) => account,
            Err(error) => panic!("invalid MockExecutionConfig::initial_state: {error}"),
        };
        if config.spot_margin.is_some() {
            account.enable_margin();
        }
        let order_id_start = first_unseeded_order_id(&account);

        Self {
            exchange: config.mocked_exchange,
            fee_model: config.fee_model,
            spot_fee_asset: config.spot_fee_asset,
            fill_model: Arc::new(config.fill_model),
            slippage: Slippage::new(config.slippage),
            instruments,
            account,
            market: FnvHashMap::default(),
            positions,
            order_sequence: 0,
            order_id_start,
            trade_sequence: 0,
            time_exchange_latest: Default::default(),
            regime,
            holding_costs: Vec::new(),
            accrued_through: None,
            next_charge: None,
            cash_flow_sequence: 0,
            valued_at_entry: false,
            shortability: None,
            market_order_timing: config.market_order_timing,
            stale_market: config.stale_market,
            spot_margin: config.spot_margin.clone(),
            fee_asset: config.fee_asset.clone(),
            margin_interest: None,
            next_interest: None,
            next_interest_loans: 0,
        }
    }

    /// This venue, charging each open position what `models` say holding it costs.
    ///
    /// Each model is asked for its boundaries on every instrument this venue holds a position in,
    /// and charges the position held across each one, as described on [`HoldingCostModel`]. Only
    /// a cash-settled position is charged: a spot holding is a balance on this venue, not a
    /// position. See the type's `# Holding costs` for when a charge is made and how it is
    /// reported.
    #[must_use]
    pub fn with_holding_costs(mut self, models: Vec<Arc<dyn HoldingCostModel>>) -> Self {
        self.holding_costs = models;
        self.refresh_next_charge();
        self
    }

    /// This venue, charging interest on its spot margin loans as `model` says.
    ///
    /// Each loan is charged when it is taken, on the amount lent, and at each of the model's
    /// boundaries while the account owes principal in its asset, on that principal, as described
    /// on [`MarginInterestModel`]. See the type's `# Spot margin` for how a charge is reported.
    ///
    /// # Panics
    /// If this venue has no [`MockExecutionConfig::spot_margin`]: a cash account takes no loans,
    /// so a model given to one would silently charge nothing. Or if `model` breaks its contract
    /// with a boundary not after the instant it was asked from, for a loan the account already
    /// owes.
    #[must_use]
    pub fn with_margin_interest(mut self, model: Arc<dyn MarginInterestModel>) -> Self {
        assert!(
            self.spot_margin.is_some(),
            "SimulatedVenue given a margin interest model without MockExecutionConfig::spot_margin: \
             a cash account takes no loans to charge"
        );
        self.margin_interest = Some(model);
        self.refresh_next_interest();
        self
    }

    /// This venue, pricing each taker fill with `model` rather than the configured
    /// [`fill_model`](MockExecutionConfig::fill_model).
    ///
    /// The way to plug in a model of your own, such as a size-aware impact model reading
    /// [`FillContext::quantity`]. The configured
    /// [`slippage`](MockExecutionConfig::slippage) still applies to whatever price it returns. See
    /// [`FillModel`] for what an implementation must uphold.
    ///
    /// The model is not part of the configuration, so a serialised configuration no longer says
    /// what priced the fills: its `fill_model` is unused. A venue that
    /// [`MockExchange::new`](super::MockExchange::new) drives is built from its configuration
    /// alone, so it takes no custom model.
    #[must_use]
    pub fn with_fill_model(mut self, model: Arc<dyn FillModel>) -> Self {
        self.fill_model = model;
        self
    }

    /// This venue, refusing a CFD short that `provider` does not allow.
    ///
    /// Asked on the arrival of every order that would open or increase a short, as described in
    /// the type's `# Locates and the short-sale restriction`.
    #[must_use]
    pub fn with_shortability(mut self, provider: Arc<dyn ShortabilityProvider>) -> Self {
        self.shortability = Some(provider);
        self
    }

    /// The next instant at which this venue has something to do of its own accord: an open order
    /// reaching its deadline, a holding-cost boundary of a position it holds, or an interest
    /// boundary of a loan it made.
    ///
    /// For a driver with a timeline of its own, such as `SimRunner`, which moves the clock to this
    /// instant so that an expiry or a charge happens when it is due rather than when the next
    /// market event or request happens to arrive. `None` when nothing is due.
    ///
    /// Recompute it after anything that moves this venue: an order, a fill, or the clock. A
    /// holding-cost or interest boundary is reported only once the venue's clock has first moved,
    /// since that is where charging starts.
    pub fn next_deadline(&self) -> Option<DateTime<Utc>> {
        let expiry = self.account.orders().next_expiry();
        expiry
            .into_iter()
            .chain(self.next_charge)
            .chain(self.next_interest)
            .min()
    }

    /// Recomputes [`next_charge`](Self::next_charge) from the positions held now.
    fn refresh_next_charge(&mut self) {
        self.next_charge = self.accrued_through.and_then(|after| {
            self.positions
                .keys()
                .flat_map(|instrument| {
                    self.holding_costs
                        .iter()
                        .filter_map(move |model| next_boundary(model.as_ref(), instrument, after))
                })
                .min()
        });
    }

    /// Recomputes [`next_interest`](Self::next_interest) from the loans owed now.
    fn refresh_next_interest(&mut self) {
        self.next_interest_loans = self.account.loans_changed();
        let Some(model) = self.margin_interest.as_deref() else {
            return;
        };
        self.next_interest = self.accrued_through.and_then(|after| {
            self.account
                .loans()
                .filter_map(|(asset, _)| next_interest_boundary(model, asset, after))
                .min()
        });
    }

    /// Recomputes [`next_interest`](Self::next_interest) if the assets owing principal may have
    /// changed since it was last computed. Called at the end of every input that can lend or
    /// repay.
    fn refresh_next_interest_if_loans_changed(&mut self) {
        if self.account.loans_changed() != self.next_interest_loans {
            self.refresh_next_interest();
        }
    }

    /// Which price source this venue has, and so which order kinds it accepts.
    pub fn regime(&self) -> VenueRegime {
        self.regime
    }

    /// Sets the instant this venue stamps on everything it produces from now on, retiring any
    /// order whose deadline that instant has reached.
    ///
    /// The caller owns the latency model: a driver simulating a network delay passes an instant
    /// already offset by it. The venue itself models no delay.
    ///
    /// # Deadlines are swept from here and from [`apply_market`](Self::apply_market), never on a
    /// clock of their own
    /// A [`TimeInForce::GoodTillDate`] order must stop working at the instant it says, not at
    /// whenever the next market tick happens to arrive -- otherwise a cancel sent after the
    /// nominal deadline would succeed against an order that should already have been retired, and
    /// an instrument that stops ticking would hold its expired orders open indefinitely. So both
    /// of this venue's inputs sweep.
    ///
    /// The sweep is **not** scoped to any instrument: a deadline is a property of the clock, not of
    /// a book. An order on a quiet instrument is retired by activity anywhere on the venue.
    ///
    /// ## The residual limitation, stated plainly
    /// This venue has no timer. Nothing retires an order until a driver next advances the clock or
    /// feeds a market, so a deadline falling after the last such call is never reached at all. A
    /// driver that stops driving leaves orders working past their deadline, and that is a property
    /// of the simulation rather than something a caller can configure away. A driver that wants
    /// each deadline reached at its own instant advances the clock to
    /// [`next_deadline`](Self::next_deadline).
    ///
    /// # Returns the expiries it caused, which a driver must deliver
    /// Per retired order the events are `[balance, order]` -- the released reservation, then the
    /// terminal [`Expired`] snapshot -- or `[order]` alone for an order this venue never took a
    /// reservation for, exactly as [`cancel_order`](Self::cancel_order) reports one.
    ///
    /// `#[must_use]` because a driver that advances the clock and drops the result has silently
    /// eaten the expiries, leaving its client holding orders the venue no longer has and a balance
    /// it has already released.
    ///
    /// # And the holding costs and interest it reached
    /// Every holding-cost and interest boundary between the previous instant and this one is
    /// charged first, in time order, each as `[balance, cash flow]` stamped at its boundary — see
    /// the type's `# Holding costs` and `# Spot margin`. They precede the expiries, which are
    /// stamped at `time_exchange`.
    ///
    /// # Panics
    /// If a configured [`HoldingCostModel`] or [`MarginInterestModel`] breaks its contract: a
    /// boundary not after the instant it was asked from, or a negative interest.
    #[must_use]
    pub fn advance_time(&mut self, time_exchange: DateTime<Utc>) -> Vec<UnindexedAccountEvent> {
        // Charged before the balances are restamped, so each restatement it emits keeps its own
        // boundary's stamp and the ledger still ends stamped at `time_exchange`.
        let mut events = self.accrue(time_exchange);
        self.time_exchange_latest = time_exchange;
        self.account.update_time_exchange(time_exchange);
        events.append(&mut self.sweep_expired(time_exchange));
        self.refresh_next_interest_if_loans_changed();
        events
    }

    /// Charges every holding-cost and interest boundary in `(accrued_through, now]`, the first
    /// against the position held across it and the second against the principal owed when it falls,
    /// returning `[balance, cash flow]` per charge. In boundary order, and at one boundary the
    /// holding costs, by instrument then model, before the interest, by asset.
    ///
    /// The positions and the principal owed cannot have changed since `accrued_through`: this
    /// venue's state moves only on its inputs, and each input charges what is due before it fills
    /// anything. So what is held and owed now is what was held and owed across every boundary
    /// being charged, and a gap of several boundaries is caught up exactly. Interest charged at
    /// one boundary is not principal, so it does not change what the next one charges.
    ///
    /// # Panics
    /// If a model returns a boundary that is not after the instant it was asked from, or a
    /// negative interest — see the contracts of [`HoldingCostModel`] and [`MarginInterestModel`].
    fn accrue(&mut self, now: DateTime<Utc>) -> Vec<UnindexedAccountEvent> {
        let after = match self.accrued_through {
            // The clock's first move: charging starts here.
            None => {
                self.accrued_through = Some(now);
                self.refresh_next_charge();
                self.refresh_next_interest();
                return Vec::new();
            }
            Some(after) if now <= after => return Vec::new(),
            Some(after) => after,
        };
        // Every input refreshes this as it ends, but the ledger is public, so one changed since is
        // caught here, while the cache is still computed from `after`.
        self.refresh_next_interest_if_loans_changed();
        self.accrued_through = Some(now);

        // Nothing falls in `(after, now]`, so the first boundary after `now` is still the first
        // after `after`, and the caches stay right.
        let falls = |next: Option<DateTime<Utc>>| next.is_some_and(|due| due <= now);
        if !falls(self.next_charge) && !falls(self.next_interest) {
            return Vec::new();
        }

        let mut due = Vec::new();
        for instrument in self.positions.keys() {
            for (index, model) in self.holding_costs.iter().enumerate() {
                let boundaries = boundaries_through(after, now, |from| {
                    next_boundary(model.as_ref(), instrument, from)
                });
                due.extend(
                    boundaries.map(|boundary| (boundary, Due::Holding(instrument.clone(), index))),
                );
            }
        }
        if let Some(model) = self.margin_interest.as_deref() {
            for (asset, principal) in self.account.loans() {
                let boundaries = boundaries_through(after, now, |from| {
                    next_interest_boundary(model, asset, from)
                });
                due.extend(
                    boundaries.map(|boundary| (boundary, Due::Interest(asset.clone(), principal))),
                );
            }
        }
        // Positions and balances are hashed, so their iteration order is arbitrary: sorted, so
        // one run's charges arrive in the same order as another's.
        due.sort_unstable();

        let mut events = Vec::with_capacity(due.len() * 2);
        for (boundary, due) in due {
            match due {
                Due::Holding(instrument, index) => {
                    self.charge_holding_cost(boundary, &instrument, index, &mut events);
                }
                Due::Interest(asset, principal) => {
                    self.charge_interest_boundary(boundary, &asset, principal, &mut events);
                }
            }
        }
        self.refresh_next_charge();
        self.refresh_next_interest();
        events
    }

    /// Charges the interest on `principal` of `asset`, owed when `boundary` falls, pushing
    /// `[balance, cash flow]` onto `events`, or nothing if the model charges nothing.
    fn charge_interest_boundary(
        &mut self,
        boundary: DateTime<Utc>,
        asset: &AssetNameExchange,
        principal: Decimal,
        events: &mut Vec<UnindexedAccountEvent>,
    ) {
        if let Some((balance, flow)) =
            self.charge_interest(asset, principal, InterestDue::Boundary(boundary))
        {
            events.push(self.build_account_event(Snapshot(balance)));
            events.push(self.build_account_event(AccountEventKind::CashFlow(flow)));
        }
    }

    /// Charges a loan of `principal` of `asset` what the interest model says is `due`, returning
    /// the restated balance and the cash flow that reports the charge, stamped when it was due.
    /// `None` when there is no model, or it charges nothing.
    ///
    /// # Panics
    /// If the model charges a negative interest — see [`MarginInterestModel`]'s contract.
    fn charge_interest(
        &mut self,
        asset: &AssetNameExchange,
        principal: Decimal,
        due: InterestDue,
    ) -> Option<(
        AssetBalance<AssetNameExchange>,
        CashFlow<AssetNameExchange, InstrumentNameExchange>,
    )> {
        let model = self.margin_interest.as_deref()?;
        let charge = model.charge(asset, principal, due)?;
        assert!(
            charge.interest >= Decimal::ZERO,
            "MarginInterestModel {model:?} charged negative interest {} on {principal} {asset} \
             due {due:?}",
            charge.interest
        );
        if charge.interest.is_zero() {
            return None;
        }

        let time = due.time();
        let balance = self.account.charge_interest(asset, charge.interest, time);
        let id = CashFlowId::new(self.cash_flow_sequence.to_smolstr());
        self.cash_flow_sequence += 1;

        let flow = CashFlow::new(
            CashFlowKind::MarginInterest {
                rate: charge.rate,
                principal: Some(principal),
                timing: Some(match due {
                    InterestDue::Borrow(_) => InterestTiming::OnBorrow,
                    InterestDue::Boundary(_) => InterestTiming::Periodic,
                }),
            },
            asset.clone(),
            -charge.interest,
            None,
            time,
            Some(id),
        );
        Some((balance, flow))
    }

    /// Charges one model's cost of the position in `instrument` at `boundary`, pushing
    /// `[balance, cash flow]` onto `events`, or nothing if the model charges nothing.
    fn charge_holding_cost(
        &mut self,
        boundary: DateTime<Utc>,
        instrument: &InstrumentNameExchange,
        model: usize,
        events: &mut Vec<UnindexedAccountEvent>,
    ) {
        let (Some(position), Some(terms)) = (
            self.positions.get(instrument).copied(),
            self.instruments.get(instrument),
        ) else {
            return;
        };
        let quote = terms.underlying.quote.clone();
        let contract_size = terms.kind.contract_size();
        let price = self.valuation(instrument, position);

        let held = HeldPosition::new(
            instrument,
            position.quantity,
            contract_size,
            position.entry,
            price,
        );
        let Some(charge) = self.holding_costs[model].charge(&held, boundary) else {
            return;
        };
        if charge.amount.is_zero() {
            return;
        }

        let balance = self.account.charge(&quote, charge.amount, boundary);
        // Warned when `free` goes negative, not at every charge while it stays there: an
        // underwater account charged hourly would otherwise warn every simulated hour. Each charge
        // is still reported as a cash flow.
        let free = balance.balance.free;
        if free.is_sign_negative() && !(free - charge.amount).is_sign_negative() {
            warn!(
                exchange = %self.exchange,
                %instrument,
                asset = %quote,
                amount = %charge.amount,
                free = %balance.balance.free,
                %boundary,
                "SimulatedVenue charged a holding cost the account could not cover: free balance \
                 is negative, and this venue models no liquidation"
            );
        }

        let id = CashFlowId::new(self.cash_flow_sequence.to_smolstr());
        self.cash_flow_sequence += 1;

        events.push(self.build_account_event(Snapshot(balance)));
        events.push(
            self.build_account_event(AccountEventKind::CashFlow(CashFlow::new(
                charge.kind,
                quote,
                charge.amount,
                Some(instrument.clone()),
                boundary,
                Some(id),
            ))),
        );
    }

    /// The price a holding cost values `position` in `instrument` at: the mid of this venue's
    /// market, else its last price, else the position's entry price.
    ///
    /// The entry price is a degraded valuation, used only where this venue has no market for the
    /// instrument, as on a [`RequestPriced`](VenueRegime::RequestPriced) venue. It is warned of
    /// once.
    fn valuation(&mut self, instrument: &InstrumentNameExchange, position: NetPosition) -> Decimal {
        let price = self
            .market(instrument)
            .and_then(|market| mid_or_last(&market.snapshot));

        price.unwrap_or_else(|| {
            if !self.valued_at_entry {
                self.valued_at_entry = true;
                warn!(
                    exchange = %self.exchange,
                    %instrument,
                    entry = %position.entry,
                    "SimulatedVenue has no market price to value a holding cost at, so values it \
                     at the position's entry price; warned once per venue"
                );
            }
            position.entry
        })
    }

    /// The [`MarginEffect`] an order takes: `requested`, else the spot margin configuration's
    /// default, and [`NoSideEffect`](MarginEffect::NoSideEffect) on a cash account, which neither
    /// borrows nor repays.
    fn margin_effect(&self, requested: Option<MarginEffect>) -> MarginEffect {
        match &self.spot_margin {
            Some(config) => requested.unwrap_or(config.margin_effect()),
            None => MarginEffect::NoSideEffect,
        }
    }

    /// Why an order carrying `requested` must be refused unsent, or `None` if this venue honours
    /// it: a CFD never borrows or repays, so with spot margin on it takes `NoSideEffect` alone, and
    /// a cash account takes `NoSideEffect` alone for the same reason.
    fn refused_margin_effect(
        &self,
        requested: Option<MarginEffect>,
        terms: &InstrumentTerms,
    ) -> Option<MarginEffect> {
        let borrows_here = self.spot_margin.is_some() && !terms.cash_settled;
        requested.filter(|effect| !borrows_here && *effect != MarginEffect::NoSideEffect)
    }

    /// Gives `reservation` back to `free`, repaying the loan its order took when it was placed if
    /// the spot margin configuration repays at cancel. See [`AccountState::release_reservation`].
    fn release_reservation(
        &mut self,
        reservation: &Reservation,
        time_exchange: DateTime<Utc>,
    ) -> AssetBalance<AssetNameExchange> {
        let repays = self.repays_at_cancel();
        self.account
            .release_reservation(reservation, repays, time_exchange)
    }

    /// Whether a loan its order no longer needs is repaid: the spot margin configuration's
    /// [`auto_repay_at_cancel`](SpotMarginConfig::auto_repay_at_cancel).
    fn repays_at_cancel(&self) -> bool {
        self.spot_margin
            .as_ref()
            .is_some_and(SpotMarginConfig::auto_repay_at_cancel)
    }

    /// The most a margin account may borrow of the asset `debit` pays with, for an arrival on an
    /// instrument with `terms`: see [`SpotMarginConfig`]'s `# How much it lends`.
    ///
    /// Zero unless spot margin lends, the order's `effect` is [`Borrow`](MarginEffect::Borrow),
    /// the instrument is spot, and `free` falls short of the debit, so a venue that lends nothing,
    /// or an order that needs no loan, values nothing.
    /// `market` is the snapshot the order is priced from, used to value an asset on an instrument
    /// this venue holds no market for, as on a [`RequestPriced`](VenueRegime::RequestPriced)
    /// venue.
    fn borrowable(
        &self,
        debit: &Debit,
        effect: MarginEffect,
        terms: &InstrumentTerms,
        market: Option<&MarketSnapshot>,
    ) -> Decimal {
        let Some(config) = self.spot_margin.as_ref() else {
            return Decimal::ZERO;
        };
        if effect != MarginEffect::Borrow
            || terms.cash_settled
            || self.account.free(&debit.asset) >= debit.settled + debit.reserved
        {
            return Decimal::ZERO;
        }

        let priced = market.map(|market| (&terms.underlying, market));
        let valuation = config.valuation_asset();
        let Some(asset_price) = self.price_in(&debit.asset, valuation, priced) else {
            return Decimal::ZERO;
        };

        let mut equity = Decimal::ZERO;
        let mut debt = Decimal::ZERO;
        for balance in self.account.balances() {
            let margin = balance.balance.margin.unwrap_or_default();
            let owed = margin.borrowed + margin.interest;
            let Some(price) = self.price_in(&balance.asset, valuation, priced) else {
                // A debt this venue cannot value could be any size, so it lends nothing more.
                if owed > Decimal::ZERO {
                    return Decimal::ZERO;
                }
                continue;
            };
            equity += (balance.balance.total - owed) * price;
            debt += owed * price;
        }

        let headroom = (config.max_leverage() - Decimal::ONE) * equity - debt;
        // `price_in` never values an asset at zero, so the division is safe.
        match headroom > Decimal::ZERO {
            true => headroom / asset_price,
            false => Decimal::ZERO,
        }
    }

    /// What one unit of `asset` is worth in `valuation`: one for `valuation` itself, else the mid
    /// or last price of a spot instrument pairing the two, in either direction. `None` if no
    /// instrument this venue trades has a positive price for the pair.
    ///
    /// `priced` is a pair with its snapshot, used when this venue holds no market for it. Of
    /// several instruments pairing the two, the one first by name is used, so a run values the
    /// same way every time.
    fn price_in(
        &self,
        asset: &AssetNameExchange,
        valuation: &AssetNameExchange,
        priced: Option<(&Underlying<AssetNameExchange>, &MarketSnapshot)>,
    ) -> Option<Decimal> {
        if asset == valuation {
            return Some(Decimal::ONE);
        }

        let snapshot_of = |name: &InstrumentNameExchange, underlying| {
            self.market(name).map(|market| market.snapshot).or_else(|| {
                priced
                    .filter(|(pair, _)| *pair == underlying)
                    .map(|(_, s)| *s)
            })
        };

        self.instruments
            .iter()
            .filter(|(_, instrument)| matches!(instrument.kind, InstrumentKind::Spot))
            .filter_map(|(name, instrument)| {
                let underlying = &instrument.underlying;
                let inverse = match (&underlying.base, &underlying.quote) {
                    (base, quote) if base == asset && quote == valuation => false,
                    (base, quote) if base == valuation && quote == asset => true,
                    _ => return None,
                };
                let price = mid_or_last(&snapshot_of(name, underlying)?)?;
                // A price of zero values nothing, and the inverse would divide by it.
                if price <= Decimal::ZERO {
                    return None;
                }
                let value = match inverse {
                    true => Decimal::ONE / price,
                    false => price,
                };
                Some((name, value))
            })
            .min_by(|(a, _), (b, _)| a.cmp(b))
            .map(|(_, value)| value)
    }

    /// Retires every order whose deadline `time_exchange` has reached, releasing what it held.
    ///
    /// Shared by this venue's two inputs so that a deadline means the same thing whichever one
    /// reaches it first -- see [`advance_time`](Self::advance_time).
    ///
    /// Deadlines are collected before anything is retired, because retiring removes from the very
    /// index the sweep walks. [`OpenOrders::expired_as_of`] yields them by deadline then
    /// [`ClientOrderId`], so the events are in the same order on every run.
    ///
    /// [`OpenOrders::expired_as_of`]: super::orders::OpenOrders::expired_as_of
    fn sweep_expired(&mut self, time_exchange: DateTime<Utc>) -> Vec<UnindexedAccountEvent> {
        let expired = self.account.orders().expired_as_of(time_exchange);

        if expired.is_empty() {
            return Vec::new();
        }

        let mut events = Vec::with_capacity(expired.len() * 2);

        for cid in expired {
            // Collected from this same index with nothing in between, so this always finds it.
            if let Some(resting) = self.account.remove_order(&cid) {
                events.extend(self.retire_expired(resting, time_exchange));
            }
        }

        events
    }

    /// Retires an order already taken off the book as expired, returning `[balance, order]`, or
    /// `[order]` for one the venue took no reservation for.
    fn retire_expired(
        &mut self,
        RestingOrder { order, reservation }: RestingOrder,
        time_exchange: DateTime<Utc>,
    ) -> Vec<UnindexedAccountEvent> {
        let mut events = Vec::with_capacity(2);

        // Released before the terminal snapshot, so a consumer applying them in order never sees
        // an order retired against a balance that still holds its reservation. An order the venue
        // took nothing for releases nothing -- see `OpenOrders`.
        if let Some(reservation) = reservation {
            let balance = self.release_reservation(&reservation, time_exchange);
            events.push(self.build_account_event(Snapshot(balance)));
        }

        let expired_id = order.state.id.or_client_id(&order.key.cid);
        let expired_order = Order {
            key: order.key,
            side: order.side,
            price: order.price,
            quantity: order.quantity,
            kind: order.kind,
            time_in_force: order.time_in_force,
            state: Expired {
                id: expired_id,
                time_exchange,
                filled_quantity: Some(order.state.filled_quantity),
            },
        };

        self.account.ack_expired(expired_order.clone());

        events.push(self.build_account_event(Snapshot(UnindexedOrder::from(expired_order))));
        events
    }

    pub fn time_exchange(&self) -> DateTime<Utc> {
        self.time_exchange_latest
    }

    /// Records this venue's own view of `instrument` as of `time_exchange`, from `observation`.
    ///
    /// Its [`snapshot`](MarketObservation::snapshot) **replaces** whatever was held: it is a
    /// complete view of the instrument, not a partial update, so a field that is `None` means the
    /// feed supplies no such price rather than "unchanged". Whoever calls this owns the state
    /// machine that folds a stream of market events into that view.
    ///
    /// # The [`depth`](MarketObservation::depth) replaces what is left, it does not add to it
    /// [`MarketDepth`] is the size on offer as of this observation, and it is stored as the size
    /// still *available* — drawn down by every taker fill struck against it until the next call
    /// replaces it. That is the only thing that stops two market orders arriving between two
    /// observations from each taking the whole of a size that was displayed once: reading a
    /// stored size does not consume it, so without the draw-down both would see it undiminished.
    ///
    /// It bounds this account's own aggression within one observation and claims nothing more. It
    /// is not queue position against the rest of the market, which stays unmodelled — see the
    /// type's `# What matching does not model`.
    ///
    /// A feed with no sizes passes [`MarketDepth::UNKNOWN`], which caps nothing. See
    /// [`MarketDepth`] for why that, and not "nothing is available", is what absent size means.
    ///
    /// # Not every driver supplies this
    /// A venue only has market state if something feeds it one. `SimRunner` does, routing each
    /// source market event to the venues trading that instrument before the `Engine` sees it, and
    /// so does [`MockExchange::new_market_driven`](super::MockExchange::new_market_driven), from a
    /// live feed. A request-priced venue, which [`MockExchange::new`](super::MockExchange::new)
    /// drives, is fed nothing, since a backtest feeding it the market alongside requests would
    /// re-create the look-ahead hazard that motivated the split, so it reports
    /// [`market`](Self::market) as `None` forever. That difference is a property of the regime,
    /// not an accident of wiring.
    ///
    /// # What it prices
    /// Everything this venue fills. It is the market a **resting** order is matched against, the
    /// one a limit order's marketability is judged on, and — on a
    /// [`MarketDriven`](VenueRegime::MarketDriven) venue, which is the only kind that has one — the
    /// one a **market** order is priced from. See the type's `# How an order is priced`.
    ///
    /// So feeding this is not optional for a `MarketDriven` venue: an instrument it has never been
    /// fed cannot fill a market order, and says so rather than reaching for the requester's
    /// snapshot.
    ///
    /// # Returns the fills it caused, which a driver must deliver
    /// Applying a market is what makes a resting order fill, so this returns every account event
    /// those fills produced, in the order they must be delivered — the same obligation
    /// [`VenueOutcome`] carries for a request. Per filled order the events are
    /// `[balance, trade, order]`: the trade precedes the terminal order snapshot, because a
    /// consumer routing a fill to a position needs the order still to be live when the trade
    /// arrives.
    ///
    /// They are preceded by the holding costs of every boundary since the clock last moved and the
    /// expiries this tick reached, exactly as [`advance_time`](Self::advance_time) reports them.
    /// The costs are valued at the market as it stood before this tick replaced it.
    ///
    /// # A bar releases the orders held for it
    /// Under [`MarketOrderTiming::NextBar`], an observation carrying a
    /// [`bar`](MarketObservation::bar) releases every order held on `instrument`, earliest first,
    /// stamped `time_exchange`: each market order filled at the bar's reference price as a taker,
    /// and each limit order held on a stale market decided as if it arrived to that price. Their
    /// events follow the expiries and precede the resting fills, since a held order trades at the
    /// start of the bar and a resting one is crossed during it.
    /// [`fills_ahead_of`](Self::fills_ahead_of) says beforehand whether an observation will
    /// release anything this way.
    ///
    /// Under [`StaleMarketPolicy::Wait`], a bar that is not [`fresh`](MarketObservation::fresh)
    /// releases nothing, and cancels the immediate-or-cancel and fill-or-kill orders held for it.
    ///
    /// # A fresh observation releases the orders waiting for one
    /// Under [`StaleMarketPolicy::Wait`] with [`MarketOrderTiming::OnArrival`], a
    /// [`fresh`](MarketObservation::fresh) observation releases every order that arrived on a
    /// stale `instrument`, earliest first, each decided as if it had arrived just after this
    /// observation, stamped `time_exchange`: a market order fills, and a limit order trades what
    /// the market crosses and rests the rest at its limit. Their events follow the resting fills,
    /// which the observation crossed first, so a limit order resting on release is not crossed by
    /// the observation that released it.
    ///
    /// # An observation that is not fresh crosses no resting order
    /// Under [`StaleMarketPolicy::Wait`], an observation that is not
    /// [`fresh`](MarketObservation::fresh) still moves the price the venue holds, but fills no
    /// resting order, however far it moves: it is not evidence that anything traded there.
    ///
    /// `#[must_use]` because a driver that applies the market and drops the result has silently
    /// eaten the fills, leaving its client holding an order the venue no longer has.
    ///
    /// # Panics
    /// If a configured [`HoldingCostModel`] or [`MarginInterestModel`] breaks its contract: a
    /// boundary not after the instant it was asked from, or a negative interest.
    #[must_use]
    pub fn apply_market(
        &mut self,
        instrument: &InstrumentNameExchange,
        observation: MarketObservation,
        time_exchange: DateTime<Utc>,
    ) -> Vec<UnindexedAccountEvent> {
        // Charged before the snapshot is replaced, so a boundary this tick passed is valued at the
        // market as of that boundary rather than at a price observed after it.
        let mut events = self.accrue(time_exchange);

        let MarketObservation {
            snapshot,
            depth,
            bar,
            fresh,
        } = observation;
        let entry = self.market.entry(instrument.clone()).or_default();
        entry.snapshot = snapshot;
        entry.depth = depth;
        entry.time_exchange = time_exchange;
        if bar.is_some() {
            entry.bar = bar;
        }
        if fresh {
            entry.fresh_at = Some(time_exchange);
        }

        // Swept before matching, so an order whose deadline this tick has reached cannot trade on
        // the very tick that retires it -- see `advance_time`.
        events.append(&mut self.sweep_expired(time_exchange));
        // Under `Wait`, an observation that shows nothing trading moves the price but fills no one.
        let crosses_resting = fresh || !matches!(self.stale_market, StaleMarketPolicy::Wait { .. });
        match self.market_order_timing {
            MarketOrderTiming::NextBar(price) => {
                if let Some(bar) = bar {
                    if self.bar_releases(&observation) {
                        events.append(&mut self.release(
                            instrument,
                            Release::Bar(&bar, price),
                            time_exchange,
                        ));
                    } else {
                        events.append(&mut self.cancel_held_immediate(instrument, time_exchange));
                    }
                }
                if crosses_resting {
                    events.append(&mut self.match_resting(instrument, snapshot, time_exchange));
                }
            }
            MarketOrderTiming::OnArrival => {
                if crosses_resting {
                    events.append(&mut self.match_resting(instrument, snapshot, time_exchange));
                }
                // Only `Wait` holds an order under `OnArrival`, so no other policy has one to look
                // up.
                if fresh && matches!(self.stale_market, StaleMarketPolicy::Wait { .. }) {
                    events.append(&mut self.release(
                        instrument,
                        Release::Market(&snapshot),
                        time_exchange,
                    ));
                }
            }
        }
        self.refresh_next_interest_if_loans_changed();
        events
    }

    /// Whether applying `observation` to `instrument` releases orders held for its bar,
    /// whose fills a driver must deliver **ahead of** the observation itself — see
    /// [`MarketOrderTiming::NextBar`].
    ///
    /// Asked before [`apply_market`](Self::apply_market), since applying the observation is what
    /// empties the hold. `false` for a fill released by a fresh observation under
    /// [`StaleMarketPolicy::Wait`] alone, which follows its observation as a resting fill does.
    pub fn fills_ahead_of(
        &self,
        instrument: &InstrumentNameExchange,
        observation: &MarketObservation,
    ) -> bool {
        matches!(self.market_order_timing, MarketOrderTiming::NextBar(_))
            && self.bar_releases(observation)
            && self.account.orders().holds(instrument)
    }

    /// Whether `observation` carries a bar that releases the orders held for one: any bar,
    /// unless [`StaleMarketPolicy::Wait`] asks for one something traded in.
    fn bar_releases(&self, observation: &MarketObservation) -> bool {
        observation.bar.is_some()
            && (observation.fresh || !matches!(self.stale_market, StaleMarketPolicy::Wait { .. }))
    }

    /// Retires every order still held as expired, filled nothing, stamped `time_exchange`:
    /// the data has ended before the bar or the fresh observation it was waiting for.
    ///
    /// For a driver at the end of its data, so that no order it accepted is left unanswered. Per
    /// order the events are `[balance, order]`, the released hold then the terminal [`Expired`]
    /// snapshot, as [`advance_time`](Self::advance_time) reports a deadline it reached. Pass the
    /// last instant of the run: this moves no clock and charges no holding cost.
    ///
    /// # Panics
    /// If the configured [`MarginInterestModel`] breaks its contract with a boundary not after the
    /// instant it was asked from, when the venue next looks for one after a loan is repaid.
    #[must_use]
    pub fn expire_held(&mut self, time_exchange: DateTime<Utc>) -> Vec<UnindexedAccountEvent> {
        let held = self.account.orders().held();
        let mut events = Vec::with_capacity(held.len() * 2);
        for cid in held {
            // Collected from this same index with nothing in between, so this always finds it.
            if let Some(resting) = self.account.remove_order(&cid) {
                events.extend(self.retire_expired(resting, time_exchange));
            }
        }
        self.refresh_next_interest_if_loans_changed();
        events
    }

    /// Fills every resting order on `instrument` that `snapshot` has moved to or through.
    ///
    /// Walks each side best-first and stops at the first order that does not cross, which
    /// [`OpenOrders::resting`]'s price-time ordering makes correct: the crossing test is monotone
    /// in price down a side, so the first order that fails it is followed only by worse ones.
    ///
    /// # What crosses is the remainder
    /// A crossing order fills what is **left** of it: its quantity less whatever
    /// [`Open::filled_quantity`] says has already traded. That is its whole quantity for every
    /// order this venue books itself, which fills nothing before it rests -- but not for one a
    /// configured `initial_state` seeds, which may arrive carrying a live account's partial fill.
    /// Settling and printing the whole quantity of such an order would double-count the part that
    /// traded elsewhere, in the balance ledger and in the trade ledger alike.
    ///
    /// [`OpenOrders::resting`]: super::orders::OpenOrders::resting
    fn match_resting(
        &mut self,
        instrument: &InstrumentNameExchange,
        snapshot: MarketSnapshot,
        time_exchange: DateTime<Utc>,
    ) -> Vec<UnindexedAccountEvent> {
        // Collected before anything is filled: matching removes from the very book it walks, and
        // each entry carries its own limit so the fill loop never re-reads an order it just took
        // off the book. `resting` only yields queued orders, and only a priced order is queued.
        let mut crossing: Vec<(ClientOrderId, Decimal)> = Vec::new();
        for side in [Side::Buy, Side::Sell] {
            crossing.extend(
                self.account
                    .orders()
                    .resting(instrument, side)
                    .take_while(|order| {
                        order
                            .price
                            .is_some_and(|limit| crosses(side, limit, &snapshot))
                    })
                    .filter_map(|order| Some((order.key.cid.clone(), order.price?))),
            );
        }

        if crossing.is_empty() {
            return Vec::new();
        }

        // One lookup for the whole instrument: every crossing order is on it by construction.
        let terms = match self.instrument_terms(instrument) {
            Ok(terms) => terms,
            // Unreachable: an order cannot rest on an instrument this venue rejected at open. A
            // venue whose `instruments` map was mutated afterwards would reach it, and dropping the
            // fills silently is the one thing this method must not do.
            Err(error) => panic!(
                "SimulatedVenue holds resting orders on an instrument it cannot price: {error}"
            ),
        };

        let mut events = Vec::with_capacity(crossing.len() * 4);

        for (cid, limit) in crossing {
            // Collected from this same book with nothing in between, so this always finds it.
            let Some(RestingOrder { order, reservation }) = self.account.remove_order(&cid) else {
                continue;
            };

            // Only what has not already traded crosses. An order can reach this book carrying a
            // filled quantity -- a configured `initial_state` seeds one straight out of a live
            // account -- and settling or printing the whole of it again would charge the ledger a
            // second time for a portion that traded before this venue ever held the order.
            let remaining = order.state.quantity_remaining(order.quantity);

            debug_assert!(
                remaining > Decimal::ZERO,
                "resting order {cid} arrived with {} of {} already filled, so crossing it trades \
                 nothing: an order with no quantity left to trade does not belong on the book",
                order.state.filled_quantity,
                order.quantity
            );

            // A resting order fills at its own limit, never at a price derived from the book --
            // see the type's `# How an order is priced` -- and takes no liquidity, so it is
            // charged the maker rate. A cash-settled one is priced against the position as it
            // stands now, which may not be the one it rested against.
            let settlement = self.fill_settlement(
                &terms,
                self.net_position(&terms, instrument),
                order.side,
                remaining,
                limit,
                Liquidity::Maker,
            );

            let mut committed = match self.settle_resting(
                &order,
                &terms,
                reservation,
                &settlement,
                time_exchange,
            ) {
                RestingSettlement::Settled(committed) => committed,
                RestingSettlement::Unaffordable { released } => {
                    events.extend(self.cancel_unfilled(order, released, time_exchange));
                    continue;
                }
            };
            self.take_fee_apart(&settlement, &mut committed, time_exchange);

            let trade = self.print_fill(
                &terms,
                &order,
                Fill {
                    quantity: remaining,
                    price: limit,
                },
                settlement.fees,
                time_exchange,
            );
            let order_id = trade.order_id.clone();

            // The order is terminal, and says so as `Inactive(FullyFilled)` rather than as an
            // `Open` carrying a complete fill. Both denote the same fact, but only this one can
            // carry the price it filled at.
            //
            // `filled_quantity` is the order's whole quantity -- what it has done in total, not
            // what this cross did -- while `avg_price` is reported only when this venue struck
            // every fill behind it, which is exactly an order that reached the book with nothing
            // done. An order that arrived part-filled took that part at a price this venue never
            // saw, so it reports no average rather than passing one fill's price off as the mean
            // of two. That is what `Filled::avg_price` being optional is for.
            let filled = Order {
                key: order.key,
                side: order.side,
                price: order.price,
                quantity: order.quantity,
                kind: order.kind,
                time_in_force: order.time_in_force,
                state: Filled::new(
                    order_id,
                    time_exchange,
                    order.quantity,
                    order.state.filled_quantity.is_zero().then_some(limit),
                ),
            };
            self.account.ack_filled(filled.clone());
            let filled = filled.map_state(OrderState::fully_filled);

            self.push_committed(&mut events, committed);
            events.push(self.build_account_event(trade));
            events.push(self.build_account_event(Snapshot(filled)));
        }

        events
    }

    /// Releases every order held on `instrument`, earliest arrival first, priced from `release`:
    /// the bar it was held for under [`MarketOrderTiming::NextBar`], or the market a fresh
    /// observation left under [`StaleMarketPolicy::Wait`]. A market order fills, and a limit order
    /// is decided as if it arrived to that market — see
    /// [`release_held_limit`](Self::release_held_limit).
    fn release(
        &mut self,
        instrument: &InstrumentNameExchange,
        release: Release<'_>,
        time_exchange: DateTime<Utc>,
    ) -> Vec<UnindexedAccountEvent> {
        let held = self.account.take_held(instrument);
        if held.is_empty() {
            return Vec::new();
        }

        let terms = match self.instrument_terms(instrument) {
            Ok(terms) => terms,
            // Unreachable, as in `match_resting`: an order is held only on an instrument this
            // venue accepted it for.
            Err(error) => {
                panic!("SimulatedVenue holds orders on an instrument it cannot price: {error}")
            }
        };

        let mut events = Vec::with_capacity(held.len() * 4);
        for cid in held {
            // Handed out by the held index with nothing in between, so this always finds it.
            let Some(resting) = self.account.remove_order(&cid) else {
                continue;
            };
            // Only a limit order is held with a price: `hold_on_arrival` drops a market order's.
            debug_assert_eq!(
                resting.order.kind == OrderKind::Limit,
                resting.order.price.is_some(),
                "SimulatedVenue held {} as {:?} with price {:?}: only a limit order is held with \
                 a price",
                resting.order.key.cid,
                resting.order.kind,
                resting.order.price
            );
            events.extend(match resting.order.price {
                Some(limit) => {
                    self.release_held_limit(resting, limit, release, &terms, time_exchange)
                }
                None => self.fill_held(resting, release, &terms, time_exchange),
            });
        }
        events
    }

    /// Cancels every immediate-or-cancel and fill-or-kill market order held on `instrument` for a
    /// bar that has arrived with nothing traded in it, leaving the rest held for the next one — see
    /// [`StaleMarketPolicy::Wait`]. Per order the events are `[balance, order]`.
    fn cancel_held_immediate(
        &mut self,
        instrument: &InstrumentNameExchange,
        time_exchange: DateTime<Utc>,
    ) -> Vec<UnindexedAccountEvent> {
        let orders = self.account.orders();
        let immediate = orders
            .held_on(instrument)
            .iter()
            .filter(|cid| {
                orders.get(cid).is_some_and(|order| {
                    matches!(
                        order.time_in_force,
                        TimeInForce::ImmediateOrCancel | TimeInForce::FillOrKill
                    )
                })
            })
            .cloned()
            .collect::<Vec<_>>();

        let mut events = Vec::with_capacity(immediate.len() * 2);
        for cid in immediate {
            // Collected from this same index with nothing in between, so this always finds it.
            if let Some(RestingOrder { order, reservation }) = self.account.remove_order(&cid) {
                let released = reservation
                    .map(|reservation| self.release_reservation(&reservation, time_exchange));
                events.extend(self.cancel_unfilled(order, released, time_exchange));
            }
        }
        events
    }

    /// Fills one held market order, as a taker arriving at the price `release` gives it, and
    /// returns `[balance.., trade, order]`, or `[balance, order]` for one it cancels.
    ///
    /// What the order would cost was held when it arrived, at the price the venue held then. The
    /// release's price is another, so the hold is released and the fill costed afresh, as a
    /// resting CFD fill is, and an order the account can no longer afford is cancelled — see
    /// [`settle_resting`](Self::settle_resting). So is one the release's market cannot price.
    fn fill_held(
        &mut self,
        RestingOrder { order, reservation }: RestingOrder,
        release: Release<'_>,
        terms: &InstrumentTerms,
        time_exchange: DateTime<Utc>,
    ) -> Vec<UnindexedAccountEvent> {
        let side = order.side;
        let quantity = order.state.quantity_remaining(order.quantity);

        let reference = match release {
            Release::Bar(bar, price) => {
                // The bar's price is handed to the model as the only price there is, so a model
                // reading the last price prices from it, and the configured slippage moves it, as
                // for any taker. A model that needs a book cannot price from it and is given the
                // reference itself.
                let reference = price.reference(side, bar);
                let at_reference = MarketSnapshot::from_last_price(Some(reference));
                Some(
                    self.fill_model
                        .fill_price(&FillContext::new(side, quantity, &at_reference))
                        .unwrap_or(reference),
                )
            }
            // Priced exactly as an order arriving now would be.
            Release::Market(market) => self
                .fill_model
                .fill_price(&FillContext::new(side, quantity, market)),
        };
        // A fresh observation leaving a market the model cannot price for this side: a quote with
        // only the other side of the book, say. On arrival that order would be refused as
        // unpriceable; having been accepted, it is cancelled.
        let Some(reference) = reference else {
            let released = reservation
                .map(|reservation| self.release_reservation(&reservation, time_exchange));
            return self.cancel_unfilled(order, released, time_exchange);
        };

        // What the releasing observation has to give this order, which is all of it wherever no
        // size is known -- as on every candle feed.
        let filled_quantity = match self.depth_available(&order.key.instrument, side) {
            Some(available) => quantity.min(available),
            None => quantity,
        };
        // Its time in force decides what becomes of a part the observation cannot fill, as on
        // arrival: a deadline already reached was swept before it released anything.
        let kill = order.time_in_force == TimeInForce::FillOrKill;
        if filled_quantity <= Decimal::ZERO || (filled_quantity < quantity && kill) {
            let released = reservation
                .map(|reservation| self.release_reservation(&reservation, time_exchange));
            return self.cancel_unfilled(order, released, time_exchange);
        }

        // Drawn only now that the order is known to trade, and handed back if the ledger refuses
        // it, as in `fill_on_arrival`.
        let slippage_before = self.slippage.clone();
        let fill_price = self.slippage.apply(side, reference);

        let settlement = self.fill_settlement(
            terms,
            self.net_position(terms, &order.key.instrument),
            side,
            filled_quantity,
            fill_price,
            Liquidity::Taker,
        );

        let mut committed =
            match self.settle_resting_afresh(terms, reservation, &settlement, time_exchange) {
                RestingSettlement::Settled(committed) => committed,
                RestingSettlement::Unaffordable { released } => {
                    self.slippage = slippage_before;
                    return self.cancel_unfilled(order, released, time_exchange);
                }
            };
        self.take_fee_apart(&settlement, &mut committed, time_exchange);

        self.consume_depth(&order.key.instrument, side, filled_quantity);
        let fill = Fill {
            quantity: filled_quantity,
            price: fill_price,
        };
        let trade = self.print_fill(terms, &order, fill, settlement.fees, time_exchange);

        // Filled outright, or cancelled carrying what the observation's size allowed: a market
        // order has no limit to rest a remainder at, as on arrival.
        let terminal = if filled_quantity == quantity {
            let filled = Order {
                key: order.key,
                side,
                price: order.price,
                quantity: order.quantity,
                kind: order.kind,
                time_in_force: order.time_in_force,
                state: Filled::new(
                    trade.order_id.clone(),
                    time_exchange,
                    order.quantity,
                    Some(fill_price),
                ),
            };
            self.account.ack_filled(filled.clone());
            filled.map_state(OrderState::fully_filled)
        } else {
            let cancelled = Order {
                key: order.key,
                side,
                price: order.price,
                quantity: order.quantity,
                kind: order.kind,
                time_in_force: order.time_in_force,
                state: Cancelled {
                    id: trade.order_id.clone(),
                    time_exchange,
                    filled_quantity: Some(filled_quantity),
                },
            };
            self.account.ack_cancelled(cancelled.clone());
            UnindexedOrder::from(cancelled)
        };

        let mut events = Vec::with_capacity(4);
        self.push_committed(&mut events, committed);
        events.push(self.build_account_event(trade));
        events.push(self.build_account_event(Snapshot(terminal)));
        events
    }

    /// Releases one limit order held on a stale market, as if it had arrived to the market
    /// `release` gives it, and returns `[balance.., trade, order]` for one that trades,
    /// `[balance, order]` for one that joins the book whole or that it cancels.
    ///
    /// Decided against that market as an arriving limit order is decided against the market it
    /// arrives to:
    /// - one the market crosses trades as a taker, priced by the venue's [`FillModel`], moved by
    ///   its slippage and capped at its limit, up to the size the market has, and what is left of
    ///   it joins the book at its limit;
    /// - one the market does not cross joins the book whole, at its limit;
    /// - a post-only one the market crosses is cancelled, having traded nothing.
    ///
    /// A bar's reference price is handed over as the only price there is, as for a held market
    /// order — see [`fill_held`](Self::fill_held).
    ///
    /// What the order would cost was held when it arrived, at the market the venue held then. The
    /// hold is released and the order costed afresh, its fill and what it rests as one
    /// requirement, as on arrival, so an order the account can no longer afford is cancelled.
    /// Whatever joins the book is stamped `time_exchange`, which is when it joined the queue.
    fn release_held_limit(
        &mut self,
        RestingOrder { order, reservation }: RestingOrder,
        limit: Decimal,
        release: Release<'_>,
        terms: &InstrumentTerms,
        time_exchange: DateTime<Utc>,
    ) -> Vec<UnindexedAccountEvent> {
        let side = order.side;
        let quantity = order.state.quantity_remaining(order.quantity);

        let (market, reference) = match release {
            Release::Bar(bar, price) => {
                let reference = price.reference(side, bar);
                (
                    MarketSnapshot::from_last_price(Some(reference)),
                    Some(reference),
                )
            }
            Release::Market(market) => (*market, None),
        };

        let marketable = crosses(side, limit, &market);
        let post_only = matches!(
            order.time_in_force,
            TimeInForce::GoodUntilCancelled { post_only: true }
        );
        if marketable && post_only {
            let released = reservation
                .map(|reservation| self.release_reservation(&reservation, time_exchange));
            return self.cancel_unfilled(order, released, time_exchange);
        }

        // What the market has to give this order: nothing if it does not cross, and all of it
        // wherever no size is known.
        let filled_quantity = match self.depth_available(&order.key.instrument, side) {
            _ if !marketable => Decimal::ZERO,
            Some(available) => quantity.min(available),
            None => quantity,
        };
        let unfilled = quantity - filled_quantity;

        // Drawn only if the order trades, and handed back if the ledger refuses it, as in
        // `fill_on_arrival`.
        let slippage_before = self.slippage.clone();
        let position = self.net_position(terms, &order.key.instrument);
        let fill = (filled_quantity > Decimal::ZERO).then(|| {
            // A crossed market prices it, but a model that needs more of a book than the market
            // has falls back to the bar's reference price, or to the limit, as on arrival.
            let price = self
                .fill_model
                .fill_price(&FillContext::new(side, quantity, &market))
                .or(reference)
                .unwrap_or(limit);
            let price = clamp_to_limit(side, self.slippage.apply(side, price), limit);
            let settlement = self.fill_settlement(
                terms,
                position,
                side,
                filled_quantity,
                price,
                Liquidity::Taker,
            );
            (price, settlement)
        });

        // What resting the rest will cost, priced as the fill that settles it will be: at the
        // limit, as the maker, against the position the fill leaves.
        let held = (unfilled > Decimal::ZERO).then(|| {
            let position = match &fill {
                Some((price, _)) => position.after(side, filled_quantity, *price),
                None => position,
            };
            self.settlement(terms, position, side, unfilled, limit, Liquidity::Maker)
        });

        let (debit, credit) = match (&fill, &held) {
            (Some((_, fill)), Some(held)) => (fill.settled_holding(held), Some(&fill.credit)),
            (Some((_, fill)), None) => (fill.settled(), Some(&fill.credit)),
            (None, Some(held)) => (held.reserved(), None),
            (None, None) => unreachable!(
                "SimulatedVenue released {} with nothing to trade or rest: it holds only an order \
                 with a positive quantity, which `open_order_inner` checks, and such an order \
                 either trades or rests some of it",
                order.key.cid
            ),
        };
        let effect = reservation.as_ref().map_or_else(
            || self.margin_effect(None),
            |reservation| reservation.effect,
        );
        let (mut committed, loan) =
            match self.commit_afresh(terms, reservation, &debit, credit, time_exchange) {
                Recommitted::Committed { commitment, loan } => (commitment, loan),
                Recommitted::Unaffordable { released } => {
                    self.slippage = slippage_before;
                    return self.cancel_unfilled(order, released, time_exchange);
                }
            };

        let mut events = Vec::with_capacity(4);
        let mut filled_total = order.state.filled_quantity;
        let mut trade = None;
        if let Some((price, settlement)) = fill {
            self.take_fee_apart(&settlement, &mut committed, time_exchange);
            self.consume_depth(&order.key.instrument, side, filled_quantity);
            let fill = Fill {
                quantity: filled_quantity,
                price,
            };
            trade = Some(self.print_fill(terms, &order, fill, settlement.fees, time_exchange));
            filled_total += filled_quantity;
        }

        let terminal = match held {
            // What is left joins the book, carrying what has already traded, holding the loan
            // this release left the order with, as a remainder rested on arrival does.
            Some(held) => {
                let open = Open::new(order.state.id.clone(), time_exchange, filled_total);
                let rested = Order {
                    key: order.key,
                    side,
                    price: order.price,
                    quantity: order.quantity,
                    kind: order.kind,
                    time_in_force: order.time_in_force,
                    state: open,
                };
                self.book_rested(
                    rested.clone(),
                    Reservation {
                        borrowed: loan.min(held.requirement()),
                        amount: held.requirement(),
                        asset: held.asset,
                        effect,
                    },
                );
                rested.map_state(OrderState::active)
            }
            // Filled outright by this one trade, which carries the order's id: a held order has
            // traded nothing before its release, so the trade's price is the mean of its fills.
            None => {
                let Some(trade) = &trade else {
                    unreachable!("an order with nothing left to rest has traded");
                };
                let filled = Order {
                    key: order.key,
                    side,
                    price: order.price,
                    quantity: order.quantity,
                    kind: order.kind,
                    time_in_force: order.time_in_force,
                    state: Filled::new(
                        trade.order_id.clone(),
                        time_exchange,
                        order.quantity,
                        Some(trade.price),
                    ),
                };
                self.account.ack_filled(filled.clone());
                filled.map_state(OrderState::fully_filled)
            }
        };

        self.push_committed(&mut events, committed);
        if let Some(trade) = trade {
            events.push(self.build_account_event(trade));
        }
        events.push(self.build_account_event(Snapshot(terminal)));
        events
    }

    /// Records `fill` of `order`, an order this venue already holds, and returns the trade it
    /// printed, acknowledged in the ledger.
    ///
    /// The trade's cumulative is everything the order had already done plus `fill`.
    fn print_fill(
        &mut self,
        terms: &InstrumentTerms,
        order: &OpenOrder,
        fill: Fill,
        fees: AssetFees<AssetNameExchange>,
        time_exchange: DateTime<Utc>,
    ) -> Trade<AssetNameExchange, InstrumentNameExchange> {
        let Fill { quantity, price } = fill;
        self.record_fill(terms, &order.key.instrument, order.side, fill);

        let trade = Trade {
            id: self.trade_id_sequence_fetch_add(),
            order_id: order.state.id.or_client_id(&order.key.cid),
            instrument: order.key.instrument.clone(),
            strategy: order.key.strategy.clone(),
            time_exchange,
            side: order.side,
            price,
            quantity,
            order_filled_quantity: Some(order.state.filled_quantity + quantity),
            fees,
            origin: TradeOrigin::Order,
            position_side: None,
            client_order_id: Some(order.key.cid.clone()),
        };

        self.account.ack_trade(trade.clone());
        trade
    }

    /// Moves the balances one resting fill pays with and receives, and returns the restatements it
    /// owes.
    ///
    /// # A cash-settled fill is costed again when it fills
    /// What a CFD order holds was computed against the position when it rested, and the position
    /// may have moved since: another order may have closed what this one was going to close, so
    /// this one now opens a position instead. Its hold is therefore released and the fill costed
    /// afresh, as one ledger move with one restatement. If the account can no longer afford it,
    /// the result is [`RestingSettlement::Unaffordable`] and the order is cancelled, as a venue
    /// re-checking margin at fill time would cancel it, rather than filled with balance the account
    /// does not have. A spot fill whose fee exceeds what it receives is the same: its hold covers
    /// what it pays with, not the excess fee taken from the asset it receives, so it is checked
    /// afresh.
    ///
    /// # Panics
    /// Panics if a spot order the venue holds nothing against cannot be afforded when it fills —
    /// see this type's caller obligations on `initial_state` — unless its fee exceeds what it
    /// receives, which is checked afresh and cancelled like a CFD order.
    fn settle_resting(
        &mut self,
        order: &OpenOrder,
        terms: &InstrumentTerms,
        reservation: Option<Reservation>,
        settlement: &Settlement,
        time_exchange: DateTime<Utc>,
    ) -> RestingSettlement {
        let delivery = match &settlement.credit {
            // A fill whose fee is taken apart costs less than its order holds, the cost of its
            // fee falling back, whenever that fee would have been on top of what it pays with.
            _ if settlement.fee_apart => {
                return self.settle_resting_afresh(terms, reservation, settlement, time_exchange);
            }
            Credit::Delivery(delivery) if !delivery.amount.is_sign_negative() => delivery,
            // A cash-settled fill, or a spot fill whose fee exceeds what it receives.
            Credit::PaidBack(_) | Credit::Delivery(_) => {
                return self.settle_resting_afresh(terms, reservation, settlement, time_exchange);
            }
        };

        // An order seeded by `initial_state` holds nothing, and takes the venue's default effect.
        let effect = reservation.as_ref().map_or_else(
            || self.margin_effect(None),
            |reservation| reservation.effect,
        );
        let Some(Reservation { asset, amount, .. }) = reservation else {
            // Seeded by a configured `initial_state`, so nothing is held against it and the fill
            // debits now. An account that cannot cover it is a mis-specified fixture, in the same
            // class as an absent balance, and gets the same treatment, unless a margin account
            // lends what it lacks.
            let debit = settlement.settled();
            return RestingSettlement::Settled(
                self.commit(
                    &debit,
                    Some(&settlement.credit),
                    effect,
                    terms,
                    None,
                    time_exchange,
                )
                .unwrap_or_else(|insufficient| {
                    panic!(
                        "SimulatedVenue cannot afford the fill of resting order {}, which was \
                             seeded by `initial_state` and so reserved nothing: {} of {} free, {} \
                             required",
                        order.key.cid, insufficient.free, insufficient.asset, insufficient.required
                    )
                }),
            );
        };

        // Reserve exactly what will be settled, then settle exactly what was reserved: the client
        // sees one balance restatement per asset, and never a balance the account did not hold.
        // Both sides are the unfilled remainder, priced at the order's own limit as the maker --
        // `rest_order` holds for it and this settles it, so the two agree by construction rather
        // than by two formulas coinciding. Only spot reaches this: what a spot fill costs does not
        // depend on a position, so nothing can have moved it since the order rested.
        debug_assert!(
            asset == settlement.asset && amount == settlement.amount,
            "resting order {} reserved {amount} of {asset} but its fill settles {} of {}: the \
             reservation and the fill disagree, so a balance the account never held would be \
             reported",
            order.key.cid,
            settlement.amount,
            settlement.asset
        );

        // A loan taken when the order was placed stays owed: it paid for this fill.
        let paid = self.account.settle(&asset, amount, time_exchange);
        let received = self.account.deliver(delivery, effect, time_exchange);
        RestingSettlement::Settled(Commitment::from(Committed {
            paid,
            received: Some(received),
            borrowed: Decimal::ZERO,
        }))
    }

    /// Releases a resting fill's hold and settles the fill afresh, restating each asset it moved
    /// once, or reports it unaffordable. See [`settle_resting`](Self::settle_resting).
    ///
    /// On a margin account, a loan the order took when it was placed stays owed while the fill is
    /// costed afresh, which may borrow more. A fill that costs less than was held repays the part
    /// of the loan it no longer needs, and an order that turns out unaffordable repays all of it,
    /// as a cancelled order does.
    fn settle_resting_afresh(
        &mut self,
        terms: &InstrumentTerms,
        reservation: Option<Reservation>,
        settlement: &Settlement,
        time_exchange: DateTime<Utc>,
    ) -> RestingSettlement {
        match self.commit_afresh(
            terms,
            reservation,
            &settlement.settled(),
            Some(&settlement.credit),
            time_exchange,
        ) {
            Recommitted::Committed { commitment, .. } => RestingSettlement::Settled(commitment),
            Recommitted::Unaffordable { released } => RestingSettlement::Unaffordable { released },
        }
    }

    /// Releases an order's hold and commits `debit` and `credit` afresh in its place, restating
    /// each asset it moved once, or reports the account cannot cover them. See
    /// [`settle_resting_afresh`](Self::settle_resting_afresh) and [`Recommitted`].
    fn commit_afresh(
        &mut self,
        terms: &InstrumentTerms,
        reservation: Option<Reservation>,
        debit: &Debit,
        credit: Option<&Credit>,
        time_exchange: DateTime<Utc>,
    ) -> Recommitted {
        let effect = reservation.as_ref().map_or_else(
            || self.margin_effect(None),
            |reservation| reservation.effect,
        );
        let released = reservation.map(|reservation| {
            let balance =
                self.account
                    .release(&reservation.asset, reservation.amount, time_exchange);
            (reservation, balance)
        });

        let repays_at_cancel = self.repays_at_cancel();
        match self.commit(debit, credit, effect, terms, None, time_exchange) {
            Ok(mut commitment) => {
                let mut loan = commitment.committed.borrowed;
                if let Some((reservation, _)) = &released {
                    loan += reservation.borrowed;
                }
                // A fill that cost less than was held needs less of the loan; the account's own
                // funds pay first, so the unused loan is the smaller of the loan and the surplus.
                // It is repaid only if the venue repays what its orders no longer need.
                if let Some((reservation, _)) = released.filter(|_| repays_at_cancel) {
                    let surplus = reservation.amount - (debit.settled + debit.reserved);
                    let unused = reservation.borrowed.min(surplus);
                    if unused > Decimal::ZERO {
                        debug_assert_eq!(commitment.committed.paid.asset, reservation.asset);
                        commitment.committed.paid =
                            self.account
                                .repay_loan(&reservation.asset, unused, time_exchange);
                        loan -= unused;
                    }
                }
                Recommitted::Committed { commitment, loan }
            }
            Err(_) => Recommitted::Unaffordable {
                released: released.map(|(reservation, balance)| {
                    match !repays_at_cancel || reservation.borrowed.is_zero() {
                        true => balance,
                        false => self.account.repay_loan(
                            &reservation.asset,
                            reservation.borrowed,
                            time_exchange,
                        ),
                    }
                }),
            },
        }
    }

    /// Appends the balances one commitment restated, the asset paid with first, then the cash
    /// flow reporting the interest charged on its loan.
    fn push_committed(&self, events: &mut Vec<UnindexedAccountEvent>, commitment: Commitment) {
        let Commitment {
            committed: Committed { paid, received, .. },
            interest,
            fee,
        } = commitment;
        events.push(self.build_account_event(Snapshot(paid)));
        if let Some(received) = received {
            events.push(self.build_account_event(Snapshot(received)));
        }
        if let Some(fee) = fee {
            events.push(self.build_account_event(Snapshot(*fee)));
        }
        if let Some(interest) = interest {
            events.push(self.build_account_event(AccountEventKind::CashFlow(*interest)));
        }
    }

    /// Takes a fill's fee out of its asset's free balance when `settlement` says it is
    /// [taken apart](Settlement::fee_apart), adding that balance's restatement to `commitment`.
    fn take_fee_apart(
        &mut self,
        settlement: &Settlement,
        commitment: &mut Commitment,
        time_exchange: DateTime<Utc>,
    ) {
        // A fee discounted to nothing takes nothing, from a balance the account may never have
        // held.
        if !settlement.fee_apart || settlement.fees.fees.is_zero() {
            return;
        }
        // `fee_in_fee_asset` saw the free balance cover the fee before the fill moved anything,
        // and the fill exchanges neither its base nor its quote for the fee asset, nor lends it,
        // so the balance still covers it.
        commitment.fee = Some(Box::new(self.account.charge(
            &settlement.fees.asset,
            -settlement.fees.fees,
            time_exchange,
        )));
    }

    /// Commits one arrival's whole ledger effect through [`AccountState::commit`], lending what
    /// [`borrowable`](Self::borrowable) allows to an order whose `effect` borrows, then charges
    /// interest on whatever it lent.
    ///
    /// The interest is charged at `time_exchange` on the amount lent, so the restated
    /// [`Committed::paid`] includes it, and [`Commitment::interest`] reports it.
    ///
    /// # Errors
    /// As [`AccountState::commit`]: the ledger is left untouched and nothing is charged.
    fn commit(
        &mut self,
        debit: &Debit,
        credit: Option<&Credit>,
        effect: MarginEffect,
        terms: &InstrumentTerms,
        market: Option<&MarketSnapshot>,
        time_exchange: DateTime<Utc>,
    ) -> Result<Commitment, BalanceInsufficient> {
        let borrowable = self.borrowable(debit, effect, terms, market);
        let mut committed =
            self.account
                .commit(debit, credit, effect, borrowable, time_exchange)?;

        let interest = match committed.borrowed > Decimal::ZERO {
            true => self
                .charge_interest(
                    &debit.asset,
                    committed.borrowed,
                    InterestDue::Borrow(time_exchange),
                )
                .map(|(balance, flow)| {
                    committed.paid = balance;
                    Box::new(flow)
                }),
            false => None,
        };
        Ok(Commitment {
            committed,
            interest,
            fee: None,
        })
    }

    /// Cancels an order the venue held and will not fill, and reports it: a resting order whose
    /// fill the account can no longer afford, or a held market order its bar could not fill.
    ///
    /// The released hold restates first, so a consumer applying the events in order never sees the
    /// order retired against a balance that still holds its reservation.
    fn cancel_unfilled(
        &mut self,
        order: OpenOrder,
        released: Option<AssetBalance<AssetNameExchange>>,
        time_exchange: DateTime<Utc>,
    ) -> Vec<UnindexedAccountEvent> {
        let mut events = Vec::with_capacity(2);
        if let Some(balance) = released {
            events.push(self.build_account_event(Snapshot(balance)));
        }

        let id = order.state.id.or_client_id(&order.key.cid);
        let cancelled = Order {
            key: order.key,
            side: order.side,
            price: order.price,
            quantity: order.quantity,
            kind: order.kind,
            time_in_force: order.time_in_force,
            state: Cancelled {
                id,
                time_exchange,
                filled_quantity: Some(order.state.filled_quantity),
            },
        };
        self.account.ack_cancelled(cancelled.clone());
        events.push(self.build_account_event(Snapshot(UnindexedOrder::from(cancelled))));

        events
    }

    /// This venue's view of `instrument`, or `None` if nothing has fed it one.
    pub fn market(&self, instrument: &InstrumentNameExchange) -> Option<&VenueInstrumentMarket> {
        self.market.get(instrument)
    }

    /// Number of orders this venue has booked.
    ///
    /// Also how far the next `OrderId` is past the first one this venue minted, which is `0` unless
    /// the seeded account state carried a decimal id: then the first is one past the highest such
    /// id, so a minted id never repeats a seeded one.
    ///
    /// Counts every order it gave an id to, including those that retired without ever trading. It
    /// is **not** a count of trades — one order can print more than once, and trade ids are minted
    /// from a sequence of their own.
    pub fn order_sequence(&self) -> u64 {
        self.order_sequence
    }

    pub fn balances(&self, assets: &[AssetNameExchange]) -> Vec<AssetBalance<AssetNameExchange>> {
        // Empty slice means "return all" (consistent with account_snapshot behavior).
        self.account
            .balances()
            .filter(|balance| assets.is_empty() || assets.contains(&balance.asset))
            .cloned()
            .collect()
    }

    pub fn orders_open(
        &self,
        instruments: &[InstrumentNameExchange],
    ) -> Vec<Order<ExchangeId, InstrumentNameExchange, Open>> {
        // Empty slice means "return all" (consistent with account_snapshot behavior).
        self.account
            .orders_open()
            .filter(|order| instruments.is_empty() || instruments.contains(&order.key.instrument))
            .cloned()
            .collect()
    }

    /// How each of `orders` ended, for those that have: filled, cancelled (including the
    /// unfilled remainder of a market order) or expired at its own deadline.
    ///
    /// An order still open is omitted, and so is one this venue never held, including one it
    /// rejected on arrival, whose rejection was the answer to its open request. An empty `orders`
    /// returns nothing, not every ended order.
    ///
    /// Each order is found by its client order id, which this venue keys every order on, and is
    /// returned under the key it was asked for. A key naming a different instrument from the one
    /// the order traded is treated as unknown, and an id asked about more than once is reported
    /// once, under the first key that finds it.
    pub fn orders_ended(&self, orders: &[UnindexedOrderKey]) -> Vec<UnindexedInactiveOrder> {
        let mut reported = FnvHashSet::default();
        orders
            .iter()
            .filter_map(|key| {
                let order = self
                    .account
                    .order_ended(&key.cid)
                    .filter(|order| order.key.instrument == key.instrument)?;
                reported.insert(&key.cid).then(|| Order {
                    key: key.clone(),
                    ..order
                })
            })
            .collect()
    }

    pub fn trades(
        &self,
        time_since: DateTime<Utc>,
    ) -> Vec<Trade<AssetNameExchange, InstrumentNameExchange>> {
        self.account.trades(time_since).cloned().collect()
    }

    /// Books an open against the ledger and reports everything it owes the client.
    ///
    /// The venue books its own fill: the `Trade` is acknowledged into the ledger here, so a driver
    /// cannot forget to. A filled open reports `[balance, trade]` -- `[paid, received, trade]` for
    /// spot, which moves two assets -- mirroring a real venue where the trade is booked before the
    /// order can be reported `FullyFilled`; an open that rests reports `[balance]` alone -- the
    /// reservation now held against it -- and no trade, because nothing traded.
    ///
    /// A Market order has no limit price, and any price it carries is ignored, so the venue prices
    /// it from whichever market its [`VenueRegime`] gives it -- its own on a
    /// [`MarketDriven`](VenueRegime::MarketDriven) venue, and
    /// [`RequestOpen::market`](crate::order::request::RequestOpen::market) on a
    /// [`RequestPriced`](VenueRegime::RequestPriced) one. A Limit order is always judged and priced
    /// against this venue's own market; see the type's `# How an order is priced`.
    ///
    /// An order whose quantity is zero or negative is rejected, moving nothing, whatever the
    /// market: with an [`ApiError::OrderRejected`] naming the quantity, unless its kind or time in
    /// force is refused first.
    ///
    /// # Panics
    /// If a configured [`HoldingCostModel`] or [`MarginInterestModel`] breaks its contract: a
    /// boundary not after the instant it was asked from, or a negative interest.
    pub fn open_order(
        &mut self,
        request: OrderRequestOpen<ExchangeId, InstrumentNameExchange>,
    ) -> OpenOutcome {
        // Chosen here so one path holds one snapshot: threading both through would allow two copies
        // to disagree, with nothing to arbitrate.
        let market = self.pricing_market(&request);
        let (response, notifications) = self.open_order_inner(request, market);

        // Everything is already committed -- the trade acknowledged, the order recorded or booked,
        // the ledger moved. All that is left is to package it in the order a driver must deliver
        // it: the balance that pays for a fill before the fill that spent it.
        let events = match notifications {
            Some(OpenOrderNotifications::Filled { commitment, trade }) => {
                let mut events = Vec::with_capacity(3);
                self.push_committed(&mut events, commitment);
                events.push(self.build_account_event(trade));
                events
            }
            // Already on the book: `open_order_inner` put it there, holding the reservation this
            // balance restates.
            Some(OpenOrderNotifications::Rested { balance, interest }) => {
                let mut events = vec![self.build_account_event(balance)];
                if let Some(interest) = interest {
                    events.push(self.build_account_event(AccountEventKind::CashFlow(*interest)));
                }
                events
            }
            None => Vec::new(),
        };
        self.refresh_next_interest_if_loans_changed();

        VenueOutcome { events, response }
    }

    /// Takes a resting order off the book, releasing whatever is held against it.
    ///
    /// Returns `[balance]` and a [`Cancelled`] carrying the quantity filled before the cancel
    /// arrived -- which is whatever the order had done: nothing for one that rested untouched, the
    /// taker part for one the book could only partly fill on arrival, and whatever a configured
    /// `initial_state` seeded, carried through rather than added to. An order the venue holds
    /// nothing against releases nothing and reports no balance; see this type's note on
    /// `initial_state`.
    ///
    /// # A cancel that finds nothing says which nothing it found
    /// A cancel racing its own order's fill is the reason this distinguishes three cases rather
    /// than rejecting flatly. With a non-zero `to_venue` latency the fill can win, and
    /// [`ApiError::OrderAlreadyFullyFilled`] is what tells the caller to reconcile against the fill
    /// rather than retry. An order cancelled twice gets [`ApiError::OrderAlreadyCancelled`], and
    /// only an id this venue has never booked is rejected as unknown.
    ///
    /// # Panics
    /// If the configured [`MarginInterestModel`] breaks its contract with a boundary not after the
    /// instant it was asked from, when the venue next looks for one after a loan is repaid.
    pub fn cancel_order(
        &mut self,
        request: OrderRequestCancel<ExchangeId, InstrumentNameExchange>,
    ) -> CancelOutcome {
        let time_exchange = self.time_exchange();

        let Some(RestingOrder { order, reservation }) = self.account.remove_order(&request.key.cid)
        else {
            return VenueOutcome {
                events: Vec::new(),
                response: UnindexedOrderResponseCancel {
                    state: Err(self.cancel_missing_reason(&request.key.cid)),
                    key: request.key,
                },
            };
        };

        // Released before the response is built, so a request arriving after this one sees the
        // freed balance regardless of when a driver delivers the restatement.
        let events = match reservation {
            Some(reservation) => {
                let balance = self.release_reservation(&reservation, time_exchange);
                vec![self.build_account_event(Snapshot(balance))]
            }
            None => Vec::new(),
        };
        self.refresh_next_interest_if_loans_changed();

        let cancelled = Cancelled {
            id: order.state.id.or_client_id(&order.key.cid),
            time_exchange,
            filled_quantity: Some(order.state.filled_quantity),
        };

        self.account.ack_cancelled(Order {
            key: order.key,
            side: order.side,
            price: order.price,
            quantity: order.quantity,
            kind: order.kind,
            time_in_force: order.time_in_force,
            state: cancelled.clone(),
        });

        VenueOutcome {
            events,
            response: UnindexedOrderResponseCancel {
                key: request.key,
                state: Ok(cancelled),
            },
        }
    }

    /// Why a cancel found no resting order under `cid`.
    fn cancel_missing_reason(&self, cid: &ClientOrderId) -> UnindexedOrderError {
        if self.account.is_filled(cid) {
            ApiError::OrderAlreadyFullyFilled.into()
        } else if self.account.is_cancelled(cid) {
            ApiError::OrderAlreadyCancelled.into()
        } else if self.account.is_expired(cid) {
            ApiError::OrderAlreadyExpired.into()
        } else {
            UnindexedOrderError::Rejected(ApiError::OrderRejected(format!(
                "SimulatedVenue is not holding an open order with {cid}"
            )))
        }
    }

    pub fn account_snapshot(&self) -> UnindexedAccountSnapshot {
        let balances = self.account.balances().cloned().collect();

        let orders_open = self
            .account
            .orders_open()
            .cloned()
            .map(UnindexedOrder::from);

        let orders_cancelled = self
            .account
            .orders_cancelled()
            .cloned()
            .map(UnindexedOrder::from);

        let orders_expired = self
            .account
            .orders_expired()
            .cloned()
            .map(UnindexedOrder::from);

        let orders_all = orders_open.chain(orders_cancelled).chain(orders_expired);
        // Sorted on `(instrument, cid)` rather than `instrument` alone: the sort is unstable, so a
        // key shared by several orders leaves their relative order unspecified, and a snapshot that
        // lists the same account's orders in a different order on each run is not comparable
        // between runs. `cid` is unique per order, so the extended key is total.
        let orders_all = orders_all
            .sorted_unstable_by_key(|order| (order.key.instrument.clone(), order.key.cid.clone()));
        let orders_by_instrument = orders_all.chunk_by(|order| order.key.instrument.clone());

        let mut orders_by_instrument: FnvHashMap<_, Vec<_>> = orders_by_instrument
            .into_iter()
            .map(|(instrument, orders)| (instrument, orders.collect()))
            .collect();

        // Every instrument with an order, and every cash-settled instrument whether or not it has
        // one: a CFD's position is reported even while it is flat, which is what lets a consumer
        // tell "holds none" from "not reported".
        let mut instruments: Vec<_> = self
            .instruments
            .iter()
            .filter_map(|(name, instrument)| {
                let orders = orders_by_instrument.remove(name);
                let position = self.position_report(name, instrument);
                if orders.is_none() && position == PositionReport::Unreported {
                    return None;
                }
                Some(InstrumentAccountSnapshot {
                    instrument: name.clone(),
                    orders: orders.unwrap_or_default(),
                    // Read from the venue's own book, so every open order is here under the id it
                    // was placed with. Cancelled and expired orders are listed too, which only adds
                    // to what a consumer can see.
                    orders_complete: true,
                    position,
                    isolated: None,
                })
            })
            .collect();

        // Orders a configured `initial_state` seeded on an instrument this venue does not trade,
        // which it still holds and so still reports.
        instruments.extend(
            orders_by_instrument
                .into_iter()
                .map(|(instrument, orders)| InstrumentAccountSnapshot {
                    instrument,
                    orders,
                    orders_complete: true,
                    position: PositionReport::Unreported,
                    isolated: None,
                }),
        );
        instruments.sort_unstable_by(|a, b| a.instrument.cmp(&b.instrument));

        UnindexedAccountSnapshot {
            exchange: self.exchange,
            balances,
            instruments,
        }
    }

    /// The position this venue reports for `instrument`.
    ///
    /// A cash-settled instrument reports its net position, [`Flat`](PositionReport::Flat) when it
    /// holds none. A spot holding is an asset balance on this venue rather than a position, so a
    /// spot instrument reports [`Unreported`](PositionReport::Unreported).
    fn position_report(
        &self,
        name: &InstrumentNameExchange,
        instrument: &Instrument<ExchangeId, AssetNameExchange>,
    ) -> PositionReport {
        if !matches!(instrument.kind, InstrumentKind::Cfd(_)) {
            return PositionReport::Unreported;
        }

        let position = self.positions.get(name).copied().unwrap_or_default();
        PositionReport::from_position(Position::new(
            position.quantity,
            (!position.quantity.is_zero()).then_some(position.entry),
            None,
            None,
            None,
            None,
            None,
            self.time_exchange(),
        ))
    }

    /// Decides one open's fate, moves the balance it pays with, and commits nothing else.
    ///
    /// Kept separate from [`open_order`](Self::open_order) rather than inlined: this body has
    /// several early returns, and the ordering contract -- emit the balance before the trade it
    /// paid for -- is the part a reader needs to find. Splitting keeps that contract in a short
    /// caller instead of at the end of a long one.
    ///
    /// Everything an arrival commits is committed *here*, by whichever function decides the
    /// order's fate: [`fill_on_arrival`](Self::fill_on_arrival) acknowledges its own trade and
    /// records what the order became, exactly as [`cancel_on_arrival`](Self::cancel_on_arrival),
    /// [`expire_on_arrival`](Self::expire_on_arrival) and [`rest_order`](Self::rest_order) already
    /// do. The caller is left owning event order and nothing else.
    ///
    /// `market` is the snapshot the request carried, and is used only by an order that is priced
    /// from it -- see the type's `# How an order is priced`.
    /// The market an arriving order is priced against, which is the venue's own wherever it has
    /// one.
    ///
    /// # Why the regime decides, and why there is no fallback
    /// A [`MarketDriven`](VenueRegime::MarketDriven) venue owns a book, and a fill is priced from
    /// the book the order reaches -- that is what a venue *is*. Its driver routes each market event
    /// to it before the client that will react sees it, and books the request at the instant it
    /// arrives, so this snapshot is the market as of that arrival: neither stale, nor from a future
    /// the sender could not have seen.
    ///
    /// [`RequestPriced`](VenueRegime::RequestPriced) has no book at all, so the snapshot the
    /// request carried is its only price source. That is the whole of the difference, and it is why
    /// a request-priced `MockExchange`'s results do not move.
    ///
    /// A `MarketDriven` venue that has not been fed this instrument answers `None` rather than
    /// falling back to the request's snapshot. A venue with no market for an instrument cannot fill
    /// a market order in it, and saying so is the observable failure; silently pricing from the
    /// requester's view would make the fill depend on which of the two happened to hold a price,
    /// and would re-admit exactly the request-priced behaviour the regime exists to distinguish.
    /// [`fill_on_arrival`](Self::fill_on_arrival) reports it as an unpriceable order, naming the
    /// absent snapshot.
    fn pricing_market(
        &self,
        request: &OrderRequestOpen<ExchangeId, InstrumentNameExchange>,
    ) -> Option<MarketSnapshot> {
        match self.regime {
            VenueRegime::RequestPriced => request.state.market,
            // `VenueInstrumentMarket` is `Copy`, so this leaves no borrow outstanding.
            VenueRegime::MarketDriven => self
                .market(&request.key.instrument)
                .map(|market| market.snapshot),
        }
    }

    fn open_order_inner(
        &mut self,
        request: OrderRequestOpen<ExchangeId, InstrumentNameExchange>,
        market: Option<MarketSnapshot>,
    ) -> (
        Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState>,
        Option<OpenOrderNotifications>,
    ) {
        if let Err(error) = self.validate_order_kind_supported(request.state.kind) {
            return (build_open_order_err_response(request, error), None);
        }

        if let Err(error) =
            validate_time_in_force_supported(request.state.kind, request.state.time_in_force)
        {
            return (build_open_order_err_response(request, error), None);
        }

        // An order for nothing, or for less than nothing, is refused as a venue refuses it. Every
        // path below takes the quantity as positive: a held order, for one, is released only to
        // trade or rest some of it.
        if request.state.quantity <= Decimal::ZERO {
            let reason = format!(
                "cannot open {} for {}: quantity {} is not positive",
                request.key.instrument, request.key.exchange, request.state.quantity
            );
            return (
                build_open_order_err_response(
                    request,
                    UnindexedOrderError::Rejected(ApiError::OrderRejected(reason)),
                ),
                None,
            );
        }

        // Read out before the `&mut self` balance borrows below.
        let terms = match self.instrument_terms(&request.key.instrument) {
            Ok(terms) => terms,
            Err(error) => return (build_open_order_err_response(request, error), None),
        };

        // Before anything touches the ledger: an effect this venue cannot honour is refused rather
        // than placed without it, which would borrow, or not repay, against the caller's intent.
        if let Some(effect) = self.refused_margin_effect(request.state.margin_effect, &terms) {
            return (
                build_open_order_err_response(
                    request,
                    UnindexedOrderError::UnsupportedMarginEffect(effect),
                ),
                None,
            );
        }

        // Before anything touches the ledger, and for every kind: see the type's note on client
        // order ids. It is also what makes a refused booking in `book_rested` unreachable.
        if self.account.orders().contains(&request.key.cid) {
            let reason = format!(
                "{} already names an order resting on {}",
                request.key.cid, request.key.exchange
            );
            return (
                build_open_order_err_response(request, ApiError::DuplicateClientOrderId(reason)),
                None,
            );
        }

        // Before anything touches the ledger: a refused short leaves no trace on it.
        if let Err(error) = self.check_shortability(&request, &terms, market.as_ref()) {
            return (build_open_order_err_response(request, error), None);
        }

        let now = self.time_exchange();

        // Only a limit order's price is a limit, and a limit order without one has nothing to rest
        // at or bound a fill by. Refused before the stale-market gate below, so that the gate
        // never holds an order this venue would refuse anyway.
        let limit = match request.state.kind {
            OrderKind::Limit => match request.state.price {
                Some(limit) => Some(limit),
                None => {
                    let reason = format!(
                        "cannot open {} for {}: OrderKind::Limit carries no limit price",
                        request.key.instrument, request.key.exchange
                    );
                    return (
                        build_open_order_err_response(
                            request,
                            UnindexedOrderError::Rejected(ApiError::OrderRejected(reason)),
                        ),
                        None,
                    );
                }
            },
            _ => None,
        };

        // Under `StaleMarketPolicy::Wait`, an order arriving on a stale market is handled as if it
        // arrived just after the instrument's next fresh observation: held until then, or refused
        // if its time in force will not wait. An order already past its own deadline is not asked,
        // since it expires below whatever the market is doing.
        if let StaleMarketPolicy::Wait { max_age } = self.stale_market
            && !matches!(
                request.state.time_in_force,
                TimeInForce::GoodTillDate { expiry } if now >= expiry
            )
        {
            match self.market_age(&request.key.instrument, max_age, now) {
                MarketAge::NoFeed => {
                    let reason = format!(
                        "cannot accept {} on {}: StaleMarketPolicy::Wait needs a market feed to \
                         measure {}'s age from, and this venue has none",
                        request.key.cid, request.key.exchange, request.key.instrument
                    );
                    return (
                        build_open_order_err_response(
                            request,
                            UnindexedOrderError::Rejected(ApiError::OrderRejected(reason)),
                        ),
                        None,
                    );
                }
                MarketAge::Stale { fresh_at } => {
                    if matches!(
                        request.state.time_in_force,
                        TimeInForce::ImmediateOrCancel | TimeInForce::FillOrKill
                    ) {
                        let last = fresh_at.map_or_else(
                            || "never observed fresh".to_owned(),
                            |fresh_at| format!("last observed fresh at {fresh_at}"),
                        );
                        let reason = format!(
                            "cannot fill {} on {}: {}'s market is stale under \
                             StaleMarketPolicy::Wait (max_age {max_age:?}; {last}), and \
                             TimeInForce::{} does not wait for a fresh observation",
                            request.key.cid,
                            request.key.exchange,
                            request.key.instrument,
                            request.state.time_in_force
                        );
                        return (
                            build_open_order_err_response(
                                request,
                                UnindexedOrderError::Rejected(ApiError::OrderRejected(reason)),
                            ),
                            None,
                        );
                    }
                    return self.hold_on_arrival(request, market, &terms);
                }
                MarketAge::Fresh | MarketAge::Unpriced => {}
            }
        }

        // `None` for every kind but a limit order, each of which is marketable on arrival by
        // definition.
        let Some(limit) = limit else {
            // Only the two aggressing arms an order with no limit price can reach, and `Expire`,
            // are reachable: `Rest` and `FillAndRest` need somewhere to rest, which such an order
            // has not got, and `CancelUnfilled` needs `post_only`, which the static gate already
            // refused on a market order. The remaining arms retire the order unfilled rather than
            // asserting, because filling an order this function could not account for is the one
            // wrong answer.
            //
            // The two aggressing arms differ in what becomes of a remainder the book could not
            // fill: `ImmediateOrCancel` keeps what it got and retires the rest, `FillOrKill`
            // would rather trade nothing -- see `Remainder`.
            //
            // Under `MarketOrderTiming::NextBar`, both aggressing arms wait for the bar instead,
            // and their time in force is applied when it fills them.
            return match disposition(request.state.kind, request.state.time_in_force, true, now) {
                Disposition::FillAndCancel | Disposition::FillOrNothing
                    if matches!(self.market_order_timing, MarketOrderTiming::NextBar(_)) =>
                {
                    self.hold_on_arrival(request, market, &terms)
                }
                Disposition::FillAndCancel => {
                    self.fill_on_arrival(request, market, &terms, Remainder::Cancel)
                }
                Disposition::FillOrNothing => {
                    self.fill_on_arrival(request, market, &terms, Remainder::Kill)
                }
                Disposition::Expire => self.expire_on_arrival(request, now),
                Disposition::FillAndRest | Disposition::CancelUnfilled | Disposition::Rest => {
                    self.cancel_on_arrival(request, now)
                }
            };
        };

        // The same snapshot the order will be priced from, so marketability and price cannot be
        // decided against two different views of the book. `validate_order_kind_supported` has
        // already refused a limit order on a `RequestPriced` venue, so on this path
        // `pricing_market` is this venue's own market by construction.
        let marketable = market.is_some_and(|market| crosses(request.state.side, limit, &market));

        match disposition(
            request.state.kind,
            request.state.time_in_force,
            marketable,
            now,
        ) {
            // The three differ only in what becomes of a remainder the book could not fill, which
            // is exactly what they are asked here -- see `Remainder`.
            Disposition::FillAndRest => {
                self.fill_on_arrival(request, market, &terms, Remainder::Rest { limit })
            }
            Disposition::FillAndCancel => {
                self.fill_on_arrival(request, market, &terms, Remainder::Cancel)
            }
            Disposition::FillOrNothing => {
                self.fill_on_arrival(request, market, &terms, Remainder::Kill)
            }
            // Nothing has traded, so the whole quantity is what rests.
            Disposition::Rest => self.rest_order(request, limit, &terms, Decimal::ZERO),
            Disposition::CancelUnfilled => self.cancel_on_arrival(request, now),
            Disposition::Expire => self.expire_on_arrival(request, now),
        }
    }

    /// How old `instrument`'s market is at `now`, measured against `max_age` — see
    /// [`StaleMarketPolicy::Wait`].
    fn market_age(
        &self,
        instrument: &InstrumentNameExchange,
        max_age: Duration,
        now: DateTime<Utc>,
    ) -> MarketAge {
        if self.regime == VenueRegime::RequestPriced {
            return MarketAge::NoFeed;
        }
        let Some(market) = self
            .market(instrument)
            .filter(|market| !market.snapshot.is_empty())
        else {
            return MarketAge::Unpriced;
        };
        let Some(fresh_at) = market.fresh_at else {
            return MarketAge::Stale { fresh_at: None };
        };
        // A `max_age` too long for a `TimeDelta` is longer than any run, so nothing is stale.
        let stale = chrono::TimeDelta::from_std(max_age)
            .is_ok_and(|max_age| now.signed_duration_since(fresh_at) > max_age);
        if stale {
            MarketAge::Stale {
                fresh_at: Some(fresh_at),
            }
        } else {
            MarketAge::Fresh
        }
    }

    /// Accepts an order to fill later, holding what it would cost at the venue's current market:
    /// a market order on its instrument's next bar under [`MarketOrderTiming::NextBar`], and any
    /// order arriving on a stale market on its next fresh observation under
    /// [`StaleMarketPolicy::Wait`] (or, combined with `NextBar`, its next fresh bar).
    ///
    /// What it would cost is what it would cost arriving now: a market order, or a limit order the
    /// market crosses, as a taker at the price the [`FillModel`] gives, capped at a limit order's
    /// limit; a limit order the market does not cross, or a post-only one, at its limit as the
    /// maker it would rest as.
    ///
    /// Refused instead, with nothing moved, when the order waits for a bar and the instrument has
    /// never been fed one (there is no next bar this venue can know to wait for), when the current
    /// market prices nothing for a market order, and when the account cannot cover the hold. The
    /// last two are what an arriving order would be refused for too, so a strategy is refused the
    /// same orders whether or not they wait.
    fn hold_on_arrival(
        &mut self,
        request: OrderRequestOpen<ExchangeId, InstrumentNameExchange>,
        market: Option<MarketSnapshot>,
        terms: &InstrumentTerms,
    ) -> (
        Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState>,
        Option<OpenOrderNotifications>,
    ) {
        if matches!(self.market_order_timing, MarketOrderTiming::NextBar(_))
            && self
                .market(&request.key.instrument)
                .and_then(|market| market.bar)
                .is_none()
        {
            let reason = format!(
                "cannot hold {} on {} for {}'s next bar: MarketOrderTiming::NextBar holds it for \
                 one and needs a bar feed, and this venue has been fed no bar for it",
                request.key.cid, request.key.exchange, request.key.instrument
            );
            return (
                build_open_order_err_response(
                    request,
                    UnindexedOrderError::Rejected(ApiError::OrderRejected(reason)),
                ),
                None,
            );
        }

        let side = request.state.side;
        let limit = match request.state.kind {
            OrderKind::Limit => request.state.price,
            _ => None,
        };
        let post_only = matches!(
            request.state.time_in_force,
            TimeInForce::GoodUntilCancelled { post_only: true }
        );

        // The price the order would fill at now, unslipped: the hold is an estimate, released and
        // costed afresh when the order is released, so it takes no draw from the slippage stream.
        let taker_estimate = || {
            market.and_then(|market| {
                self.fill_model
                    .fill_price(&FillContext::new(side, request.state.quantity, &market))
            })
        };
        let (estimate, liquidity) = match limit {
            Some(limit)
                if !post_only && market.is_some_and(|market| crosses(side, limit, &market)) =>
            {
                // A crossed market prices it, but a model that needs more of a book than the
                // market has falls back to the limit, as on arrival.
                let estimate = taker_estimate().unwrap_or(limit);
                (
                    Some(clamp_to_limit(side, estimate, limit)),
                    Liquidity::Taker,
                )
            }
            Some(limit) => (Some(limit), Liquidity::Maker),
            None => (taker_estimate(), Liquidity::Taker),
        };
        let Some(estimate) = estimate else {
            let reason = format!(
                "cannot price {} for {}: no market price available yet and OrderKind::{:?} carries \
                 no limit price",
                request.key.instrument, request.key.exchange, request.state.kind
            );
            return (
                build_open_order_err_response(
                    request,
                    UnindexedOrderError::Rejected(ApiError::OrderRejected(reason)),
                ),
                None,
            );
        };

        let time_exchange = self.time_exchange();
        let settlement = self.settlement(
            terms,
            self.net_position(terms, &request.key.instrument),
            side,
            request.state.quantity,
            estimate,
            liquidity,
        );

        let debit = settlement.reserved();
        let effect = self.margin_effect(request.state.margin_effect);
        let (balance, borrowed, interest) =
            match self.commit(&debit, None, effect, terms, market.as_ref(), time_exchange) {
                Ok(Commitment {
                    committed: Committed { paid, borrowed, .. },
                    interest,
                    ..
                }) => (paid, borrowed, interest),
                Err(insufficient) => {
                    return (
                        build_open_order_err_response(request, insufficient_error(insufficient)),
                        None,
                    );
                }
            };

        let open = Open::new(
            VenueOrderId::Assigned(self.order_id_sequence_fetch_add()),
            time_exchange,
            Decimal::ZERO,
        );
        // A market order is held with no price whatever the request carried, since a price on one
        // is ignored, and a limit order with its limit, which it rests at once released.
        let order = Order {
            key: request.key,
            side,
            price: limit,
            quantity: request.state.quantity,
            kind: request.state.kind,
            time_in_force: request.state.time_in_force,
            state: open,
        };

        let reservation = Reservation {
            amount: settlement.requirement(),
            asset: settlement.asset,
            borrowed,
            effect,
        };
        if let Err(AlreadyResting(refused)) = self.account.hold(order.clone(), Some(reservation)) {
            unreachable!(
                "SimulatedVenue held {} over a resting order: open_order_inner checks first",
                refused.order.key.cid
            );
        }

        (
            order.map_state(OrderState::active),
            Some(OpenOrderNotifications::Rested {
                balance: Snapshot(balance),
                interest,
            }),
        )
    }

    /// Refuses an order that would open or increase a CFD short which the configured
    /// [`ShortabilityProvider`] does not allow; see the type's
    /// `# Locates and the short-sale restriction`.
    ///
    /// The short an order opens is measured as if every resting sell on the instrument filled
    /// first, so that a short this venue has already accepted on the book counts against what is
    /// left to lend, and an order whose short part is nothing — a buy, or a sell that only reduces
    /// a long — passes untouched. `market` is the snapshot the order will be priced from, so
    /// whether it is marketable is judged against the book it would fill on.
    fn check_shortability(
        &self,
        request: &OrderRequestOpen<ExchangeId, InstrumentNameExchange>,
        terms: &InstrumentTerms,
        market: Option<&MarketSnapshot>,
    ) -> Result<(), UnindexedApiError> {
        let Some(provider) = &self.shortability else {
            return Ok(());
        };
        if !terms.cash_settled || request.state.side != Side::Sell {
            return Ok(());
        }

        let instrument = &request.key.instrument;
        let resting_sells: Decimal = self
            .account
            .orders_open()
            .filter(|order| order.key.instrument == *instrument && order.side == Side::Sell)
            .map(|order| order.state.quantity_remaining(order.quantity))
            .sum();
        // The position left if every resting sell fills, before and after this order does too.
        let committed = self.net_position(terms, instrument).quantity - resting_sells;
        let short_before = (-committed).max(Decimal::ZERO);
        let short_after = (request.state.quantity - committed).max(Decimal::ZERO);
        if short_after <= short_before {
            return Ok(());
        }

        let now = self.time_exchange();
        let exchange = request.key.exchange;
        let shortability = provider.shortability(instrument, now);

        if let Some(delisting_at) = shortability.delisting_at
            && delisting_at <= now
        {
            return Err(ApiError::BorrowRejected(BorrowReject::new(
                BorrowRejectReason::NotShortable,
                None,
                format!(
                    "{instrument} cannot be sold short on {exchange} at {now}: it is delisted at \
                     {delisting_at}"
                ),
            )));
        }
        if shortability.shortable == Some(false) {
            return Err(ApiError::BorrowRejected(BorrowReject::new(
                BorrowRejectReason::NotShortable,
                None,
                format!("{instrument} cannot be sold short on {exchange} at {now}"),
            )));
        }

        if let Some(available) = shortability.available
            && short_after > available
        {
            let message = format!(
                "selling {} {instrument} on {exchange} would take its short, resting sells \
                 included, to {short_after}, past the {available} there is to borrow at {now}",
                request.state.quantity
            );
            let left = (available - short_before).max(Decimal::ZERO);
            return Err(ApiError::BorrowRejected(
                BorrowReject::new(BorrowRejectReason::InventoryUnavailable, None, message)
                    .with_available(left),
            ));
        }

        // A limit is judged against what a sell trades against, the bid, else the last price, as
        // `crosses` judges it. Every other kind this venue accepts takes whatever the book offers,
        // at the price the fill model gives it. When there is nothing to judge against, an order
        // that would take from the book is refused as unpriceable instead, which names the real
        // cause.
        let marketable = || {
            market.is_some_and(|market| match request.state.kind {
                OrderKind::Limit => request
                    .state
                    .price
                    .is_some_and(|limit| crosses(Side::Sell, limit, market)),
                _ => self
                    .fill_model
                    .fill_price(&FillContext::new(
                        Side::Sell,
                        request.state.quantity,
                        market,
                    ))
                    .is_some(),
            })
        };
        if provider.short_sale_restricted(instrument, now) && marketable() {
            return Err(ApiError::BorrowRejected(BorrowReject::new(
                BorrowRejectReason::ShortSaleRestricted,
                None,
                format!(
                    "{instrument} is under a short-sale restriction on {exchange} at {now}: a \
                     short sale must be priced above the best bid"
                ),
            )));
        }

        Ok(())
    }

    /// Retires an order that asked to work only on arrival and could not, having traded nothing.
    ///
    /// Reached by a non-marketable [`TimeInForce::ImmediateOrCancel`] or
    /// [`TimeInForce::FillOrKill`], and by a `post_only` order that would have taken liquidity.
    /// Nothing was reserved and nothing traded, so this owes no balance restatement -- only the
    /// terminal response.
    fn cancel_on_arrival(
        &mut self,
        request: OrderRequestOpen<ExchangeId, InstrumentNameExchange>,
        now: DateTime<Utc>,
    ) -> (
        Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState>,
        Option<OpenOrderNotifications>,
    ) {
        let cancelled = Cancelled {
            id: self.order_id_sequence_fetch_add(),
            time_exchange: now,
            filled_quantity: Some(Decimal::ZERO),
        };

        self.account.ack_cancelled(Order {
            key: request.key.clone(),
            side: request.state.side,
            price: request.state.price,
            quantity: request.state.quantity,
            kind: request.state.kind,
            time_in_force: request.state.time_in_force,
            state: cancelled.clone(),
        });

        (
            Order {
                key: request.key,
                side: request.state.side,
                price: request.state.price,
                quantity: request.state.quantity,
                kind: request.state.kind,
                time_in_force: request.state.time_in_force,
                state: OrderState::inactive(cancelled),
            },
            None,
        )
    }

    /// Retires an order whose [`TimeInForce::GoodTillDate`] deadline had already passed when it
    /// arrived.
    ///
    /// Such an order is never rested, and never traded -- not even when the book would have filled
    /// it, since an order past its deadline has stopped working and whether it *could* have traded
    /// is not a question this venue asks. With no independent clock, deadlines are swept only when
    /// a driver advances it or feeds it a market, so an order accepted past its own deadline would
    /// work until something else happened to touch the venue -- and if nothing did, for the rest of
    /// the run. Retiring it here makes the deadline mean what it says.
    ///
    /// Reported as expired rather than rejected because nothing was wrong with the request: its
    /// price, size and funding were never examined, and calling it a rejection would tell a
    /// consumer's statistics the venue refused an order it merely found too late.
    fn expire_on_arrival(
        &mut self,
        request: OrderRequestOpen<ExchangeId, InstrumentNameExchange>,
        now: DateTime<Utc>,
    ) -> (
        Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState>,
        Option<OpenOrderNotifications>,
    ) {
        let expired = Expired {
            id: self.order_id_sequence_fetch_add(),
            time_exchange: now,
            filled_quantity: Some(Decimal::ZERO),
        };

        self.account.ack_expired(Order {
            key: request.key.clone(),
            side: request.state.side,
            price: request.state.price,
            quantity: request.state.quantity,
            kind: request.state.kind,
            time_in_force: request.state.time_in_force,
            state: expired.clone(),
        });

        (
            Order {
                key: request.key,
                side: request.state.side,
                price: request.state.price,
                quantity: request.state.quantity,
                kind: request.state.kind,
                time_in_force: request.state.time_in_force,
                state: OrderState::expired(expired),
            },
            None,
        )
    }

    /// Trades an order against the book the moment it arrives, for as much of it as the book has.
    ///
    /// # What the book has is what it fills
    /// The fill is capped at the size on offer to this side
    /// ([`VenueInstrumentMarket::depth`]), and that size is drawn down by what this fill takes, so
    /// a second order arriving before the next [`apply_market`](Self::apply_market) sees only what
    /// the first left. A feed supplying no size caps nothing — see [`MarketDepth`].
    ///
    /// `remainder` decides what becomes of the quantity the book could not fill, and it is the
    /// order's own time in force that chose it — see [`Remainder`] and [`Disposition`].
    ///
    /// # An order is funded whole or refused whole
    /// An order that fills in part and rests the rest owes the ledger two things at one instant: a
    /// settlement for what traded and a hold against what did not. They are asked for as one
    /// requirement ([`AccountState::commit`]), so an account that cannot cover both has the order
    /// refused with nothing moved — rather than filled for the part it could afford, which would
    /// be this venue choosing a disposition the sender did not ask for.
    ///
    /// That makes a capped order *dearer* than the same order filling outright, because the
    /// remainder is held at the order's own limit while the fill struck a better price. An order
    /// can therefore be refused for a size the book was willing to sell it.
    ///
    /// [`VenueInstrumentMarket::depth`]: VenueInstrumentMarket::depth
    /// [`AccountState::commit`]: crate::exchange::mock::account::AccountState::commit
    fn fill_on_arrival(
        &mut self,
        request: OrderRequestOpen<ExchangeId, InstrumentNameExchange>,
        market: Option<MarketSnapshot>,
        terms: &InstrumentTerms,
        remainder: Remainder,
    ) -> (
        Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState>,
        Option<OpenOrderNotifications>,
    ) {
        let market_supplied = market.is_some();
        let market = market.unwrap_or_default();

        // Only a limit order's price is a limit. Any other kind's is ignored, as the live clients
        // ignore a price sent with a market order: it neither prices the fill nor bounds it.
        let limit = match request.state.kind {
            OrderKind::Limit => request.state.price,
            _ => None,
        };

        // The order's own price is deliberately NOT handed to the model. A limit constrains the
        // result, not the pricing: a model reads the book and returns where a taker prints, and
        // this venue is what bounds that by the order's terms. See `FillModel`'s contract.
        let maybe_reference = self
            .fill_model
            .fill_price(&FillContext::new(
                request.state.side,
                request.state.quantity,
                &market,
            ))
            // For a market order this is `.or(None)`, whatever price it carries. For a marketable
            // limit it is the last resort that makes the rejection below unreachable: an order
            // whose limit the market crossed necessarily has one.
            .or(limit);

        // No price anywhere. Ordinary user data -- a cold start, a thin instrument, a subscription
        // that was never made, or a caller that supplied no snapshot at all -- not a violated
        // internal invariant, so it is rejected rather than panicked on.
        //
        // A panic here is also strictly less informative. The async driver runs as a spawned task:
        // killing it drops the request receiver, every later order comes back as
        // `ConnectivityError::ExchangeOffline`, and the run completes over the whole dataset
        // having filled nothing, reporting only a `JoinError` at teardown.
        //
        // The two causes get different messages because they have different fixes: an absent
        // snapshot is a wiring problem in the caller, an empty one is a timing problem in the data.
        let Some(reference) = maybe_reference else {
            let cause = if market_supplied {
                "no market price available yet"
            } else {
                "the request carried no market snapshot (RequestOpen::market was None)"
            };
            let reason = format!(
                "cannot price {} for {}: {cause} and OrderKind::{:?} carries no limit price",
                request.key.instrument, request.key.exchange, request.state.kind
            );
            return (
                build_open_order_err_response(
                    request,
                    UnindexedOrderError::Rejected(ApiError::OrderRejected(reason)),
                ),
                None,
            );
        };

        let time_exchange = self.time_exchange();
        let side = request.state.side;

        // What the book has to give this order, which is all of it wherever no size is known.
        let filled_quantity = match self.depth_available(&request.key.instrument, side) {
            Some(available) => request.state.quantity.min(available),
            None => request.state.quantity,
        };
        let unfilled = request.state.quantity - filled_quantity;

        // Nothing trades: either the book has no size left to give, or the order would rather
        // trade nothing than trade in part. `FillOrKill` is the second case and the only one --
        // this is where it stops coinciding with `ImmediateOrCancel`, which takes what it can get.
        // The whole order then meets the fate its remainder would have.
        if filled_quantity <= Decimal::ZERO || (unfilled > Decimal::ZERO && remainder.is_kill()) {
            return match remainder {
                // Nothing has traded, so the whole quantity is what rests.
                Remainder::Rest { limit } => self.rest_order(request, limit, terms, Decimal::ZERO),
                Remainder::Cancel | Remainder::Kill => {
                    self.cancel_on_arrival(request, time_exchange)
                }
            };
        }

        // Slipped only now that the order is known to trade, so the stream advances exactly once
        // per fill, and an order that is cancelled or rests whole takes no draw. One the ledger
        // refuses below hands its draw back, which needs the stream as it was.
        let slippage_before = self.slippage.clone();
        let fill_price = self.slippage.apply(side, reference);

        // The clamp, and the only place a limit price bounds a fill. A taker crossing the spread
        // can be filled better than its limit but never worse, so a buy never prints above it and
        // a sell never below. Applied here rather than inside the model because it is a property of
        // the order's terms, not of how the market is read, and after the slippage so that no
        // rate, however large, fills an order past its limit.
        let fill_price = match limit {
            Some(limit) => clamp_to_limit(side, fill_price, limit),
            None => fill_price,
        };

        // Marketable on arrival, so this fill takes liquidity and is charged the taker rate.
        let position = self.net_position(terms, &request.key.instrument);
        let fill = self.fill_settlement(
            terms,
            position,
            side,
            filled_quantity,
            fill_price,
            Liquidity::Taker,
        );

        // What holding the remainder will cost, priced exactly as the fill that settles it will be
        // -- the unfilled quantity, at the order's own limit, as the maker, against the position
        // this fill leaves. Computed before anything moves, so both legs are asked of the ledger as
        // one requirement.
        let held = match remainder {
            Remainder::Rest { limit } if unfilled > Decimal::ZERO => Some(self.settlement(
                terms,
                position.after(side, filled_quantity, fill_price),
                side,
                unfilled,
                limit,
                Liquidity::Maker,
            )),
            _ => None,
        };

        // One commitment for the whole arrival. A configured `total != free` (an `initial_state`
        // copied from a live account with margin reserved) is carried through untouched rather
        // than rejected: the ledger represents a held amount, so there is nothing left to refuse.
        let debit = match &held {
            Some(held) => fill.settled_holding(held),
            None => fill.settled(),
        };

        let effect = self.margin_effect(request.state.margin_effect);
        let mut commitment = match self.commit(
            &debit,
            Some(&fill.credit),
            effect,
            terms,
            Some(&market),
            time_exchange,
        ) {
            Ok(commitment) => commitment,
            Err(insufficient) => {
                // Refused, so it never traded: the next fill draws the rate it would have drawn had
                // this order never been sent.
                self.slippage = slippage_before;
                return (
                    build_open_order_err_response(request, insufficient_error(insufficient)),
                    None,
                );
            }
        };

        self.take_fee_apart(&fill, &mut commitment, time_exchange);

        // Taken off the book only now that it is paid for, so a refused order consumes nothing.
        self.consume_depth(&request.key.instrument, side, filled_quantity);
        self.record_fill(
            terms,
            &request.key.instrument,
            side,
            Fill {
                quantity: filled_quantity,
                price: fill_price,
            },
        );

        let order_id = self.order_id_sequence_fetch_add();
        let trade = Trade {
            id: self.trade_id_sequence_fetch_add(),
            order_id: order_id.clone(),
            instrument: request.key.instrument.clone(),
            strategy: request.key.strategy.clone(),
            time_exchange,
            side,
            price: fill_price,
            quantity: filled_quantity,
            // An arriving order that aggresses has no prior executions, so this fill is its
            // whole cumulative.
            order_filled_quantity: Some(filled_quantity),
            fees: fill.fees,
            origin: TradeOrigin::Order,
            position_side: None,
            client_order_id: Some(request.key.cid.clone()),
        };

        // Booked here rather than by the caller, so that whatever this order became is decided in
        // one place: every other arrival already acknowledges its own outcome.
        self.account.ack_trade(trade.clone());

        let state = self.retire_filled(
            &request,
            order_id,
            Fill {
                quantity: filled_quantity,
                price: fill_price,
            },
            held,
            commitment.committed.borrowed,
            time_exchange,
        );

        (
            Order {
                key: request.key,
                side,
                price: request.state.price,
                quantity: request.state.quantity,
                kind: request.state.kind,
                time_in_force: request.state.time_in_force,
                state,
            },
            Some(OpenOrderNotifications::Filled { commitment, trade }),
        )
    }

    /// Records what an order that traded on arrival became, and reports the state it answers with.
    ///
    /// The three outcomes are the three things a taker fill can leave behind: nothing, a remainder
    /// with nowhere to wait, or a remainder on the book. `borrowed` is what a margin account lent
    /// the arrival, part of which a remainder on the book holds.
    fn retire_filled(
        &mut self,
        request: &OrderRequestOpen<ExchangeId, InstrumentNameExchange>,
        order_id: OrderId,
        fill: Fill,
        held: Option<Settlement>,
        borrowed: Decimal,
        time_exchange: DateTime<Utc>,
    ) -> UnindexedOrderState {
        // Spelled out per arm rather than shared: a closure would be monomorphic in the state
        // type, and the two arms that record an order record two different ones.
        match held {
            // The book could not fill all of it and the remainder waits at the order's own limit,
            // carrying what has already traded so `Open::quantity_remaining` stays true for the
            // rest of its life -- which is what `match_resting` settles and prints.
            Some(held) => {
                let open = Open::new(
                    VenueOrderId::Assigned(order_id),
                    time_exchange,
                    fill.quantity,
                );
                self.book_rested(
                    Order {
                        key: request.key.clone(),
                        side: request.state.side,
                        price: request.state.price,
                        quantity: request.state.quantity,
                        kind: request.state.kind,
                        time_in_force: request.state.time_in_force,
                        state: open.clone(),
                    },
                    Reservation {
                        // The fill spent the account's own balance first, so whatever was lent is
                        // held against the remainder.
                        borrowed: borrowed.min(held.requirement()),
                        amount: held.requirement(),
                        asset: held.asset,
                        effect: self.margin_effect(request.state.margin_effect),
                    },
                );

                OrderState::active(open)
            }

            // Either it filled outright, or what is left has nowhere to wait.
            None if fill.quantity == request.state.quantity => {
                // One fill is the whole of this order, so its price is also the mean of every
                // fill behind the total -- which is exactly when `avg_price` may be reported.
                let filled = Filled::new(
                    order_id,
                    time_exchange,
                    request.state.quantity,
                    Some(fill.price),
                );
                self.account.ack_filled(Order {
                    key: request.key.clone(),
                    side: request.state.side,
                    price: request.state.price,
                    quantity: request.state.quantity,
                    kind: request.state.kind,
                    time_in_force: request.state.time_in_force,
                    state: filled.clone(),
                });

                OrderState::fully_filled(filled)
            }

            // A market order has no limit price, so its remainder has nothing to rest at and
            // retires carrying what did trade -- which is what `Cancelled::filled_quantity` is for,
            // and the first time this venue makes it non-zero.
            None => {
                let cancelled = Cancelled {
                    id: order_id,
                    time_exchange,
                    filled_quantity: Some(fill.quantity),
                };
                self.account.ack_cancelled(Order {
                    key: request.key.clone(),
                    side: request.state.side,
                    price: request.state.price,
                    quantity: request.state.quantity,
                    kind: request.state.kind,
                    time_in_force: request.state.time_in_force,
                    state: cancelled.clone(),
                });

                OrderState::inactive(cancelled)
            }
        }
    }

    /// What is left to take at the best price on the far side of `side`, where a feed says.
    fn depth_available(&self, instrument: &InstrumentNameExchange, side: Side) -> Option<Decimal> {
        self.market
            .get(instrument)
            .and_then(|market| market.depth.available_to(side))
    }

    /// Draws down what an aggressor on `side` can still take, by what this one just took.
    fn consume_depth(
        &mut self,
        instrument: &InstrumentNameExchange,
        side: Side,
        quantity: Decimal,
    ) {
        if let Some(market) = self.market.get_mut(instrument) {
            market.depth.consume(side, quantity);
        }
    }

    /// Puts `order` on the book holding `reservation`.
    ///
    /// # Panics
    /// If an order is already resting under its id. `open_order_inner` refuses such an open before
    /// anything else, under the same `&mut self`, so the book is vacant under this id by
    /// construction, and a refusal here would be a bug in this venue with no correct reply left
    /// to give.
    fn book_rested(&mut self, order: OpenOrder, reservation: Reservation) {
        if let Err(AlreadyResting(refused)) = self.account.book(order, Some(reservation)) {
            unreachable!(
                "SimulatedVenue booked {} over a resting order: open_order_inner checks first",
                refused.order.key.cid
            );
        }
    }

    /// Puts what is left of an order onto the book, holding what that remainder's fill will cost.
    ///
    /// `filled_quantity` is how much of `request` has already traded, and everything here is
    /// computed from what is **left** of it: the reservation covers the unfilled remainder alone,
    /// and the [`Open`] state carries the filled part so that [`Open::quantity_remaining`] stays
    /// true for the rest of the order's life -- which is what
    /// [`match_resting`](Self::match_resting) settles and prints when the book reaches it.
    /// Reserving for the whole quantity would hold balance against a portion that has already
    /// settled, and the fill that eventually released it would settle less than was held.
    ///
    /// The reservation is what the fill will settle, computed once here and settled unchanged --
    /// never a conservative over-estimate. A conservative reservation would have to be released and
    /// re-debited on the fill, and [`AccountState::commit`]'s contract is that an arrival restates
    /// each asset it moves exactly **once**; the extra restatements would report balances the
    /// account never held, and [`Balance::used`](crate::balance::Balance::used) would misreport
    /// for the order's whole life.
    ///
    /// [`AccountState::commit`]: crate::exchange::mock::account::AccountState::commit
    fn rest_order(
        &mut self,
        request: OrderRequestOpen<ExchangeId, InstrumentNameExchange>,
        limit: Decimal,
        terms: &InstrumentTerms,
        filled_quantity: Decimal,
    ) -> (
        Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState>,
        Option<OpenOrderNotifications>,
    ) {
        let time_exchange = self.time_exchange();

        // Priced and charged exactly as the fill will be: the unfilled remainder, at the order's
        // own limit, as the maker, against the position as it stands now.
        let settlement = self.settlement(
            terms,
            self.net_position(terms, &request.key.instrument),
            request.state.side,
            request.state.quantity - filled_quantity,
            limit,
            Liquidity::Maker,
        );

        let debit = settlement.reserved();
        let market = self
            .market(&request.key.instrument)
            .map(|market| market.snapshot);
        let effect = self.margin_effect(request.state.margin_effect);
        let (balance_snapshot, borrowed, interest) =
            match self.commit(&debit, None, effect, terms, market.as_ref(), time_exchange) {
                // Nothing traded, so nothing is delivered: the one balance is the hold.
                Ok(Commitment {
                    committed: Committed { paid, borrowed, .. },
                    interest,
                    ..
                }) => (paid, borrowed, interest),
                Err(insufficient) => {
                    return (
                        build_open_order_err_response(request, insufficient_error(insufficient)),
                        None,
                    );
                }
            };

        // The order rests carrying whatever it has already done, so the book, the client and this
        // venue's own later arithmetic all read the same remainder off it.
        let open = Open::new(
            VenueOrderId::Assigned(self.order_id_sequence_fetch_add()),
            time_exchange,
            filled_quantity,
        );

        self.book_rested(
            Order {
                key: request.key.clone(),
                side: request.state.side,
                price: request.state.price,
                quantity: request.state.quantity,
                kind: request.state.kind,
                time_in_force: request.state.time_in_force,
                state: open.clone(),
            },
            Reservation {
                amount: settlement.requirement(),
                asset: settlement.asset,
                borrowed,
                effect,
            },
        );

        let order_response = Order {
            key: request.key,
            side: request.state.side,
            price: request.state.price,
            quantity: request.state.quantity,
            kind: request.state.kind,
            time_in_force: request.state.time_in_force,
            state: OrderState::active(open),
        };

        (
            order_response,
            Some(OpenOrderNotifications::Rested {
                balance: Snapshot(balance_snapshot),
                interest,
            }),
        )
    }

    /// The instrument facts one order's settlement is computed from, read out once.
    fn instrument_terms(
        &self,
        instrument: &InstrumentNameExchange,
    ) -> Result<InstrumentTerms, UnindexedApiError> {
        let instrument = self.find_instrument_data(instrument)?;
        let cash_settled = Self::settlement_of_supported_kind(instrument)?;

        Ok(InstrumentTerms {
            underlying: instrument.underlying.clone(),
            contract_size: instrument.kind.contract_size(),
            cash_settled,
        })
    }

    /// The net position an order on `instrument` trades against. Flat for a cash-settled
    /// instrument this account holds no position in, and for every spot instrument, which skips
    /// the lookup: a spot settlement never reads it.
    fn net_position(
        &self,
        terms: &InstrumentTerms,
        instrument: &InstrumentNameExchange,
    ) -> NetPosition {
        if !terms.cash_settled {
            return NetPosition::default();
        }
        self.positions.get(instrument).copied().unwrap_or_default()
    }

    /// Moves `instrument`'s net position by a fill, if it is cash-settled. A spot fill moves the
    /// ledger's balances and nothing here.
    fn record_fill(
        &mut self,
        terms: &InstrumentTerms,
        instrument: &InstrumentNameExchange,
        side: Side,
        fill: Fill,
    ) {
        if !terms.cash_settled {
            return;
        }

        // One lookup for a position already held, and the name cloned only to open one.
        let opened_or_closed = match self.positions.get_mut(instrument) {
            Some(position) => {
                *position = position.after(side, fill.quantity, fill.price);
                let closed = position.quantity.is_zero();
                if closed {
                    self.positions.remove(instrument);
                }
                closed
            }
            None => {
                let position = NetPosition::default().after(side, fill.quantity, fill.price);
                let opened = !position.quantity.is_zero();
                if opened {
                    self.positions.insert(instrument.clone(), position);
                }
                opened
            }
        };

        // A position opened or closed has boundaries of its own, or no longer has any. One that
        // only changed size keeps its boundaries, which depend on the instrument alone.
        if opened_or_closed && !self.holding_costs.is_empty() {
            self.refresh_next_charge();
        }
    }

    /// What one order pays with at `price`, how much of it including the fee, and what it pays
    /// back.
    ///
    /// The single place this venue decides an order's cost. A reservation and the fill that settles
    /// it both come from here, with the same `price` and `liquidity`, which is what makes "reserve
    /// exactly what will be settled" true by construction rather than by two formulas agreeing.
    /// For a cash-settled instrument the cost also depends on `position`, the net position the
    /// order trades against, which can change between an order resting and filling; see
    /// [`settle_resting`](Self::settle_resting).
    ///
    /// Both the notional and the fee carry the instrument's `contract_size` multiplier, which is
    /// `Decimal::ONE` for `Spot` and a real per-point multiplier for a `Cfd`. Dropping it here while
    /// the engine applies it to PnL and fees (`InstrumentState::update_from_trade`) would make this
    /// ledger and the engine's position accounting disagree by exactly that factor -- balances
    /// moving 1x while PnL moves 25x, silently, with every balance-derived return, drawdown and
    /// Sharpe wrong by the same factor. Which models actually consult the multiplier is theirs to
    /// decide -- `PercentageFeeModel` scales by it, `PerContractFeeModel` deliberately does not --
    /// and passing it is what keeps that decision in the models rather than making this a second
    /// place the multiplier can be lost.
    fn settlement(
        &self,
        terms: &InstrumentTerms,
        position: NetPosition,
        side: Side,
        quantity: Decimal,
        price: Decimal,
        liquidity: Liquidity,
    ) -> Settlement {
        let fees_quote =
            self.fee_model
                .compute_fee(price, quantity.abs(), terms.contract_size, liquidity);
        self.settlement_with_fee(terms, position, side, quantity, price, fees_quote)
    }

    /// The settlement of a fill, as [`settlement`](Self::settlement) gives it, unless its fee is
    /// charged in the [`FeeAssetConfig`] asset: then the fill exchanges its two assets free of fee,
    /// and its fee, in that asset, is [taken apart](Settlement::fee_apart) when it settles.
    ///
    /// Only a fill uses this. What an order holds while it works is its
    /// [`settlement`](Self::settlement), which is what its fill costs when the fee falls back, and
    /// never less than when it does not.
    fn fill_settlement(
        &self,
        terms: &InstrumentTerms,
        position: NetPosition,
        side: Side,
        quantity: Decimal,
        price: Decimal,
        liquidity: Liquidity,
    ) -> Settlement {
        let settlement = self.settlement(terms, position, side, quantity, price, liquidity);
        match self.fee_in_fee_asset(terms, &settlement.fees) {
            Some(fees) => Settlement {
                fees,
                fee_apart: true,
                ..self.settlement_with_fee(terms, position, side, quantity, price, Decimal::ZERO)
            },
            None => settlement,
        }
    }

    /// `fees`, a fill's fee in quote, as the [`FeeAssetConfig`] asset charges it: discounted, and
    /// converted at this venue's price for that asset in the fill's quote. `None` when the fill
    /// falls back to the [`SpotFeeAsset`] rule, as `FeeAssetConfig`'s `# When it falls back`
    /// lists, including when the asset's free balance is short of the fee.
    fn fee_in_fee_asset(
        &self,
        terms: &InstrumentTerms,
        fees: &AssetFees<AssetNameExchange>,
    ) -> Option<AssetFees<AssetNameExchange>> {
        let config = self.fee_asset.as_ref()?;
        let asset = config.asset();
        let underlying = &terms.underlying;
        let fees_quote = fees.fees_quote?;
        if terms.cash_settled
            || *asset == underlying.base
            || *asset == underlying.quote
            || fees_quote <= Decimal::ZERO
        {
            return None;
        }

        let price = self.price_in(asset, &underlying.quote, None)?;
        let fees_quote = fees_quote * (Decimal::ONE - config.discount());
        let fee = fees_quote.checked_div(price)?;
        (self.account.free(asset) >= fee)
            .then(|| AssetFees::new(asset.clone(), fee, Some(fees_quote)))
    }

    /// [`settlement`](Self::settlement), with its fee already computed: `fees_quote`, in quote.
    fn settlement_with_fee(
        &self,
        terms: &InstrumentTerms,
        position: NetPosition,
        side: Side,
        quantity: Decimal,
        price: Decimal,
        fees_quote: Decimal,
    ) -> Settlement {
        let quantity = quantity.abs();
        let fees = AssetFees::new(terms.underlying.quote.clone(), fees_quote, Some(fees_quote));

        if terms.cash_settled {
            // A CFD is a cash-settled position on a price, not an exchange of the two underlying
            // assets: there is nothing to deliver in either direction, so both directions post
            // and receive quote. A CFD short is a margin position rather than a stock loan, so --
            // unlike a spot sell -- it requires no base inventory, which would otherwise force the
            // caller to fund a phantom balance in an index or a commodity to open one.
            //
            // The fill first closes whatever of `position` it opposes, and opens a position with
            // the rest. This venue models no leverage, so opening posts the full notional as
            // margin -- the conservative reading, and the requirement a spot buy already carries.
            // Closing pays that margin back together with the realised PnL, which for a closed
            // quantity `c` against an average entry `e` is `c * cs * (price - e)` for a long and
            // `c * cs * (e - price)` for a short. The fee is charged on the whole quantity.
            let closing = position.closing(side, quantity);
            let opening = quantity - closing;
            let open_margin = price * opening * terms.contract_size;
            let close_proceeds = closing
                * terms.contract_size
                * match position.is_long() {
                    true => price,
                    false => position.entry + position.entry - price,
                };

            // A short closed at more than twice its entry has lost more than its margin. There is
            // no liquidation here to have stopped it, so the shortfall is paid like any other
            // debit rather than credited as a negative amount.
            let (credit, shortfall) = match close_proceeds.is_sign_negative() {
                true => (Decimal::ZERO, -close_proceeds),
                false => (close_proceeds, Decimal::ZERO),
            };

            return Settlement {
                asset: terms.underlying.quote.clone(),
                amount: open_margin + fees_quote + shortfall,
                credit: Credit::PaidBack(credit),
                fees,
                fee_apart: false,
            };
        }

        // A spot fill exchanges the two assets. Its fee comes out of what a sell receives, in quote,
        // and under `SpotFeeAsset::Quote` on top of what a buy pays, so the base it moves is exactly
        // its quantity. Under `Received` a buy's fee comes out of the base it receives instead,
        // converted at the fill price. That base fee is what the engine nets from its position, so
        // the two still agree. The fee each fill reports is the one charged, in the asset charged.
        let notional = price * quantity * terms.contract_size;
        match side {
            Side::Buy
                if self.spot_fee_asset == SpotFeeAsset::Received
                    && price > Decimal::ZERO
                    && !fees_quote.is_zero() =>
            {
                let fee_base = fees_quote / price;
                Settlement {
                    asset: terms.underlying.quote.clone(),
                    amount: notional,
                    credit: Credit::Delivery(Delivery {
                        asset: terms.underlying.base.clone(),
                        amount: quantity - fee_base,
                    }),
                    fees: AssetFees::new(terms.underlying.base.clone(), fee_base, Some(fees_quote)),
                    fee_apart: false,
                }
            }
            Side::Buy => Settlement {
                asset: terms.underlying.quote.clone(),
                amount: notional + fees_quote,
                credit: Credit::Delivery(Delivery {
                    asset: terms.underlying.base.clone(),
                    amount: quantity,
                }),
                fees,
                fee_apart: false,
            },
            Side::Sell => Settlement {
                asset: terms.underlying.base.clone(),
                amount: quantity,
                credit: Credit::Delivery(Delivery {
                    asset: terms.underlying.quote.clone(),
                    amount: notional - fees_quote,
                }),
                fees,
                fee_apart: false,
            },
        }
    }

    /// Whether this venue accepts `order_kind`, which depends on its [`VenueRegime`].
    ///
    /// [`OrderKind::Market`] is always accepted. [`OrderKind::Limit`] needs somewhere to rest and
    /// something to be matched against, so it is accepted only by a
    /// [`MarketDriven`](VenueRegime::MarketDriven) venue. Every other kind is rejected outright.
    ///
    /// # Errors
    /// Returns [`ApiError::OrderRejected`] naming the kind, and -- for a limit order refused by the
    /// regime -- why the venue cannot hold one.
    pub fn validate_order_kind_supported(
        &self,
        order_kind: OrderKind,
    ) -> Result<(), UnindexedOrderError> {
        let reason = match (order_kind, self.regime) {
            (OrderKind::Market, _) | (OrderKind::Limit, VenueRegime::MarketDriven) => return Ok(()),
            (OrderKind::Limit, VenueRegime::RequestPriced) => format!(
                "SimulatedVenue does not support OrderKind::{order_kind:?} in \
                 VenueRegime::RequestPriced: it has no market feed, so an order that rested could \
                 never be matched. Construct it with SimulatedVenue::new_market_driven, and feed \
                 it with apply_market"
            ),
            _ => format!("SimulatedVenue does not support OrderKind::{order_kind:?}"),
        };

        Err(UnindexedOrderError::Rejected(ApiError::OrderRejected(
            reason,
        )))
    }

    /// Returns whether `instrument` is cash-settled, rejecting kinds this venue cannot model.
    ///
    /// # Why this is enforced here and not only upstream
    /// This type and its [`instruments`](Self::instruments) map are both public, so a consumer can
    /// construct one directly and never pass through the `rustrade` builder that screens kinds
    /// today. Without this gate a [`InstrumentKind::Perpetual`], [`InstrumentKind::Future`] or
    /// [`InstrumentKind::Option`] falls to the physically-settled spot path and is filled as if it
    /// were deliverable stock — with its `contract_size` multiplier applied to a delivery that
    /// cannot happen, and with no funding, margin or expiry settlement anywhere. That is a wrong
    /// backtest, not a missing feature, and it is silent.
    ///
    /// # Errors
    /// Returns [`ApiError::InstrumentInvalid`] for any kind other than [`InstrumentKind::Spot`] or
    /// [`InstrumentKind::Cfd`].
    fn settlement_of_supported_kind(
        instrument: &Instrument<ExchangeId, AssetNameExchange>,
    ) -> Result<bool, UnindexedApiError> {
        match &instrument.kind {
            InstrumentKind::Spot => Ok(false),
            InstrumentKind::Cfd(_) => Ok(true),
            unsupported => Err(ApiError::InstrumentInvalid(
                instrument.name_exchange.clone(),
                format!(
                    "SimulatedVenue does not support {}; only Spot and Cfd are modelled",
                    match unsupported {
                        InstrumentKind::Perpetual(_) => "InstrumentKind::Perpetual",
                        InstrumentKind::Future(_) => "InstrumentKind::Future",
                        InstrumentKind::Option(_) => "InstrumentKind::Option",
                        // Unreachable: both are matched above. Spelled out rather than `_` so a new
                        // kind is a compile error here instead of a mislabelled rejection.
                        InstrumentKind::Spot | InstrumentKind::Cfd(_) => "InstrumentKind",
                    }
                ),
            )),
        }
    }

    pub fn find_instrument_data(
        &self,
        instrument: &InstrumentNameExchange,
    ) -> Result<&Instrument<ExchangeId, AssetNameExchange>, UnindexedApiError> {
        self.instruments.get(instrument).ok_or_else(|| {
            ApiError::InstrumentInvalid(
                instrument.clone(),
                format!("SimulatedVenue is not set-up for managing: {instrument}"),
            )
        })
    }

    fn order_id_sequence_fetch_add(&mut self) -> OrderId {
        let sequence = self.order_sequence;
        self.order_sequence += 1;
        OrderId((self.order_id_start + u128::from(sequence)).to_smolstr())
    }

    /// Mints the next `TradeId`, which no other trade from this venue instance carries.
    ///
    /// Not derived from the order's id: one order can print twice — filling in part on arrival and
    /// again when its remainder is crossed — and two trades under one id would be indistinguishable
    /// to anything reconciling them. See [`TradeId`] for what a consumer may assume of one.
    fn trade_id_sequence_fetch_add(&mut self) -> TradeId {
        let sequence = self.trade_sequence;
        self.trade_sequence += 1;
        TradeId(sequence.to_smolstr())
    }

    fn build_account_event<Kind>(&self, kind: Kind) -> UnindexedAccountEvent
    where
        Kind: Into<AccountEventKind<ExchangeId, AssetNameExchange, InstrumentNameExchange>>,
    {
        UnindexedAccountEvent {
            exchange: self.exchange,
            kind: kind.into(),
        }
    }
}

/// `model`'s first boundary for `instrument` after `after`, checked against its contract.
///
/// # Panics
/// If the boundary is not after `after`. Charging it would charge one instant forever, and a
/// driver waking the venue for it would wake it there forever, so it is refused at the first
/// read, wherever that is.
fn next_boundary(
    model: &dyn HoldingCostModel,
    instrument: &InstrumentNameExchange,
    after: DateTime<Utc>,
) -> Option<DateTime<Utc>> {
    let boundary = model.next_boundary(instrument, after)?;
    assert!(
        boundary > after,
        "HoldingCostModel {model:?} returned boundary {boundary} for {instrument}, which is not \
         after {after}"
    );
    Some(boundary)
}

/// `model`'s first interest boundary for `asset` after `after`, checked against its contract.
///
/// # Panics
/// If the boundary is not after `after` — see [`MarginInterestModel`]'s contract.
fn next_interest_boundary(
    model: &dyn MarginInterestModel,
    asset: &AssetNameExchange,
    after: DateTime<Utc>,
) -> Option<DateTime<Utc>> {
    let boundary = model.next_boundary(asset, after)?;
    assert!(
        boundary > after,
        "MarginInterestModel {model:?} returned boundary {boundary} for {asset}, which is not \
         after {after}"
    );
    Some(boundary)
}

/// Every boundary in `(after, through]`, each found from the one before by `next`.
fn boundaries_through(
    after: DateTime<Utc>,
    through: DateTime<Utc>,
    mut next: impl FnMut(DateTime<Utc>) -> Option<DateTime<Utc>>,
) -> impl Iterator<Item = DateTime<Utc>> {
    std::iter::successors(next(after), move |&boundary| next(boundary))
        .take_while(move |&boundary| boundary <= through)
}

/// One charge that falls due at a boundary, ordered so a run's charges at one instant arrive in
/// the same order every time: holding costs first, then interest.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum Due {
    /// The holding cost of the position in an instrument, by the index of its model.
    Holding(InstrumentNameExchange, usize),
    /// The interest on the principal owed in an asset, with that principal: charging interest
    /// does not change it, so it holds for every boundary of one accrual.
    Interest(AssetNameExchange, Decimal),
}

/// The net positions an `initial_state` opens a venue with: one for each cash-settled instrument
/// the snapshot reports an open position in.
///
/// Its balances are taken as they are, so the margin such a position was opened with is treated as
/// already posted, and closing it pays that margin back. A position on a spot instrument is not
/// seeded: a spot holding is a balance, not a position, on this venue.
///
/// # Panics
/// Panics if a cash-settled position reports no entry price. Closing it credits margin and
/// realised PnL computed from the entry, so an absent one is a mis-specified fixture, in the same
/// class as an absent balance.
fn seeded_positions(
    initial_state: &UnindexedAccountSnapshot,
    instruments: &FnvHashMap<InstrumentNameExchange, Instrument<ExchangeId, AssetNameExchange>>,
) -> FnvHashMap<InstrumentNameExchange, NetPosition> {
    initial_state
        .instruments
        .iter()
        .filter(|snapshot| {
            instruments
                .get(&snapshot.instrument)
                .is_some_and(|instrument| matches!(instrument.kind, InstrumentKind::Cfd(_)))
        })
        .filter_map(|snapshot| {
            let position = snapshot.position.open()?;
            let Some(entry) = position.entry_price else {
                panic!(
                    "SimulatedVenue's initial_state reports an open position in {} with no entry \
                     price, so the margin and PnL its close would credit cannot be computed",
                    snapshot.instrument
                );
            };
            Some((
                snapshot.instrument.clone(),
                NetPosition {
                    quantity: position.quantity,
                    entry,
                },
            ))
        })
        .collect()
}

/// The rejection for an order the account cannot pay for, naming what it has, what it needs, and,
/// on a margin account, what the venue would have lent.
fn insufficient_error(insufficient: BalanceInsufficient) -> UnindexedApiError {
    let BalanceInsufficient {
        asset,
        free,
        required,
        borrowable,
    } = insufficient;
    let message = match borrowable {
        None => format!("Available Balance: {free}, Required Balance inc. fees: {required}"),
        Some(borrowable) => format!(
            "Available Balance: {free}, Required Balance inc. fees: {required}, Borrowable: \
             {borrowable}"
        ),
    };
    ApiError::BalanceInsufficient(Some(asset), message)
}

/// The mid of `snapshot`'s best bid and ask, else its last price.
fn mid_or_last(snapshot: &MarketSnapshot) -> Option<Decimal> {
    match (snapshot.best_bid, snapshot.best_ask) {
        (Some(bid), Some(ask)) => Some((bid + ask) / Decimal::TWO),
        _ => snapshot.last_price,
    }
}

/// Whether the market has moved to or through `limit` for an order resting on `side`.
///
/// Judged on the far side of the book -- an offer for a buy, a bid for a sell -- because that is
/// what an order on this side trades against. A feed supplying no book at all falls back to
/// `last_price`, which is what makes a trades-only feed able to match anything; a feed that does
/// supply a book is never second-guessed by it, since a price *between* the two sides crosses
/// neither.
fn crosses(side: Side, limit: Decimal, market: &MarketSnapshot) -> bool {
    match side {
        Side::Buy => match market.best_ask {
            Some(best_ask) => best_ask <= limit,
            None => market.last_price.is_some_and(|last| last <= limit),
        },
        Side::Sell => match market.best_bid {
            Some(best_bid) => best_bid >= limit,
            None => market.last_price.is_some_and(|last| last >= limit),
        },
    }
}

/// `price` bounded by `limit` for an order on `side`: a buy never above it, a sell never below.
fn clamp_to_limit(side: Side, price: Decimal, limit: Decimal) -> Decimal {
    match side {
        Side::Buy => price.min(limit),
        Side::Sell => price.max(limit),
    }
}

/// Whether this venue can honour `time_in_force` for an order of `order_kind` **at all**.
///
/// This is the static half of the time-in-force decision: it asks only whether the pair could ever
/// be honoured, never what the order should then do. What a supported time in force *does* depends
/// on whether the order is marketable when it arrives, which is not known here -- see
/// [`Disposition`].
///
/// # Most of a time in force is moot for an order that works only on arrival
/// A [`OrderKind::Market`] order trades the instant it arrives and never afterwards, which
/// satisfies every time in force that governs *how long* an order works: there is no later instant
/// at which it could still be working, and a remainder the book could not fill has no limit price
/// to wait at, so it is cancelled rather than kept.
///
/// [`TimeInForce::AtOpen`] and [`TimeInForce::AtClose`] are not of that kind. They govern *when* an
/// order executes, not how long it lasts, and honouring them needs a session calendar this venue
/// has not got. Accepting one would fill it immediately, at a price that is not the auction it
/// asked for -- a wrong fill rather than an ignored flag. This library takes them seriously
/// elsewhere: its IBKR client turns them into real market-on-close and limit-on-close orders, which
/// is correct only because a real venue has the calendar. So they are refused here for the same
/// reason on both order kinds.
///
/// [`TimeInForce::GoodUntilCancelled`] with `post_only` is likewise refused on a market order, as
/// a promise never to take liquidity is one a market order cannot keep.
///
/// # Errors
/// Returns [`ApiError::OrderRejected`] naming what it would take to honour the pair. Rejecting is
/// the point: treating an unsupported time in force as `GoodUntilCancelled` would silently leave an
/// order working that its sender asked to have cancelled, and treating an unsupported one as
/// "fill now" answers a question the sender did not ask.
fn validate_time_in_force_supported(
    order_kind: OrderKind,
    time_in_force: TimeInForce,
) -> Result<(), UnindexedOrderError> {
    const NO_CALENDAR: &str = "a session calendar, which this venue does not have";

    let missing = match (order_kind, time_in_force) {
        // Governs *when* an order executes, not how long it works, whatever the kind.
        (_, TimeInForce::AtOpen | TimeInForce::AtClose) => NO_CALENDAR,

        // A market order takes liquidity by definition, so it cannot promise not to.
        (OrderKind::Market, TimeInForce::GoodUntilCancelled { post_only: true }) => {
            "an order that both takes liquidity and refuses to"
        }

        // Every other time in force bounds how long an order works, which is moot for one that
        // fills in full on arrival.
        (OrderKind::Market, _) => return Ok(()),

        (OrderKind::Limit, TimeInForce::GoodUntilEndOfDay) => NO_CALENDAR,

        // Honoured -- what each one then does is `Disposition`'s decision, not this one.
        (
            OrderKind::Limit,
            TimeInForce::GoodUntilCancelled { .. }
            | TimeInForce::ImmediateOrCancel
            | TimeInForce::FillOrKill
            | TimeInForce::GoodTillDate { .. },
        ) => return Ok(()),

        // Every other kind is rejected before this gate is reached.
        (_, _) => return Ok(()),
    };

    Err(UnindexedOrderError::Rejected(ApiError::OrderRejected(
        format!(
            "SimulatedVenue does not support TimeInForce::{time_in_force} on \
             OrderKind::{order_kind:?}: it does not model {missing}"
        ),
    )))
}

/// What a supported time in force makes one arriving order do.
///
/// The marketability-dependent half of the time-in-force decision, split from
/// [`validate_time_in_force_supported`] because three of the four time in forces this venue
/// honours on a limit order need context that gate cannot see: `post_only`, `ImmediateOrCancel`
/// and `FillOrKill` all turn on whether the order is marketable when it arrives, and
/// `GoodTillDate` turns on the clock.
///
/// # Three ways to aggress, which differ only over a remainder
/// What an aggressing order's time in force really decides is the fate of the quantity the book
/// could not fill: it rests, or it retires, or -- for [`TimeInForce::FillOrKill`] -- nothing trades
/// at all. Which of them an order asked for is a property of the order rather than of what the
/// book happened to hold, so all three are decided here and the answer is handed to
/// [`fill_on_arrival`](SimulatedVenue::fill_on_arrival) as a [`Remainder`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Disposition {
    /// Trade against the book now as the aggressor, resting whatever does not fill.
    FillAndRest,
    /// Trade against the book now as the aggressor, retiring whatever does not fill.
    FillAndCancel,
    /// Trade against the book now as the aggressor, but only if it fills in full: an order that
    /// could fill only in part trades nothing at all.
    FillOrNothing,
    /// Join the book and wait to be crossed.
    Rest,
    /// Retire immediately having traded nothing, because the order asked to work only now and
    /// could not: a non-marketable `ImmediateOrCancel` or `FillOrKill`, or a `post_only` order
    /// that would have taken liquidity.
    CancelUnfilled,
    /// Retire immediately having traded nothing, because the order's own deadline has passed.
    Expire,
}

/// Decide what one order does, given whether it is marketable and what time it is.
///
/// `marketable` is [`crosses`] for a limit order, and `true` for every other kind this venue
/// accepts -- each of those is marketable on arrival by definition, which is what lets one function
/// answer for both.
///
/// `order_kind` decides one thing only: whether an unfilled remainder has anywhere to go. An order
/// carrying no limit price has nothing to wait at, so a market order aggresses and retires whatever
/// is left of it, whichever time in force it carries.
///
/// # Immediate-or-cancel and fill-or-kill differ only when the book is too thin
/// Both aggress on arrival and neither waits, so while the book can fill an order whole they are
/// the same instruction. They part exactly where a fill is capped by the size on offer:
/// [`Disposition::FillAndCancel`] takes what there is and retires the rest, while
/// [`Disposition::FillOrNothing`] would rather trade nothing than trade in part, and so trades
/// nothing. Which one an order gets is decided here; what they then do with the remainder is
/// [`Remainder`]'s.
fn disposition(
    order_kind: OrderKind,
    time_in_force: TimeInForce,
    marketable: bool,
    now: DateTime<Utc>,
) -> Disposition {
    match time_in_force {
        // Post-only means "never take liquidity", so being marketable is what disqualifies it.
        TimeInForce::GoodUntilCancelled { post_only: true } if marketable => {
            Disposition::CancelUnfilled
        }

        // A deadline already reached retires the order whatever the book is doing. Checked before
        // marketability so that a deadline is an unconditional cutoff rather than one an order can
        // trade its way past at the very instant it expires.
        TimeInForce::GoodTillDate { expiry } if now >= expiry => Disposition::Expire,

        // The one time in force that would rather trade nothing than trade in part, whatever the
        // order kind.
        TimeInForce::FillOrKill if marketable => Disposition::FillOrNothing,

        // Every other aggressing order keeps what it could not fill only if it has somewhere to
        // keep it: a limit price to wait at, and a time in force that asked to wait. `post_only`
        // is not among them here -- a marketable one was disqualified above.
        _ if marketable => match (order_kind, time_in_force) {
            (
                OrderKind::Limit,
                TimeInForce::GoodUntilCancelled { .. } | TimeInForce::GoodTillDate { .. },
            ) => Disposition::FillAndRest,
            _ => Disposition::FillAndCancel,
        },

        TimeInForce::ImmediateOrCancel | TimeInForce::FillOrKill => Disposition::CancelUnfilled,

        _ => Disposition::Rest,
    }
}

/// How old an instrument's market is when an order arrives — see
/// [`StaleMarketPolicy::Wait`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MarketAge {
    /// The venue has no market feed, so no age to measure.
    NoFeed,
    /// The venue holds no price for the instrument: not stale, but unpriceable, which the order's
    /// usual path reports.
    Unpriced,
    /// Observed fresh within the policy's `max_age`.
    Fresh,
    /// Priced, but last observed fresh at `fresh_at`, longer ago than the policy's `max_age`, or
    /// never.
    Stale { fresh_at: Option<DateTime<Utc>> },
}

/// What a held order is priced from when it is released.
#[derive(Debug, Clone, Copy)]
enum Release<'a> {
    /// The bar it was held for, at the reference price its [`MarketOrderTiming::NextBar`] picks.
    Bar(&'a MarketBar, NextBarPrice),
    /// The market a fresh observation left, which it was waiting for under
    /// [`StaleMarketPolicy::Wait`].
    Market(&'a MarketSnapshot),
}

/// What becomes of the quantity an arriving order's book could not fill.
///
/// The half of a [`Disposition`] that [`fill_on_arrival`](SimulatedVenue::fill_on_arrival) needs,
/// derived at the two call sites that can reach it. Carrying the limit price *here* rather than
/// re-reading [`RequestOpen::price`](crate::order::request::RequestOpen::price) is what makes
/// "rest what is left" unrepresentable for an order that has nowhere to rest it: a market order
/// has no limit price, so it cannot construct [`Rest`](Self::Rest) at all.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Remainder {
    /// Joins the book at this limit and waits to be crossed.
    Rest { limit: Decimal },
    /// Retires as [`Cancelled`], carrying whatever did trade.
    Cancel,
    /// Nothing trades at all. An order that cannot be filled in full would rather be filled not at
    /// all, so there is never a remainder for this arm to dispose of -- only a whole order to
    /// retire untouched.
    Kill,
}

impl Remainder {
    /// Whether a remainder is refused rather than disposed of, which is what makes
    /// [`TimeInForce::FillOrKill`] differ from [`TimeInForce::ImmediateOrCancel`].
    fn is_kill(self) -> bool {
        matches!(self, Self::Kill)
    }
}

fn build_open_order_err_response<E>(
    request: OrderRequestOpen<ExchangeId, InstrumentNameExchange>,
    error: E,
) -> Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState>
where
    E: Into<UnindexedOrderError>,
{
    Order {
        key: request.key,
        side: request.state.side,
        price: request.state.price,
        quantity: request.state.quantity,
        kind: request.state.kind,
        time_in_force: request.state.time_in_force,
        state: OrderState::inactive(error.into()),
    }
}

/// What one open owes the client, before it is committed and packaged into events.
///
/// Internal to [`SimulatedVenue::open_order`]: it exists only to keep the ordering contract --
/// emit the balance before the trade it paid for -- visible in one short place rather than at the
/// end of the pricing body. Nothing here is uncommitted; it is what to *say*, not what to do.
///
/// An enum rather than an optional trade because the two outcomes owe different things and a
/// missing trade is not an absent field: a rested open has a balance and *no* trade, and nothing
/// about it is incomplete.
///
/// # One arrival restates each asset once
/// Including the arrival that both settles a fill and holds against the remainder it leaves
/// resting. Those are one event at the venue and one commitment in the ledger
/// ([`AccountState::commit`]), so they restate the asset paid with once, and a spot fill the asset
/// it received once more — see that method for why an intermediate would report a balance the
/// account never held.
///
/// [`AccountState::commit`]: crate::exchange::mock::account::AccountState::commit
// `large_enum_variant`: boxing the `Trade` would trade one move of ~300 bytes for a heap
// allocation on every fill, which is the wrong way round for a backtest that does millions of
// them. The value is built once per order and destructured immediately, and the struct this
// replaced moved the same bytes on both paths -- the enum only makes the rested one smaller.
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
enum OpenOrderNotifications {
    /// The open filled on arrival: the balances it moved, and the trade it printed.
    Filled {
        commitment: Commitment,
        trade: Trade<AssetNameExchange, InstrumentNameExchange>,
    },
    /// The open rests on the book, or is held for its bar: the balance now held against it, the
    /// interest charged on what a margin account lent it, and nothing traded.
    Rested {
        balance: Snapshot<AssetBalance<AssetNameExchange>>,
        interest: Option<Box<CashFlow<AssetNameExchange, InstrumentNameExchange>>>,
    },
}

/// What one arrival committed on this venue: the balances the ledger restated, and the interest
/// charged on what a margin account lent it, if any.
#[derive(Debug)]
struct Commitment {
    committed: Committed,
    /// The cash flow reporting the interest charged on [`Committed::borrowed`] when it was lent,
    /// which [`Committed::paid`] already includes.
    ///
    /// Boxed because only a borrowing arrival on a margin account charges one: an unboxed flow
    /// would more than double every commitment, and every [`RestingSettlement`] carrying one, to
    /// serve the rare arrival that has it.
    interest: Option<Box<CashFlow<AssetNameExchange, InstrumentNameExchange>>>,
    /// The fee asset's balance, restated when a fill's fee was
    /// [taken apart](Settlement::fee_apart) from it.
    ///
    /// Boxed for the reason [`interest`](Self::interest) is: only a fill charged in a configured
    /// fee asset restates one.
    fee: Option<Box<AssetBalance<AssetNameExchange>>>,
}

impl From<Committed> for Commitment {
    fn from(committed: Committed) -> Self {
        Self {
            committed,
            interest: None,
            fee: None,
        }
    }
}

/// The instrument facts one order's settlement is computed from.
///
/// Read out of [`SimulatedVenue::instruments`] once per request, before any `&mut self` borrow of
/// the ledger, so pricing never holds a borrow the balance moves need.
#[derive(Debug, Clone)]
struct InstrumentTerms {
    underlying: Underlying<AssetNameExchange>,
    contract_size: Decimal,
    cash_settled: bool,
}

/// What settling one resting fill came to.
#[derive(Debug)]
enum RestingSettlement {
    /// The fill settled, restating these balances.
    Settled(Commitment),
    /// A fill the account can no longer afford, so the order is cancelled instead: a cash-settled
    /// one, or a spot fill whose fee exceeds what it receives by more than that asset's balance
    /// holds.
    /// Carries the balance its released hold restated, if it held anything.
    Unaffordable {
        released: Option<AssetBalance<AssetNameExchange>>,
    },
}

/// What committing an order afresh, in place of the hold it was released from, came to — see
/// `SimulatedVenue::commit_afresh`.
enum Recommitted {
    /// Committed, restating these balances. `loan` is how much of the account's loans the order
    /// accounts for afterwards: what its hold had borrowed, less what this repaid, plus what this
    /// borrowed. A caller holding part of what it committed against a remainder holds that loan
    /// against it, so a later cancel repays it.
    Committed {
        commitment: Commitment,
        loan: Decimal,
    },
    /// The account cannot cover it. Carries the balance the released hold restated, if it held
    /// anything.
    Unaffordable {
        released: Option<AssetBalance<AssetNameExchange>>,
    },
}

/// How much of an arriving order traded, and at what price.
///
/// One value because the two are decided together and used together: the quantity is what the
/// book had to give, and the price is what it gave it at.
#[derive(Debug, Clone, Copy)]
struct Fill {
    quantity: Decimal,
    price: Decimal,
}

/// What one order pays with, how much of it, the fee charged, and what the fill gives back.
#[derive(Debug, Clone)]
struct Settlement {
    /// Quote for a buy or a CFD, base for a spot sell.
    asset: AssetNameExchange,
    /// Denominated in [`asset`](Self::asset), inclusive of any fee charged in it.
    amount: Decimal,
    /// What the fill gives the account. For a CFD, the margin and realised PnL of the part that
    /// closes a position, [paid back](Credit::PaidBack) into [`asset`](Self::asset). For spot, a
    /// [delivery](Credit::Delivery) in the other asset: the base a buy receives, or the quote a
    /// sell receives, net of any fee charged in it.
    credit: Credit,
    /// In the asset the fee is charged in: quote, base for a buy under
    /// [`SpotFeeAsset::Received`], or the [`FeeAssetConfig`] asset. Its `fees_quote` is always the
    /// quote fee charged, after any discount.
    fees: AssetFees<AssetNameExchange>,
    /// Whether [`fees`](Self::fees) is taken apart from the fill: out of its own asset's free
    /// balance when the fill settles, and in neither [`amount`](Self::amount) nor
    /// [`credit`](Self::credit). Only a fill charged in the [`FeeAssetConfig`] asset, which is
    /// neither of the two assets it exchanges.
    fee_apart: bool,
}

impl Settlement {
    /// What must be held for this settlement while the order it belongs to is still working.
    ///
    /// The amount net of what the fill will pay back into the asset held, and never negative. An
    /// order that only reduces a CFD position is paid more by its fill than it costs, so it holds
    /// nothing: the account that opened a position with all of its balance can still close it. A
    /// spot fill pays back in the other asset, which funds nothing, so this is its whole amount.
    fn requirement(&self) -> Decimal {
        match &self.credit {
            Credit::PaidBack(credit) => (self.amount - credit).max(Decimal::ZERO),
            Credit::Delivery(_) => self.amount,
        }
    }

    /// The whole of this settlement leaves the account, because the whole of it traded.
    fn settled(&self) -> Debit {
        Debit {
            asset: self.asset.clone(),
            settled: self.amount,
            reserved: Decimal::ZERO,
        }
    }

    /// The whole of this settlement's [`requirement`](Self::requirement) is held, because the
    /// order it belongs to is still working.
    fn reserved(&self) -> Debit {
        Debit {
            asset: self.asset.clone(),
            settled: Decimal::ZERO,
            reserved: self.requirement(),
        }
    }

    /// This settlement traded and `remainder`'s [`requirement`](Self::requirement) is held
    /// against what is still working: one order that the book filled in part and that rested the
    /// rest.
    ///
    /// # Panics
    /// Debug-asserts that both settlements pay with the same asset. They come from one order, so
    /// they share its side and its instrument, and [`SimulatedVenue::settlement`] decides the
    /// asset from nothing else — a disagreement would mean one order paying with two assets.
    fn settled_holding(&self, remainder: &Settlement) -> Debit {
        debug_assert!(
            self.asset == remainder.asset,
            "one order settled {} of {} and reserved {} of {}: an order pays with one asset, so \
             two settlements of it cannot name two",
            self.amount,
            self.asset,
            remainder.amount,
            remainder.asset
        );

        Debit {
            asset: self.asset.clone(),
            settled: self.amount,
            reserved: remainder.requirement(),
        }
    }
}

/// A cash-settled instrument's net position on this venue: what a CFD fill closes before it
/// opens anything.
///
/// Kept per instrument, in contracts, whatever position mode the client keeps its own book in. A
/// CFD venue nets one account's trades in one instrument, which is what decides how much of a fill
/// returns margin and realises PnL rather than posting new margin.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct NetPosition {
    /// Signed quantity in contracts: positive long, negative short, zero flat.
    quantity: Decimal,
    /// Volume-weighted average price the open `quantity` was entered at. Zero while flat.
    ///
    /// Rounded to `Decimal` precision when an average does not terminate, so a later close can
    /// return a margin that differs from the one posted in the last of its 28 digits.
    entry: Decimal,
}

impl NetPosition {
    fn is_long(&self) -> bool {
        self.quantity.is_sign_positive() && !self.quantity.is_zero()
    }

    /// How much of a fill of `quantity` on `side` closes this position. The rest of it opens one.
    fn closing(&self, side: Side, quantity: Decimal) -> Decimal {
        let opposes = match side {
            Side::Buy => self.quantity.is_sign_negative() && !self.quantity.is_zero(),
            Side::Sell => self.is_long(),
        };
        match opposes {
            true => quantity.min(self.quantity.abs()),
            false => Decimal::ZERO,
        }
    }

    /// This position after a fill of `quantity` on `side` at `price`.
    ///
    /// Averaged as the `rustrade` engine averages its own `Position`: an increase moves the entry
    /// to the volume-weighted average, a reduction keeps it, and a fill that opens from flat or
    /// flips through zero enters what is left at the fill price.
    fn after(self, side: Side, quantity: Decimal, price: Decimal) -> Self {
        let signed = match side {
            Side::Buy => quantity,
            Side::Sell => -quantity,
        };
        let next = self.quantity + signed;

        let entry = if next.is_zero() {
            Decimal::ZERO
        } else if self.quantity.is_zero()
            || next.is_sign_negative() != self.quantity.is_sign_negative()
        {
            price
        } else if signed.is_sign_negative() == self.quantity.is_sign_negative() {
            (self.entry * self.quantity.abs() + price * quantity) / next.abs()
        } else {
            self.entry
        };

        Self {
            quantity: next,
            entry,
        }
    }
}

/// The id a venue seeded with `account` mints its first order with: one past the highest decimal
/// `OrderId` among the seeded orders, or `0` if none carries one.
///
/// Open and cancelled orders both count, which is everything an account snapshot seeds. Each was
/// given its id by the venue the state describes, so reusing one would make two orders
/// indistinguishable to anything keyed on it.
fn first_unseeded_order_id(account: &AccountState) -> u128 {
    let open = account
        .orders_open()
        .filter_map(|order| match &order.state.id {
            VenueOrderId::Assigned(id) => Some(id),
            VenueOrderId::ClientAssigned => None,
        });
    let cancelled = account.orders_cancelled().map(|order| &order.state.id);

    open.chain(cancelled)
        .filter_map(|id| id.0.parse::<u64>().ok())
        .max()
        .map_or(0, |highest| u128::from(highest) + 1)
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)] // Test code: panics on bad input are acceptable
mod tests {
    use super::*;
    use crate::{
        balance::{Balance, MarginDetails},
        cash_flow::CashFlowKind,
        error::OrderError,
        exchange::mock::{
            fixtures::*,
            orders::{OpenOrders, as_open},
        },
        fee::{PerContractFeeModel, PercentageFeeModel},
        fill::{BidAskFillModel, NextBarPrice, SimFillConfig},
        holding_cost::{
            AccrualDays, BorrowFeeModel, DailyAccrual, DayCount, FinancingModel, FinancingRates,
            FundingModel, HoldingCharge, RateSeries, WeekendsOnly,
        },
        margin::{InterestCharge, InterestSchedule, MarginEffect, PeriodicMarginInterest},
        order::{
            OrderEvent, OrderKey, TimeInForce,
            id::{ClientOrderId, StrategyId},
            request::RequestCancel,
            state::{ActiveOrderState, InactiveOrderState},
        },
        shortability::{Shortability, ShortabilityTable},
        slippage::SlippageConfig,
    };
    use chrono::{NaiveTime, TimeDelta};
    use rustrade_instrument::{
        Underlying,
        instrument::{
            kind::cfd::CfdContract, name::InstrumentNameInternal, quote::InstrumentQuoteAsset,
        },
    };

    fn make_venue(btc: &str, usdt: &str) -> SimulatedVenue {
        make_venue_with_fee(btc, usdt, FeeModelConfig::default())
    }

    fn make_venue_with_fee(btc: &str, usdt: &str, fee_model: FeeModelConfig) -> SimulatedVenue {
        SimulatedVenue::new(&spot_config(btc, usdt, fee_model), spot_instruments())
    }

    /// Maker 2bp against taker 10bp, so a fill charged the wrong side is off by 5x rather than by a
    /// rounding difference.
    fn maker_taker_fee() -> FeeModelConfig {
        FeeModelConfig::Percentage(PercentageFeeModel::maker_taker(d("0.0002"), d("0.001")))
    }

    /// A venue fed by a driver, and so the only regime that accepts limit orders.
    fn make_market_venue(btc: &str, usdt: &str) -> SimulatedVenue {
        make_market_venue_with(btc, usdt, maker_taker_fee(), SimFillConfig::default())
    }

    fn make_market_venue_with(
        btc: &str,
        usdt: &str,
        fee_model: FeeModelConfig,
        fill_model: SimFillConfig,
    ) -> SimulatedVenue {
        SimulatedVenue::new_market_driven(
            &spot_config_with_fill(btc, usdt, fee_model, fill_model),
            spot_instruments(),
        )
    }

    /// The balance restatement a venue owes, read off the event it emitted.
    fn balance_of(event: &UnindexedAccountEvent) -> &AssetBalance<AssetNameExchange> {
        match &event.kind {
            AccountEventKind::BalanceSnapshot(balance) => &balance.0,
            other => panic!("expected a balance restatement, got: {other:?}"),
        }
    }

    fn trade_of(
        event: &UnindexedAccountEvent,
    ) -> &Trade<AssetNameExchange, InstrumentNameExchange> {
        match &event.kind {
            AccountEventKind::Trade(trade) => trade,
            other => panic!("expected a trade, got: {other:?}"),
        }
    }

    fn order_of(
        event: &UnindexedAccountEvent,
    ) -> &Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState> {
        match &event.kind {
            AccountEventKind::OrderSnapshot(order) => &order.0,
            other => panic!("expected an order snapshot, got: {other:?}"),
        }
    }

    /// The `Open` a rested order reports, or a panic naming what it reported instead.
    fn rested_open(outcome: &OpenOutcome) -> &Open {
        match &outcome.response.state {
            OrderState::Active(ActiveOrderState::Open(open)) => open,
            other => panic!("expected a resting open order, got: {other:?}"),
        }
    }

    /// The price a filled order reports having filled at.
    fn filled_price(
        order: &Order<ExchangeId, InstrumentNameExchange, UnindexedOrderState>,
    ) -> Decimal {
        match &order.state {
            OrderState::Inactive(InactiveOrderState::FullyFilled(filled)) => filled
                .avg_price
                .expect("a filled order reports the price it filled at"),
            other => panic!("expected a fully filled order, got: {other:?}"),
        }
    }

    /// Rests one buy limit, returning the venue holding it and what it told its client.
    ///
    /// The market is set first and does not cross the order, which is what makes it rest rather
    /// than fill on arrival.
    fn venue_resting_one_buy(limit: &str) -> (SimulatedVenue, OpenOutcome) {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(1));

        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(book("49000", "49100")),
                    time(1)
                )
                .is_empty(),
            "an empty book fills nothing"
        );

        let outcome = venue.open_order(limit_request("resting", Side::Buy, "1", limit, gtc()));
        assert_eq!(
            outcome.events.len(),
            1,
            "a rested order restates one balance and books no trade"
        );

        (venue, outcome)
    }

    /// Advances `venue`, asserting the advance retired nothing.
    ///
    /// Every existing test predates deadlines and holds only `GoodUntilCancelled` orders, so a
    /// sweep that produced anything would mean an order retired that nothing asked to expire.
    /// Asserting that beats discarding the value: it is the same one line, and it pins the
    /// property instead of hiding it.
    fn advance(venue: &mut SimulatedVenue, time_exchange: DateTime<Utc>) {
        assert!(
            venue.advance_time(time_exchange).is_empty(),
            "advancing to {time_exchange} retired an order this test never gave a deadline"
        );
    }

    fn time(seconds: i64) -> DateTime<Utc> {
        DateTime::<Utc>::from_timestamp(1_700_000_000 + seconds, 0).expect("representable instant")
    }

    /// The balance snapshot a filled open owes its client, read back off the venue's own output.
    ///
    /// The assertions below go through [`VenueOutcome::events`] rather than any internal, so they
    /// pin what a driver actually delivers — and, by indexing, the order it must deliver it in.
    fn filled_balance(outcome: &OpenOutcome) -> &AssetBalance<AssetNameExchange> {
        match outcome.events.first().map(|event| &event.kind) {
            Some(AccountEventKind::BalanceSnapshot(balance)) => &balance.0,
            other => panic!("a filled open must emit its balance first, got: {other:?}"),
        }
    }

    /// The balance a filled spot open received, which follows the one it paid with.
    fn filled_received(outcome: &OpenOutcome) -> &AssetBalance<AssetNameExchange> {
        match outcome.events.get(1).map(|event| &event.kind) {
            Some(AccountEventKind::BalanceSnapshot(balance)) => &balance.0,
            other => panic!("a filled spot open must emit what it received second, got: {other:?}"),
        }
    }

    /// The trade a filled open owes its client, which must follow every balance it moved, and the
    /// interest charged on what it borrowed.
    fn filled_trade(outcome: &OpenOutcome) -> &Trade<AssetNameExchange, InstrumentNameExchange> {
        let Some(at) = outcome
            .events
            .iter()
            .position(|event| matches!(event.kind, AccountEventKind::Trade(_)))
        else {
            panic!(
                "a filled open must emit its trade, got: {:?}",
                outcome.events
            );
        };
        assert!(
            at > 0
                && outcome.events[..at].iter().all(|event| matches!(
                    event.kind,
                    AccountEventKind::BalanceSnapshot(_) | AccountEventKind::CashFlow(_)
                )),
            "a filled open must emit its balances before its trade, got: {:?}",
            outcome.events
        );
        trade_of(&outcome.events[at])
    }

    /// The venue's ordering obligation, asserted without any transport in the way.
    ///
    /// Two separate claims, because a driver needs both: each fill reports its balances before its
    /// trade, and successive fills report strictly decreasing balances. A balance here is an
    /// absolute restatement rather than a delta, so a driver that reorders them does not merely
    /// reorder history — it leaves the client holding the wrong number.
    #[test]
    fn a_filled_open_reports_its_balance_before_its_trade_and_debits_monotonically() {
        const FILLS: usize = 4;

        let mut venue = make_venue("100", "10000000");
        let mut balances = Vec::with_capacity(FILLS);

        for _ in 0..FILLS {
            let outcome = venue.open_order(buy_request("0.01", market_prices("50000")));

            assert_eq!(
                outcome.events.len(),
                3,
                "a spot fill owes the balance it paid with, the one it received, and one trade"
            );
            // The accessors assert their own positions, so reaching here is the order assertion.
            let balance = filled_balance(&outcome);
            let received = filled_received(&outcome);
            let trade = filled_trade(&outcome);

            assert_eq!(balance.asset, quote(), "a spot buy debits quote");
            assert_eq!(received.asset, base(), "and credits base");
            assert_eq!(trade.price, d("50000"));
            balances.push(balance.balance.total);
        }

        // 0.01 * 50 000 = 500 per fill, from a 10 000 000 start.
        let expected = (1..=FILLS)
            .map(|nth| d("10000000") - d("500") * Decimal::from(nth))
            .collect::<Vec<_>>();
        assert_eq!(
            balances, expected,
            "successive fills must restate a strictly decreasing balance"
        );
    }

    /// The fill is in the ledger the moment `open_order` returns, not when its events are delivered.
    ///
    /// The venue acknowledges its own trade, so the ledger cannot disagree with the events a driver
    /// is still holding: a later request sees the fill regardless of when the driver gets around to
    /// emitting it. Splitting that across the seam — book here, acknowledge in the driver — is what
    /// let one driver forget.
    #[test]
    fn a_filled_open_is_in_the_ledger_before_its_events_are_delivered() {
        let mut venue = make_venue("100", "10000000");
        let before = venue.time_exchange();

        let outcome = venue.open_order(buy_request("0.01", market_prices("50000")));
        assert_eq!(outcome.events.len(), 3, "the fill must owe events");

        // Nothing has delivered `outcome`, yet the ledger already reflects it.
        let trades = venue.trades(before);
        assert_eq!(trades.len(), 1, "the venue must acknowledge its own trade");
        assert_eq!(trades[0].price, d("50000"));
    }

    /// `advance_time` is the venue's only clock input, and it stamps everything produced after it.
    #[test]
    fn a_fill_is_stamped_with_the_instant_the_venue_was_last_advanced() {
        let mut venue = make_venue("100", "10000000");
        let time_exchange = "2025-01-01T00:00:00Z".parse::<DateTime<Utc>>().unwrap();

        advance(&mut venue, time_exchange);
        assert_eq!(venue.time_exchange(), time_exchange);

        let outcome = venue.open_order(buy_request("0.01", market_prices("50000")));
        assert_eq!(filled_trade(&outcome).time_exchange, time_exchange);
        assert_eq!(filled_balance(&outcome).time_exchange, time_exchange);
    }

    /// A resting order's arrival stamp survives the clock moving past it.
    ///
    /// `advance_time` used to rewrite `time_exchange` on every open order. Nothing rested, so the
    /// only orders it could reach were those an `initial_state` seeded — and it moved them to
    /// whenever the clock last ticked. Arrival order is half of price-time priority, so an order
    /// whose arrival instant is rewritten on every event has no arrival instant at all.
    #[test]
    fn advancing_the_clock_does_not_restamp_a_resting_order() {
        let arrived = "2025-01-01T00:00:00Z".parse::<DateTime<Utc>>().unwrap();
        let much_later = "2025-06-01T00:00:00Z".parse::<DateTime<Utc>>().unwrap();

        let mut venue = make_venue("100", "10000000");
        venue.account = AccountState::new(
            venue
                .account
                .balances()
                .cloned()
                .map(|balance| (balance.asset.clone(), balance))
                .collect(),
            {
                let mut book = OpenOrders::default();
                book.insert(
                    Order {
                        key: OrderKey {
                            exchange: EXCHANGE,
                            instrument: instrument_name(),
                            strategy: StrategyId::new("test"),
                            cid: ClientOrderId::new("resting"),
                        },
                        side: Side::Buy,
                        price: Some(d("50000")),
                        quantity: d("1"),
                        kind: OrderKind::Limit,
                        time_in_force: TimeInForce::GoodUntilCancelled { post_only: false },
                        state: Open {
                            id: VenueOrderId::Assigned(OrderId::new("resting")),
                            time_exchange: arrived,
                            filled_quantity: Decimal::ZERO,
                        },
                    },
                    None,
                )
                .unwrap();
                book
            },
            Default::default(),
            Vec::new(),
        );

        advance(&mut venue, much_later);

        let resting = venue.orders_open(&[]);
        assert_eq!(resting.len(), 1, "the seeded order must still be open");
        assert_eq!(
            resting[0].state.time_exchange, arrived,
            "an order does not become a different order because time passed"
        );

        // Balances do move: a venue restates them as of now, and they carry no ordering role.
        let usdt = venue.balances(&[quote()]);
        assert_eq!(usdt[0].time_exchange, much_later);
    }

    /// A cancel for an id the venue never booked is rejected as unknown, and the rejection is the
    /// venue's rather than any driver's.
    ///
    /// Answering here — rather than in each driver — is what stops two drivers from carrying two
    /// copies of the same policy, and the response is the one the request's channel asks for.
    #[test]
    fn a_cancel_for_an_unknown_order_is_rejected_as_unknown() {
        let mut venue = make_venue("100", "10000000");
        let key = buy_request("1", market_prices("50000")).key;

        let outcome = venue.cancel_order(OrderEvent {
            key: key.clone(),
            state: RequestCancel { id: None },
        });

        assert!(
            outcome.events.is_empty(),
            "a rejected cancel moves nothing, so it owes no events"
        );
        assert_eq!(
            outcome.response.key, key,
            "the response must name its request"
        );
        match outcome.response.state {
            Err(OrderError::Rejected(ApiError::OrderRejected(ref reason))) => {
                assert!(
                    reason.contains("test-cid"),
                    "the rejection must name the order it could not find, got: {reason}"
                );
            }
            ref other => panic!("expected a rejected cancel, got: {other:?}"),
        }

        // Nothing was cancelled, so nothing may appear in the ledger either.
        assert!(
            venue.account_snapshot().instruments.is_empty(),
            "a rejected cancel must not enter the ledger"
        );
    }

    /// `contract_size` of the CFD fixture below, as a per-point multiplier a real index CFD carries.
    const CFD_CONTRACT_SIZE: &str = "25";

    fn cfd_instrument_name() -> InstrumentNameExchange {
        InstrumentNameExchange::new("spx500_usd")
    }

    /// A USD-quoted index CFD settling in **GBP** — the case that makes the settlement asset differ
    /// from the quote asset — with **only the quote asset funded** and no `spx500` balance at all.
    /// An index is not deliverable, so requiring base inventory to short one would be unfundable.
    fn make_cfd_venue(usd: &str, fee_model: FeeModelConfig) -> SimulatedVenue {
        make_cfd_venue_with_balances(
            vec![funded(AssetNameExchange::new("usd"), d(usd))],
            fee_model,
        )
    }

    fn make_cfd_venue_with_balances(
        balances: Vec<AssetBalance<AssetNameExchange>>,
        fee_model: FeeModelConfig,
    ) -> SimulatedVenue {
        SimulatedVenue::new(
            &config_from_balances(balances, fee_model),
            instruments_of(cfd_instrument()),
        )
    }

    fn cfd_instrument() -> Instrument<ExchangeId, AssetNameExchange> {
        Instrument {
            exchange: EXCHANGE,
            name_internal: InstrumentNameInternal::new("spx500_usd"),
            name_exchange: cfd_instrument_name(),
            underlying: Underlying {
                base: AssetNameExchange::new("spx500"),
                quote: AssetNameExchange::new("usd"),
            },
            quote: InstrumentQuoteAsset::UnderlyingQuote,
            kind: InstrumentKind::Cfd(CfdContract {
                contract_size: d(CFD_CONTRACT_SIZE),
                settlement_asset: AssetNameExchange::new("gbp"),
            }),
            spec: None,
            data_venue: None,
        }
    }

    fn cfd_request(
        side: Side,
        quantity: &str,
        market: Option<MarketSnapshot>,
    ) -> OrderRequestOpen<ExchangeId, InstrumentNameExchange> {
        request(cfd_instrument_name(), side, quantity, market)
    }

    /// The multiplier must reach the ledger, or balances move 1x while the engine's PnL moves
    /// `contract_size`x — the same fill accounted two different ways.
    #[test]
    fn cfd_buy_debits_the_contract_size_scaled_notional() {
        let mut venue = make_cfd_venue("200000", FeeModelConfig::default());

        let outcome = venue.open_order(cfd_request(Side::Buy, "1", market_prices("5000")));

        assert!(
            outcome.response.state.is_accepted(),
            "cfd buy should fill: {:?}",
            outcome.response.state
        );
        assert_eq!(outcome.events.len(), 2);

        // 1 contract * 5000 * 25 = 125,000 of true notional, not the unmultiplied 5,000.
        let usd = venue
            .account
            .balance_mut(&AssetNameExchange::new("usd"))
            .unwrap();
        assert_eq!(usd.balance.free, d("200000") - d("125000"));
        assert_eq!(usd.balance.total, usd.balance.free);
    }

    /// A CFD short is a margin position, not a stock loan: it must not require inventory in an
    /// index that cannot be held. This fixture funds no `spx500` balance at all, so a base debit
    /// would panic on the missing balance rather than merely reject.
    #[test]
    fn cfd_sell_needs_no_base_inventory_and_debits_quote() {
        let mut venue = make_cfd_venue("200000", FeeModelConfig::default());

        let outcome = venue.open_order(cfd_request(Side::Sell, "1", market_prices("5000")));

        assert!(
            outcome.response.state.is_accepted(),
            "cfd short should fill without base inventory: {:?}",
            outcome.response.state
        );
        let balance = filled_balance(&outcome);
        assert_eq!(
            balance.asset,
            AssetNameExchange::new("usd"),
            "a cash-settled short debits quote, not base"
        );
        assert_eq!(balance.balance.free, d("75000"));
    }

    /// The scaled notional is what the balance check tests, so an account that could fund the
    /// unmultiplied order must still be rejected.
    #[test]
    fn cfd_buy_is_rejected_when_only_the_unscaled_notional_is_funded() {
        let mut venue = make_cfd_venue("10000", FeeModelConfig::default());

        let outcome = venue.open_order(cfd_request(Side::Buy, "1", market_prices("5000")));

        assert!(outcome.events.is_empty());
        match outcome.response.state {
            OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
                ApiError::BalanceInsufficient(Some(ref asset), _),
            ))) => {
                assert_eq!(*asset, AssetNameExchange::new("usd"));
            }
            other => panic!("expected BalanceInsufficient, got: {other:?}"),
        }
    }

    /// Fees stay quote-denominated on both sides of a CFD, are computed on the `contract_size`
    /// scaled notional, and are debited on top of it.
    ///
    /// Every amount below is hard-coded rather than read back from the event: an assertion that
    /// subtracts the reported fee from its own expected balance is satisfied by *any* fee,
    /// including the unscaled one this exists to rule out.
    #[test]
    fn cfd_fee_is_quote_denominated_on_both_sides() {
        for side in [Side::Buy, Side::Sell] {
            let mut venue = make_cfd_venue(
                "200000",
                // 0.1% of the scaled notional.
                FeeModelConfig::Percentage(PercentageFeeModel::new(d("0.001"))),
            );

            let outcome = venue.open_order(cfd_request(side, "1", market_prices("5000")));

            assert!(
                outcome.response.state.is_accepted(),
                "{side:?} should fill: {:?}",
                outcome.response.state
            );
            assert_eq!(
                filled_trade(&outcome).fees.asset,
                AssetNameExchange::new("usd"),
                "{side:?} fee asset"
            );

            // 0.001 * 5000 * 1 * 25. The unscaled answer is 5, so this pins the multiplier.
            assert_eq!(
                filled_trade(&outcome).fees.fees,
                d("125"),
                "{side:?} fee must be 0.1% of the contract_size-scaled notional"
            );
            assert_eq!(
                filled_balance(&outcome).balance.free,
                d("200000") - d("125000") - d("125"),
                "{side:?} debit must be notional + fee"
            );
        }
    }

    /// The documented caller obligation: the **quote** asset must be funded, even when the CFD
    /// settles in another currency. This mock has no conversion rate, so it cannot fall back to the
    /// settlement asset, and an unfunded quote balance is a mis-specified fixture rather than a
    /// runtime condition.
    #[test]
    #[should_panic(expected = "SimulatedVenue has Balance for all configured Instrument assets")]
    fn cfd_panics_when_the_quote_asset_is_unfunded() {
        // A realistically funded GBP account: the settlement asset is present, the quote asset is
        // not. The mock cannot convert between them, so this is a mis-specified fixture.
        let mut venue = make_cfd_venue_with_balances(
            vec![funded(AssetNameExchange::new("gbp"), d("200000"))],
            FeeModelConfig::default(),
        );

        let _ = venue.open_order(cfd_request(Side::Buy, "1", market_prices("5000")));
    }

    // --- A CFD is a net position: closing pays back what opening posted -----------------------

    fn usd() -> AssetNameExchange {
        AssetNameExchange::new("usd")
    }

    fn free_usd(venue: &SimulatedVenue) -> Decimal {
        venue.balances(&[usd()]).remove(0).balance.free
    }

    fn total_usd(venue: &SimulatedVenue) -> Decimal {
        venue.balances(&[usd()]).remove(0).balance.total
    }

    /// Fills a CFD market order at `price`, asserting it was accepted.
    fn cfd_fill(
        venue: &mut SimulatedVenue,
        side: Side,
        quantity: &str,
        price: &str,
    ) -> OpenOutcome {
        let outcome = venue.open_order(cfd_request(side, quantity, market_prices(price)));
        assert!(
            outcome.response.state.is_accepted(),
            "{side:?} {quantity} @ {price} should fill: {:?}",
            outcome.response.state
        );
        outcome
    }

    /// The venue's reported CFD position as `(quantity, entry)`, or `None` while flat.
    fn cfd_position(venue: &SimulatedVenue) -> Option<(Decimal, Option<Decimal>)> {
        let snapshot = venue.account_snapshot();
        let Some(instrument) = snapshot
            .instruments
            .iter()
            .find(|instrument| instrument.instrument == cfd_instrument_name())
        else {
            panic!("a CFD instrument is always in the snapshot, flat or not");
        };
        match &instrument.position {
            PositionReport::Open(position) => Some((position.quantity, position.entry_price)),
            PositionReport::Flat => None,
            PositionReport::Unreported => panic!("a CFD position is reported, not Unreported"),
        }
    }

    /// The bug this ledger fixes: an account that opens with most of its balance can close, and a
    /// round trip moves the balance by the realised PnL alone. 1 contract × 25 × the price move.
    #[test]
    fn a_cfd_round_trip_returns_the_margin_and_settles_the_pnl() {
        // (opening side, open price, close price, balance after the round trip)
        for (side, open, close, end) in [
            (Side::Buy, "5000", "5100", "152500"),  // long that wins 2,500
            (Side::Sell, "5000", "4900", "152500"), // short that wins 2,500
            (Side::Sell, "5000", "5200", "145000"), // short that loses 5,000
        ] {
            let mut venue = make_cfd_venue("150000", FeeModelConfig::default());

            cfd_fill(&mut venue, side, "1", open);
            assert_eq!(
                free_usd(&venue),
                d("25000"),
                "{side:?}: opening posts 125,000"
            );

            let closing = match side {
                Side::Buy => Side::Sell,
                Side::Sell => Side::Buy,
            };
            let outcome = cfd_fill(&mut venue, closing, "1", close);

            assert_eq!(
                filled_balance(&outcome).balance.free,
                d(end),
                "{side:?} @ {close}"
            );
            assert_eq!(total_usd(&venue), d(end), "{side:?}: nothing is left held");
            assert_eq!(
                cfd_position(&venue),
                None,
                "{side:?}: the round trip is flat"
            );
        }
    }

    /// One sell of 3 against a long of 1 closes the long and opens a short of 2, and the long it
    /// closes helps fund the short it opens.
    #[test]
    fn a_cfd_flip_closes_the_position_and_opens_the_rest_in_one_fill() {
        let mut venue = make_cfd_venue("300000", FeeModelConfig::default());
        cfd_fill(&mut venue, Side::Buy, "1", "5000");
        assert_eq!(free_usd(&venue), d("175000"));

        // Closing 1 pays back 1 × 25 × 5100 = 127,500; opening 2 posts 2 × 25 × 5100 = 255,000.
        // 175,000 alone could not post 255,000, so the close is what funds it.
        cfd_fill(&mut venue, Side::Sell, "3", "5100");

        assert_eq!(free_usd(&venue), d("175000") + d("127500") - d("255000"));
        assert_eq!(cfd_position(&venue), Some((d("-2"), Some(d("5100")))));
    }

    #[test]
    fn a_partial_cfd_reduce_keeps_the_entry_and_pays_back_its_share() {
        let mut venue = make_cfd_venue("300000", FeeModelConfig::default());
        cfd_fill(&mut venue, Side::Buy, "2", "5000");
        assert_eq!(free_usd(&venue), d("50000"));

        cfd_fill(&mut venue, Side::Sell, "1", "5200");

        // 1 × 25 × 5200: the 125,000 posted for it plus 5,000 of PnL.
        assert_eq!(free_usd(&venue), d("180000"));
        assert_eq!(
            cfd_position(&venue),
            Some((d("2") - d("1"), Some(d("5000"))))
        );
    }

    #[test]
    fn increasing_a_cfd_position_averages_its_entry() {
        let mut venue = make_cfd_venue("300000", FeeModelConfig::default());
        cfd_fill(&mut venue, Side::Buy, "1", "5000");
        cfd_fill(&mut venue, Side::Buy, "1", "5200");

        assert_eq!(free_usd(&venue), d("300000") - d("125000") - d("130000"));
        assert_eq!(cfd_position(&venue), Some((d("2"), Some(d("5100")))));
    }

    /// Fees stay on the whole quantity whichever way it splits, so a round trip costs the PnL and
    /// both fees and nothing else.
    #[test]
    fn a_cfd_close_is_charged_its_fee_on_top_of_the_proceeds() {
        let mut venue = make_cfd_venue(
            "200000",
            FeeModelConfig::Percentage(PercentageFeeModel::new(d("0.001"))),
        );
        cfd_fill(&mut venue, Side::Buy, "1", "5000"); // fee 125
        let outcome = cfd_fill(&mut venue, Side::Sell, "1", "5100"); // fee 127.5

        assert_eq!(filled_trade(&outcome).fees.fees, d("127.5"));
        assert_eq!(
            free_usd(&venue),
            d("200000") + d("2500") - d("125") - d("127.5")
        );
    }

    /// A short that more than doubles has lost more than its margin. Nothing liquidated it, so the
    /// shortfall is paid rather than credited as a negative amount.
    #[test]
    fn a_cfd_short_that_loses_more_than_its_margin_pays_the_shortfall() {
        let mut venue = make_cfd_venue("200000", FeeModelConfig::default());
        cfd_fill(&mut venue, Side::Sell, "1", "1000"); // posts 25,000
        cfd_fill(&mut venue, Side::Buy, "1", "2500"); // loses 37,500

        assert_eq!(free_usd(&venue), d("200000") - d("37500"));
        assert_eq!(cfd_position(&venue), None);
    }

    #[test]
    fn a_spot_instrument_still_reports_no_position() {
        let mut venue = make_venue("10", "1000000");
        let _ = venue.open_order(request(
            instrument_name(),
            Side::Buy,
            "1",
            market_prices("50000"),
        ));

        let snapshot = venue.account_snapshot();
        assert!(
            snapshot
                .instruments
                .iter()
                .all(|instrument| instrument.position == PositionReport::Unreported),
            "a spot holding is a balance, not a position"
        );
    }

    #[test]
    fn a_cfd_position_in_the_initial_state_is_where_the_venue_starts() {
        let config = MockExecutionConfig::new(
            EXCHANGE,
            UnindexedAccountSnapshot {
                exchange: EXCHANGE,
                balances: vec![funded(usd(), d("10000"))],
                instruments: vec![InstrumentAccountSnapshot {
                    instrument: cfd_instrument_name(),
                    orders: vec![],
                    orders_complete: true,
                    position: PositionReport::from_position(Position::new(
                        d("-1"),
                        Some(d("5000")),
                        None,
                        None,
                        None,
                        None,
                        None,
                        time(0),
                    )),
                    isolated: None,
                }],
            },
            0,
            FeeModelConfig::default(),
            SimFillConfig::default(),
            SpotFeeAsset::default(),
            crate::slippage::SlippageConfig::default(),
            crate::fill::MarketOrderTiming::default(),
            crate::fill::StaleMarketPolicy::default(),
            None,
            None,
        );
        let mut venue = SimulatedVenue::new(&config, instruments_of(cfd_instrument()));
        assert_eq!(cfd_position(&venue), Some((d("-1"), Some(d("5000")))));

        // Its margin counts as posted, so closing it pays that back: 25 × (2 × 5000 − 4800).
        cfd_fill(&mut venue, Side::Buy, "1", "4800");
        assert_eq!(free_usd(&venue), d("10000") + d("130000"));
    }

    #[test]
    #[should_panic(expected = "no entry price")]
    fn a_cfd_position_in_the_initial_state_without_an_entry_price_panics() {
        let config = MockExecutionConfig::new(
            EXCHANGE,
            UnindexedAccountSnapshot {
                exchange: EXCHANGE,
                balances: vec![funded(usd(), d("10000"))],
                instruments: vec![InstrumentAccountSnapshot {
                    instrument: cfd_instrument_name(),
                    orders: vec![],
                    orders_complete: true,
                    position: PositionReport::from_position(Position::new(
                        d("-1"),
                        None,
                        None,
                        None,
                        None,
                        None,
                        None,
                        time(0),
                    )),
                    isolated: None,
                }],
            },
            0,
            FeeModelConfig::default(),
            SimFillConfig::default(),
            SpotFeeAsset::default(),
            crate::slippage::SlippageConfig::default(),
            crate::fill::MarketOrderTiming::default(),
            crate::fill::StaleMarketPolicy::default(),
            None,
            None,
        );
        let _ = SimulatedVenue::new(&config, instruments_of(cfd_instrument()));
    }

    // --- A resting CFD order holds only what it opens ------------------------------------------

    fn make_cfd_market_venue(usd: &str) -> SimulatedVenue {
        let mut venue = SimulatedVenue::new_market_driven(
            &config_from_balances(vec![funded(self::usd(), d(usd))], FeeModelConfig::default()),
            instruments_of(cfd_instrument()),
        );
        advance(&mut venue, time(1));
        venue
    }

    fn cfd_limit(
        cid: &str,
        side: Side,
        quantity: &str,
        price: &str,
    ) -> OrderRequestOpen<ExchangeId, InstrumentNameExchange> {
        let mut request = limit_request(cid, side, quantity, price, gtc());
        request.key.instrument = cfd_instrument_name();
        request
    }

    /// Feeds the CFD a market with a book and a trade price, returning whatever it filled.
    fn cfd_market(
        venue: &mut SimulatedVenue,
        bid: &str,
        ask: &str,
        last: &str,
    ) -> Vec<UnindexedAccountEvent> {
        let time_exchange = venue.time_exchange();
        venue.apply_market(
            &cfd_instrument_name(),
            MarketObservation::new(MarketSnapshot {
                best_bid: Some(d(bid)),
                best_ask: Some(d(ask)),
                last_price: Some(d(last)),
            }),
            time_exchange,
        )
    }

    fn cfd_market_fill(venue: &mut SimulatedVenue, side: Side, quantity: &str) {
        let outcome = venue.open_order(cfd_request(side, quantity, None));
        assert!(
            outcome.response.state.is_accepted(),
            "{side:?} {quantity} should fill: {:?}",
            outcome.response.state
        );
    }

    /// An account fully deployed in a long can still rest the order that closes it, which holds
    /// nothing, and the close pays the margin back when it fills.
    #[test]
    fn a_resting_order_that_only_reduces_a_cfd_position_holds_nothing() {
        let mut venue = make_cfd_market_venue("125000");
        assert!(cfd_market(&mut venue, "4990", "5000", "5000").is_empty());
        cfd_market_fill(&mut venue, Side::Buy, "1");
        assert_eq!(
            free_usd(&venue),
            Decimal::ZERO,
            "the long took the whole balance"
        );

        let outcome = venue.open_order(cfd_limit("close", Side::Sell, "1", "5200"));
        assert!(rested_open(&outcome).filled_quantity.is_zero());
        assert_eq!(
            total_usd(&venue) - free_usd(&venue),
            Decimal::ZERO,
            "nothing is held"
        );

        let events = cfd_market(&mut venue, "5200", "5210", "5200");
        assert_eq!(balance_of(&events[0]).balance.free, d("130000"));
        assert_eq!(filled_price(order_of(&events[2])), d("5200"));
        assert_eq!(cfd_position(&venue), None);
    }

    #[test]
    fn a_resting_order_that_opens_a_cfd_position_holds_its_margin_until_cancelled() {
        let mut venue = make_cfd_market_venue("200000");
        assert!(cfd_market(&mut venue, "4990", "5000", "5000").is_empty());

        let _ = venue.open_order(cfd_limit("open", Side::Buy, "1", "4800"));
        assert_eq!(free_usd(&venue), d("200000") - d("120000"));
        assert_eq!(total_usd(&venue), d("200000"));

        let cancelled = venue.cancel_order(OrderRequestCancel {
            key: cfd_limit("open", Side::Buy, "1", "4800").key,
            state: RequestCancel { id: None },
        });
        assert!(cancelled.response.state.is_ok());
        assert_eq!(free_usd(&venue), d("200000"));
    }

    /// The position a resting order was costed against can be gone by the time it fills: here a
    /// market sell closes the long the resting sell was going to close, so the resting sell now
    /// opens a short. It is costed again at the fill and posts that short's margin.
    #[test]
    fn a_resting_cfd_order_is_costed_against_the_position_when_it_fills() {
        let mut venue = make_cfd_market_venue("300000");
        assert!(cfd_market(&mut venue, "5000", "5000", "5000").is_empty());
        cfd_market_fill(&mut venue, Side::Buy, "1"); // posts 125,000

        let _ = venue.open_order(cfd_limit("close", Side::Sell, "1", "5200"));
        assert_eq!(
            free_usd(&venue),
            d("175000"),
            "a reducing order holds nothing"
        );

        cfd_market_fill(&mut venue, Side::Sell, "1"); // closes the long at 5,000
        assert_eq!(free_usd(&venue), d("300000"));
        assert_eq!(cfd_position(&venue), None);

        let events = cfd_market(&mut venue, "5200", "5210", "5200");
        assert_eq!(
            balance_of(&events[0]).balance.free,
            d("300000") - d("130000"),
            "the resting sell now opens a short of 1 at 5,200"
        );
        assert_eq!(cfd_position(&venue), Some((d("-1"), Some(d("5200")))));
    }

    /// The same, for an account that cannot afford the short the order now opens. It is cancelled
    /// rather than filled with balance the account does not have.
    #[test]
    fn a_resting_cfd_order_the_account_can_no_longer_afford_is_cancelled() {
        let mut venue = make_cfd_market_venue("126000");
        assert!(cfd_market(&mut venue, "5000", "5000", "5000").is_empty());
        cfd_market_fill(&mut venue, Side::Buy, "1");
        let _ = venue.open_order(cfd_limit("close", Side::Sell, "1", "5200"));
        cfd_market_fill(&mut venue, Side::Sell, "1");
        assert_eq!(free_usd(&venue), d("126000"));

        let events = cfd_market(&mut venue, "5200", "5210", "5200");

        // Its released hold (nothing, since it only reduced when it rested) restates first, and
        // the cancelled order comes last.
        let Some((last, released)) = events.split_last() else {
            panic!("an unaffordable fill reports its cancelled order");
        };
        assert!(
            matches!(
                order_of(last).state,
                OrderState::Inactive(InactiveOrderState::Cancelled(_))
            ),
            "{:?}",
            order_of(last).state
        );
        assert!(
            released
                .iter()
                .all(|event| balance_of(event).balance.free == d("126000")),
            "no balance moved"
        );
        assert_eq!(free_usd(&venue), d("126000"), "nothing moved");
        assert_eq!(cfd_position(&venue), None);
        assert!(venue.account.is_cancelled(&ClientOrderId::new("close")));
    }

    /// The same, for an order that holds something: its hold is given back before the order is
    /// cancelled, and nothing else moves. The resting sell of 3 closes the long of 1 and opens a
    /// short of 2, so it holds the 2's margin net of the 1's proceeds. Once a market sell has
    /// closed the long, its fill would open a short of 3, which the account cannot cover.
    #[test]
    fn a_resting_cfd_order_cancelled_as_unaffordable_releases_its_hold() {
        let mut venue = make_cfd_market_venue("260000");
        assert!(cfd_market(&mut venue, "5000", "5000", "5000").is_empty());
        cfd_market_fill(&mut venue, Side::Buy, "1"); // posts 125,000

        let _ = venue.open_order(cfd_limit("flip", Side::Sell, "3", "5200"));
        assert_eq!(
            free_usd(&venue),
            d("260000") - d("125000") - (d("260000") - d("130000")),
            "holds the short's 260,000 net of the long's 130,000"
        );

        cfd_market_fill(&mut venue, Side::Sell, "1"); // closes the long at 5,000
        assert_eq!(free_usd(&venue), d("130000"));
        assert_eq!(total_usd(&venue), d("260000"));

        let events = cfd_market(&mut venue, "5200", "5210", "5200");

        let Some((last, released)) = events.split_last() else {
            panic!("an unaffordable fill reports its cancelled order");
        };
        assert!(
            matches!(
                order_of(last).state,
                OrderState::Inactive(InactiveOrderState::Cancelled(_))
            ),
            "{:?}",
            order_of(last).state
        );
        let [released] = released else {
            panic!("exactly the released hold restates: {released:?}");
        };
        assert_eq!(
            balance_of(released).balance.free,
            d("260000"),
            "the hold is given back"
        );
        assert_eq!(free_usd(&venue), d("260000"));
        assert_eq!(total_usd(&venue), d("260000"), "nothing settled");
        assert_eq!(cfd_position(&venue), None);
        assert!(venue.account.is_cancelled(&ClientOrderId::new("flip")));
    }

    #[test]
    fn sell_order_decrements_base_and_credits_quote_proceeds() {
        let mut venue = make_venue("1.0", "10000");
        let initial_usdt = d("10000");

        let outcome = venue.open_order(sell_request("0.5", market_prices("50000")));

        assert!(
            outcome.response.state.is_accepted(),
            "sell should succeed: {:?}",
            outcome.response.state
        );
        assert_eq!(outcome.events.len(), 3, "a successful sell must notify");
        assert_eq!(
            filled_balance(&outcome).asset,
            base(),
            "a sell pays with base"
        );
        assert_eq!(
            filled_received(&outcome).asset,
            quote(),
            "and receives quote"
        );

        // Base (BTC) must be decremented by the quantity sold.
        let btc = venue.account.balance_mut(&base()).unwrap();
        assert_eq!(
            btc.balance.free,
            d("0.5"),
            "base balance should decrease by quantity sold"
        );

        // Quote (USDT) is credited the proceeds: 0.5 * 50000, with no fee in this test.
        let usdt = venue.account.balance_mut(&quote()).unwrap();
        assert_eq!(
            usdt.balance.free,
            initial_usdt + d("25000"),
            "quote balance should rise by the proceeds"
        );
    }

    /// A derivative must be rejected, not filled down the physically-settled spot path.
    ///
    /// The fixture is mutated through the public `instruments` map on purpose: that is exactly the
    /// route a consumer takes when it builds a venue itself rather than through the `rustrade`
    /// builder, and it is the route that had no gate on it.
    #[test]
    fn unsupported_instrument_kinds_are_rejected_rather_than_filled_as_spot() {
        use rustrade_instrument::instrument::kind::{
            future::FutureContract,
            option::{OptionContract, OptionExercise, OptionKind},
            perpetual::PerpetualContract,
        };

        let settlement = AssetNameExchange::new("USDT");
        let expiry = Utc::now();

        let unsupported = [
            InstrumentKind::Perpetual(PerpetualContract {
                contract_size: d("10"),
                settlement_asset: settlement.clone(),
            }),
            InstrumentKind::Future(FutureContract {
                contract_size: d("10"),
                settlement_asset: settlement.clone(),
                expiry,
            }),
            InstrumentKind::Option(OptionContract {
                contract_size: d("10"),
                settlement_asset: settlement.clone(),
                kind: OptionKind::Call,
                exercise: OptionExercise::European,
                expiry,
                strike: d("50000"),
            }),
        ];

        for kind in unsupported {
            // Amply funded: the rejection must come from the kind, not from a balance shortfall.
            let mut venue = make_venue("10", "10000000");
            venue.instruments.get_mut(&instrument_name()).unwrap().kind = kind.clone();

            let outcome = venue.open_order(buy_request("1.0", market_prices("50000")));

            assert!(
                outcome.events.is_empty(),
                "{kind:?} must produce no account events"
            );
            assert!(
                matches!(
                    outcome.response.state,
                    OrderState::Inactive(InactiveOrderState::OpenFailed(
                        UnindexedOrderError::Connectivity(_) | UnindexedOrderError::Rejected(_)
                    ))
                ),
                "{kind:?} must be rejected, got {:?}",
                outcome.response.state
            );

            // And the ledger must be untouched -- a rejected order that still moved cash would be
            // worse than one that filled.
            let usdt = venue.account.balance_mut(&quote()).unwrap();
            assert_eq!(
                usdt.balance.free,
                d("10000000"),
                "{kind:?} must not move the quote balance"
            );
        }
    }

    #[test]
    fn sell_order_insufficient_balance_names_base_asset() {
        // Regression guard for a sell-side balance bug: previously `balance_mut(&underlying.quote)`
        // was called for sells, so BalanceInsufficient would name the quote asset (USDT) instead of
        // the base (BTC).
        let mut venue = make_venue("0.1", "10000");

        // Selling 1 BTC but only 0.1 available.
        let outcome = venue.open_order(sell_request("1.0", market_prices("50000")));

        assert!(
            outcome.events.is_empty(),
            "failed order must produce no account events"
        );
        match outcome.response.state {
            OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
                ApiError::BalanceInsufficient(Some(ref asset), _),
            ))) => {
                assert_eq!(
                    *asset,
                    base(),
                    "BalanceInsufficient must name the base asset (BTC), not the quote (USDT)"
                );
            }
            other => panic!("expected BalanceInsufficient, got: {other:?}"),
        }
    }

    #[test]
    fn bid_ask_fill_model_fills_at_ask_price_and_deducts_correct_balance() {
        let mut venue = make_venue("0", "10000"); // 0 BTC, 10 000 USDT
        venue.fill_model = Arc::new(SimFillConfig::BidAsk(BidAskFillModel));

        let market = Some(MarketSnapshot {
            best_bid: Some(d("99.5")),
            best_ask: Some(d("100.5")),
            last_price: Some(d("100.0")),
        });

        // Market buy of 1 BTC; last_price 100 is only a fallback for when the fill model returns
        // None — BidAsk returns best_ask, so it is not used.
        let outcome = venue.open_order(buy_request("1", market));

        assert!(
            outcome.response.state.is_accepted(),
            "buy should succeed: {:?}",
            outcome.response.state
        );

        // BidAskFillModel: market buy fills at best_ask = 100.5, not last_price 100.0.
        assert_eq!(
            filled_trade(&outcome).price,
            d("100.5"),
            "fill price must be best_ask"
        );

        // Balance deduction: 1 * 100.5 = 100.5 USDT; fee_model = Zero.
        let usdt = venue.account.balance_mut(&quote()).unwrap();
        assert_eq!(
            usdt.balance.free,
            d("9899.5"),
            "quote balance must decrease by fill_price * qty"
        );
    }

    // --- Slippage ---

    /// A funded spot config moving every taker fill by `slippage`.
    fn slipped_config(slippage: SlippageConfig) -> MockExecutionConfig {
        MockExecutionConfig {
            slippage,
            ..spot_config("10", "1000000", FeeModelConfig::default())
        }
    }

    fn last(price: &str) -> Option<MarketSnapshot> {
        Some(MarketSnapshot {
            last_price: Some(d(price)),
            ..MarketSnapshot::default()
        })
    }

    fn uniform(seed: u64) -> SlippageConfig {
        SlippageConfig::uniform(d("0.01"), d("0.025"), seed).unwrap()
    }

    #[test]
    fn a_fixed_slippage_moves_a_market_fill_against_the_order_and_settles_that_price() {
        let config = slipped_config(SlippageConfig::fixed(d("0.01")).unwrap());
        let mut venue = SimulatedVenue::new(&config, spot_instruments());

        let bought = venue.open_order(buy_request("2", last("100")));
        assert_eq!(filled_trade(&bought).price, d("101"), "a buy pays 1% above");
        assert_eq!(
            venue.account.balance_mut(&quote()).unwrap().balance.free,
            d("999798"),
            "the quote debited is the slipped price times the quantity"
        );

        let sold = venue.open_order(sell_request("2", last("100")));
        assert_eq!(
            filled_trade(&sold).price,
            d("99"),
            "a sell receives 1% below"
        );
        assert_eq!(
            venue.account.balance_mut(&quote()).unwrap().balance.free,
            d("999996"),
            "the round trip cost the 1% on each side"
        );
    }

    /// The clamp comes after the slippage, so no rate fills a limit order past its own limit.
    #[test]
    fn a_slipped_marketable_limit_never_fills_past_its_limit() {
        let fill = |rate: &str, side: Side, limit: &str| {
            let config = slipped_config(SlippageConfig::fixed(d(rate)).unwrap());
            let mut venue = SimulatedVenue::new_market_driven(&config, spot_instruments());
            advance(&mut venue, time(1));
            let fed = venue.apply_market(
                &instrument_name(),
                MarketObservation::new(book("49000", "49100")),
                time(1),
            );
            assert!(fed.is_empty(), "an empty book fills nothing");
            let outcome = venue.open_order(limit_request("cid", side, "1", limit, gtc()));
            filled_trade(&outcome).price
        };

        assert_eq!(
            fill("0.01", Side::Buy, "49200"),
            d("49200"),
            "49591 slipped, clamped to the limit"
        );
        assert_eq!(
            fill("0.01", Side::Sell, "48800"),
            d("48800"),
            "48510 slipped, clamped to the limit"
        );
        assert_eq!(
            fill("0.001", Side::Buy, "49200"),
            d("49149.1"),
            "inside the limit, the slipped price stands"
        );
    }

    /// A resting order is the maker, so it fills at its own limit and leaves the stream alone.
    #[test]
    fn a_resting_fill_is_not_slipped_and_takes_no_draw() {
        let config = MockExecutionConfig {
            slippage: uniform(5),
            ..spot_config("10", "1000000", maker_taker_fee())
        };
        let mut venue = SimulatedVenue::new_market_driven(&config, spot_instruments());
        advance(&mut venue, time(1));
        let fed = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("49000", "49100")),
            time(1),
        );
        assert!(fed.is_empty(), "an empty book fills nothing");
        let rested = venue.open_order(limit_request("resting", Side::Buy, "1", "48000", gtc()));
        rested_open(&rested);
        assert_eq!(
            venue.slippage,
            Slippage::new(config.slippage),
            "resting drew nothing"
        );

        advance(&mut venue, time(2));
        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("47800", "47900")),
            time(2),
        );
        assert_eq!(trade_of(&events[2]).price, d("48000"));
        assert_eq!(
            venue.slippage,
            Slippage::new(config.slippage),
            "the maker's fill drew nothing"
        );
    }

    /// A marketable order the book has no size for trades nothing, whether it then rests or is
    /// cancelled, so it takes no draw.
    #[test]
    fn an_order_the_book_cannot_fill_takes_no_draw() {
        let config = slipped_config(uniform(3));
        let mut venue = SimulatedVenue::new_market_driven(&config, spot_instruments());
        advance(&mut venue, time(1));
        let fed = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("47800", "47900"))
                .with_depth(MarketDepth::new(Some(d("1")), Some(Decimal::ZERO))),
            time(1),
        );
        assert!(fed.is_empty(), "an empty book fills nothing");

        let rested = venue.open_order(limit_request("rests", Side::Buy, "1", "48000", gtc()));
        assert_eq!(rested_open(&rested).filled_quantity, Decimal::ZERO);
        let cancelled = venue.open_order(limit_request(
            "cancels",
            Side::Buy,
            "1",
            "48000",
            TimeInForce::ImmediateOrCancel,
        ));
        assert!(
            matches!(
                cancelled.response.state,
                OrderState::Inactive(InactiveOrderState::Cancelled(_))
            ),
            "{:?}",
            cancelled.response.state
        );

        assert_eq!(venue.slippage, Slippage::new(config.slippage));
    }

    /// A funded spot venue on a book offering `depth`, moving every taker fill by `slippage`.
    fn slipped_venue_offering(
        usdt: &str,
        slippage: SlippageConfig,
        depth: MarketDepth,
    ) -> SimulatedVenue {
        let config = MockExecutionConfig {
            slippage,
            ..spot_config("10", usdt, FeeModelConfig::default())
        };
        let mut venue = SimulatedVenue::new_market_driven(&config, spot_instruments());
        advance(&mut venue, time(1));
        let fed = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("47800", "47900")).with_depth(depth),
            time(1),
        );
        assert!(fed.is_empty(), "an empty book fills nothing");
        venue
    }

    /// The book fills 1 of 3: that fill is slipped, with one draw, and the remainder rests at the
    /// order's own limit.
    #[test]
    fn a_part_filled_order_is_slipped_once_and_rests_the_rest_at_its_limit() {
        let mut venue = slipped_venue_offering("1000000", uniform(8), sized("1"));
        let mut expected = Slippage::new(uniform(8));
        let price = expected.apply(Side::Buy, d("47900"));

        let outcome = venue.open_order(limit_request("part", Side::Buy, "3", "50000", gtc()));
        let trade = filled_trade(&outcome);
        assert_eq!((trade.quantity, trade.price), (d("1"), price));
        assert_eq!(rested_open(&outcome).filled_quantity, d("1"));
        assert_eq!(venue.slippage, expected, "one fill, one draw");
        assert_eq!(
            venue
                .account
                .orders()
                .resting(&instrument_name(), Side::Buy)
                .map(|order| order.price)
                .collect::<Vec<_>>(),
            vec![Some(d("50000"))],
            "the remainder rests at its limit, unslipped"
        );
    }

    /// A fill-or-kill the book can only part fill trades nothing, so it takes no draw.
    #[test]
    fn a_killed_order_takes_no_draw() {
        let mut venue = slipped_venue_offering("1000000", uniform(8), sized("1"));
        let outcome = venue.open_order(limit_request(
            "kill",
            Side::Buy,
            "3",
            "50000",
            TimeInForce::FillOrKill,
        ));
        assert!(
            matches!(
                outcome.response.state,
                OrderState::Inactive(InactiveOrderState::Cancelled(_))
            ),
            "{:?}",
            outcome.response.state
        );
        assert_eq!(venue.slippage, Slippage::new(uniform(8)));
    }

    /// The fill is affordable, its remainder's hold is not: refused whole, and the draw handed back.
    #[test]
    fn a_part_filled_order_refused_for_its_hold_hands_back_its_draw() {
        let mut venue = slipped_venue_offering("60000", uniform(8), sized("1"));
        let outcome = venue.open_order(limit_request("split", Side::Buy, "3", "50000", gtc()));
        assert!(
            matches!(
                outcome.response.state,
                OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
                    ApiError::BalanceInsufficient(..)
                )))
            ),
            "{:?}",
            outcome.response.state
        );
        assert_eq!(venue.slippage, Slippage::new(uniform(8)));
    }

    /// An order the ledger refuses never traded, so the next fill gets the rate it would have got
    /// had the refused order never been sent.
    #[test]
    fn a_refused_order_hands_back_its_draw() {
        let config = slipped_config(uniform(11));
        let mut venue = SimulatedVenue::new(&config, spot_instruments());

        let refused = venue.open_order(buy_request("1000000", last("100")));
        assert!(
            matches!(
                refused.response.state,
                OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
                    ApiError::BalanceInsufficient(..)
                )))
            ),
            "{:?}",
            refused.response.state
        );
        assert_eq!(venue.slippage, Slippage::new(config.slippage));

        let mut fresh = SimulatedVenue::new(&config, spot_instruments());
        assert_eq!(
            filled_trade(&venue.open_order(buy_request("1", last("100")))).price,
            filled_trade(&fresh.open_order(buy_request("1", last("100")))).price,
        );
    }

    /// The prices of a sequence of fills, alternating buys and sells, on a venue built from
    /// `config`.
    fn slipped_prices(config: &MockExecutionConfig) -> Vec<Decimal> {
        let mut venue = SimulatedVenue::new(config, spot_instruments());
        (0..20)
            .map(|i| {
                let request = if i % 2 == 0 {
                    buy_request("0.1", last("100"))
                } else {
                    sell_request("0.1", last("100"))
                };
                filled_trade(&venue.open_order(request)).price
            })
            .collect()
    }

    #[test]
    fn a_seeded_venue_reproduces_its_prices_within_the_range() {
        let prices = slipped_prices(&slipped_config(uniform(42)));
        assert_eq!(prices, slipped_prices(&slipped_config(uniform(42))));
        assert_ne!(prices, slipped_prices(&slipped_config(uniform(43))));

        for (i, price) in prices.iter().enumerate() {
            // Buys pay 1% to 2.5% above 100, sells receive 1% to 2.5% below.
            let (low, high) = if i % 2 == 0 {
                (d("101"), d("102.5"))
            } else {
                (d("97.5"), d("99"))
            };
            assert!(
                low <= *price && *price <= high,
                "fill {i} at {price} outside [{low}, {high}]"
            );
        }
    }

    /// A zero rate never draws and never multiplies, so it is the unslipped price exactly, scale
    /// included.
    #[test]
    fn a_zero_rate_is_identical_to_no_slippage() {
        let none = slipped_prices(&slipped_config(SlippageConfig::none()));
        let zero = slipped_prices(&slipped_config(
            SlippageConfig::uniform(Decimal::ZERO, Decimal::ZERO, 42).unwrap(),
        ));
        assert_eq!(
            none.iter().map(Decimal::to_string).collect::<Vec<_>>(),
            zero.iter().map(Decimal::to_string).collect::<Vec<_>>()
        );
    }

    /// Prices a fill one unit of price above the last trade for each unit of quantity.
    #[derive(Debug)]
    struct SizeImpact;

    impl FillModel for SizeImpact {
        fn fill_price(&self, fill: &FillContext<'_>) -> Option<Decimal> {
            fill.market.last_price.map(|last| last + fill.quantity)
        }
    }

    /// A custom model prices from the order's quantity, and the configured slippage still
    /// applies to what it returns.
    #[test]
    fn a_custom_fill_model_sees_the_quantity_and_is_still_slipped() {
        let config = slipped_config(SlippageConfig::fixed(d("0.01")).unwrap());
        let mut venue =
            SimulatedVenue::new(&config, spot_instruments()).with_fill_model(Arc::new(SizeImpact));

        let outcome = venue.open_order(buy_request("3", last("100")));
        assert_eq!(
            filled_trade(&outcome).price,
            d("104.03"),
            "(100 + 3) x 1.01"
        );
    }

    #[test]
    fn percentage_fee_model_deducts_correct_fee_on_buy() {
        // 0.1% fee rate
        let fee_model = FeeModelConfig::Percentage(PercentageFeeModel::new(d("0.001")));
        let mut venue = make_venue_with_fee("0", "10000", fee_model);

        // Buy 10 BTC at price 100 USDT each
        // Notional = 10 * 100 = 1000 USDT
        // Fee = 1000 * 0.001 = 1 USDT
        // Total deducted = 1000 + 1 = 1001 USDT
        let outcome = venue.open_order(buy_request("10", market_prices("100")));

        assert!(
            outcome.response.state.is_accepted(),
            "buy should succeed: {:?}",
            outcome.response.state
        );

        // Trade must report fee in quote denomination
        assert_eq!(
            filled_trade(&outcome).fees.fees,
            d("1"),
            "trade fee must be 1 USDT"
        );

        // Quote balance: 10000 - 1001 = 8999
        let usdt = venue.account.balance_mut(&quote()).unwrap();
        assert_eq!(
            usdt.balance.free,
            d("8999"),
            "quote balance must decrease by notional + fee"
        );
    }

    #[test]
    fn percentage_fee_model_deducts_correct_fee_on_sell() {
        // 0.1% fee rate
        let fee_model = FeeModelConfig::Percentage(PercentageFeeModel::new(d("0.001")));
        let mut venue = make_venue_with_fee("10", "0", fee_model);

        // Sell 1 BTC at price 100 USDT
        // Notional = 1 * 100 = 100 USDT
        // Fee (quote) = 100 * 0.001 = 0.1 USDT, out of the proceeds
        // Base deducted = 1 BTC; quote credited = 100 - 0.1 = 99.9 USDT
        let outcome = venue.open_order(sell_request("1", market_prices("100")));

        assert!(
            outcome.response.state.is_accepted(),
            "sell should succeed: {:?}",
            outcome.response.state
        );

        // Trade must report fee in quote denomination
        assert_eq!(
            filled_trade(&outcome).fees.fees,
            d("0.1"),
            "trade fee must be 0.1 USDT"
        );

        // Base balance: 10 - 1 = 9, so the base moved equals the quantity the engine counts
        let btc = venue.account.balance_mut(&base()).unwrap();
        assert_eq!(
            btc.balance.free,
            d("9"),
            "base balance must decrease by the quantity alone"
        );

        // Quote balance: 0 + 100 - 0.1 = 99.9, so the fee charged is the fee reported
        let usdt = venue.account.balance_mut(&quote()).unwrap();
        assert_eq!(
            usdt.balance.free,
            d("99.9"),
            "quote balance must rise by the proceeds less the fee"
        );
    }

    /// A spot fill exchanges the two assets: a round trip gives back the base it bought, and the
    /// quote moves by the price difference less both fees, which is what the engine books as
    /// realised PnL. Before a spot fill credited what it received, the base never arrived and the
    /// sell's proceeds never left.
    #[test]
    fn a_spot_round_trip_returns_the_base_and_moves_quote_by_pnl_less_fees() {
        // 0.1% fee rate
        let fee_model = FeeModelConfig::Percentage(PercentageFeeModel::new(d("0.001")));
        let mut venue = make_venue_with_fee("0", "1000", fee_model);

        let buy = venue.open_order(buy_request("1", market_prices("100")));
        // 1000 - (100 + 0.1 fee)
        assert_eq!(
            filled_balance(&buy).balance,
            Balance::new(d("899.9"), d("899.9"))
        );
        assert_eq!(filled_received(&buy).balance, Balance::new(d("1"), d("1")));

        let sell = venue.open_order(sell_request("1", market_prices("110")));
        assert_eq!(filled_balance(&sell).balance, Balance::new(d("0"), d("0")));
        // 899.9 + (110 - 0.11 fee)
        assert_eq!(
            filled_received(&sell).balance,
            Balance::new(d("1009.79"), d("1009.79"))
        );

        let fees = filled_trade(&buy).fees.fees + filled_trade(&sell).fees.fees;
        assert_eq!(
            d("1009.79") - d("1000"),
            d("10") - fees,
            "quote moves by the realised PnL less the fees the trades report"
        );
    }

    /// The asset a fill receives is created at zero if the account never held it, so a backtest
    /// funds only what its first order pays with.
    #[test]
    fn a_buy_creates_the_base_balance_the_account_never_held() {
        let mut venue = SimulatedVenue::new(
            &config_from_balances(vec![funded(quote(), d("1000"))], FeeModelConfig::default()),
            spot_instruments(),
        );

        let buy = venue.open_order(buy_request("2", market_prices("100")));
        let received = filled_received(&buy);
        assert_eq!(received.asset, base());
        assert_eq!(received.balance, Balance::new(d("2"), d("2")));

        let sell = venue.open_order(sell_request("2", market_prices("100")));
        assert!(
            sell.response.state.is_accepted(),
            "the base the buy received can be sold: {:?}",
            sell.response.state
        );
        assert_eq!(filled_balance(&sell).balance, Balance::new(d("0"), d("0")));
        assert_eq!(
            filled_received(&sell).balance,
            Balance::new(d("1000"), d("1000"))
        );
    }

    /// A per-unit commission, as a broker charges on shares, is a quote amount, so a sell pays it
    /// out of its proceeds rather than in base converted at the price.
    #[test]
    fn a_per_unit_commission_on_a_spot_sell_comes_out_of_the_proceeds() {
        let fee_model = FeeModelConfig::PerContract(PerContractFeeModel {
            commission_per_contract: d("0.5"),
        });
        let mut venue = make_venue_with_fee("10", "0", fee_model);

        let sell = venue.open_order(sell_request("2", market_prices("100")));

        assert_eq!(filled_trade(&sell).fees.fees, d("1"));
        assert_eq!(filled_balance(&sell).balance, Balance::new(d("8"), d("8")));
        assert_eq!(
            filled_received(&sell).balance,
            Balance::new(d("199"), d("199"))
        );
    }

    /// A sell whose fee exceeds its proceeds takes the excess from quote, and is refused with
    /// nothing moved when quote cannot cover it.
    #[test]
    fn a_sell_whose_fee_exceeds_its_proceeds_needs_the_excess_in_quote() {
        let fee_model = FeeModelConfig::PerContract(PerContractFeeModel {
            commission_per_contract: d("2"),
        });

        // Proceeds 1 * 1 = 1, fee 2: the sell owes 1 quote on top of the base it delivers.
        let mut short_of_quote = make_venue_with_fee("10", "0", fee_model);
        let refused = short_of_quote.open_order(sell_request("1", market_prices("1")));
        match refused.response.state {
            OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
                ApiError::BalanceInsufficient(Some(asset), _),
            ))) => assert_eq!(asset, quote(), "the asset short is quote, not base"),
            other => panic!("expected BalanceInsufficient, got: {other:?}"),
        }
        assert!(refused.events.is_empty(), "a refusal moves nothing");
        assert_eq!(
            short_of_quote.account.balance_mut(&base()).unwrap().balance,
            Balance::new(d("10"), d("10"))
        );

        let mut covered = make_venue_with_fee("10", "5", fee_model);
        let filled = covered.open_order(sell_request("1", market_prices("1")));
        assert_eq!(
            filled_balance(&filled).balance,
            Balance::new(d("9"), d("9"))
        );
        assert_eq!(
            filled_received(&filled).balance,
            Balance::new(d("4"), d("4"))
        );
    }

    /// The same sell resting: its hold is the base it delivers, so when it crosses with quote
    /// unable to cover the excess fee it is cancelled, releasing the base, rather than filled.
    #[test]
    fn a_resting_sell_whose_fee_exceeds_its_proceeds_is_cancelled_when_quote_cannot_cover() {
        let fee_model = FeeModelConfig::PerContract(PerContractFeeModel {
            commission_per_contract: d("2"),
        });
        let mut venue = make_market_venue_with("10", "0", fee_model, SimFillConfig::default());
        advance(&mut venue, time(1));
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(book("0.5", "0.6")),
                    time(1)
                )
                .is_empty()
        );

        let rested = venue.open_order(limit_request("s", Side::Sell, "1", "1", gtc()));
        assert_eq!(rested.events.len(), 1, "a 0.5 bid does not reach 1");
        assert_eq!(
            balance_of(&rested.events[0]).balance,
            Balance::new(d("10"), d("9"))
        );

        advance(&mut venue, time(2));
        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("1.1", "1.2")),
            time(2),
        );

        let [released, cancelled] = events.as_slice() else {
            panic!("expected the released hold, then the cancel: {events:?}");
        };
        assert_eq!(balance_of(released).balance, Balance::new(d("10"), d("10")));
        assert!(
            matches!(
                order_of(cancelled).state,
                OrderState::Inactive(InactiveOrderState::Cancelled(_))
            ),
            "{:?}",
            order_of(cancelled).state
        );
        assert!(venue.trades(time(0)).is_empty(), "nothing traded");
    }

    /// When quote can cover the excess fee, the same resting sell fills: its base hold is released
    /// and the fill settled afresh, still restating each asset once.
    #[test]
    fn a_resting_sell_whose_fee_exceeds_its_proceeds_fills_when_quote_covers_it() {
        let fee_model = FeeModelConfig::PerContract(PerContractFeeModel {
            commission_per_contract: d("2"),
        });
        let mut venue = make_market_venue_with("10", "5", fee_model, SimFillConfig::default());
        advance(&mut venue, time(1));
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(book("0.5", "0.6")),
                    time(1)
                )
                .is_empty()
        );
        let rested = venue.open_order(limit_request("s", Side::Sell, "1", "1", gtc()));
        assert_eq!(rested.events.len(), 1, "a 0.5 bid does not reach 1");

        advance(&mut venue, time(2));
        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("1.1", "1.2")),
            time(2),
        );

        assert_eq!(
            events.len(),
            4,
            "the base paid, the quote received, the trade, then the terminal order"
        );
        assert_eq!(balance_of(&events[0]).balance, Balance::new(d("9"), d("9")));
        // 5 + proceeds of 1 - the fee of 2.
        assert_eq!(balance_of(&events[1]).balance, Balance::new(d("4"), d("4")));
        assert_eq!(trade_of(&events[2]).fees.fees, d("2"));
        assert!(
            matches!(
                order_of(&events[3]).state,
                OrderState::Inactive(InactiveOrderState::FullyFilled(_))
            ),
            "{:?}",
            order_of(&events[3]).state
        );
    }

    // --- SpotFeeAsset::Received: a buy's fee comes out of the base it receives -----------------

    fn received(mut venue: SimulatedVenue) -> SimulatedVenue {
        venue.spot_fee_asset = SpotFeeAsset::Received;
        venue
    }

    /// A buy pays its notional alone, and receives its quantity less the fee converted to base at
    /// the fill price. The fill reports that base fee, with the quote fee it came from.
    #[test]
    fn received_takes_a_buys_fee_from_the_base_it_receives() {
        let fee_model = FeeModelConfig::Percentage(PercentageFeeModel::new(d("0.001")));
        let mut venue = received(make_venue_with_fee("0", "10000", fee_model));

        // Notional 10 * 100 = 1000, fee 1 quote = 0.01 base.
        let outcome = venue.open_order(buy_request("10", market_prices("100")));

        assert_eq!(
            filled_balance(&outcome).balance,
            Balance::new(d("9000"), d("9000"))
        );
        assert_eq!(filled_received(&outcome).asset, base());
        assert_eq!(
            filled_received(&outcome).balance,
            Balance::new(d("9.99"), d("9.99"))
        );
        assert_eq!(
            filled_trade(&outcome).fees,
            AssetFees::new(base(), d("0.01"), Some(d("1")))
        );
    }

    /// A sell's fee is in quote, out of its proceeds, under either rule.
    #[test]
    fn received_takes_a_sells_fee_from_its_proceeds() {
        let fee_model = FeeModelConfig::Percentage(PercentageFeeModel::new(d("0.001")));
        let mut venue = received(make_venue_with_fee("10", "0", fee_model));

        let outcome = venue.open_order(sell_request("1", market_prices("100")));

        assert_eq!(
            filled_balance(&outcome).balance,
            Balance::new(d("9"), d("9"))
        );
        assert_eq!(
            filled_received(&outcome).balance,
            Balance::new(d("99.9"), d("99.9"))
        );
        assert_eq!(
            filled_trade(&outcome).fees,
            AssetFees::new(quote(), d("0.1"), Some(d("0.1")))
        );
    }

    /// A buy whose base fee exceeds its quantity takes the excess from base, and is refused with
    /// nothing moved when base cannot cover it.
    #[test]
    fn a_received_buy_whose_fee_exceeds_its_quantity_needs_the_excess_in_base() {
        let fee_model = FeeModelConfig::PerContract(PerContractFeeModel {
            commission_per_contract: d("2"),
        });

        // Notional 1 * 1 = 1, fee 2 quote = 2 base: the buy owes 1 base on top of the 1 it receives.
        let mut short_of_base = received(make_venue_with_fee("0", "10", fee_model));
        let refused = short_of_base.open_order(buy_request("1", market_prices("1")));
        match refused.response.state {
            OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
                ApiError::BalanceInsufficient(Some(asset), _),
            ))) => assert_eq!(asset, base(), "the asset short is base, not quote"),
            other => panic!("expected BalanceInsufficient, got: {other:?}"),
        }
        assert!(refused.events.is_empty(), "a refusal moves nothing");
        assert_eq!(
            short_of_base.account.balance_mut(&quote()).unwrap().balance,
            Balance::new(d("10"), d("10"))
        );

        let mut covered = received(make_venue_with_fee("5", "10", fee_model));
        let filled = covered.open_order(buy_request("1", market_prices("1")));
        assert_eq!(
            filled_balance(&filled).balance,
            Balance::new(d("9"), d("9"))
        );
        assert_eq!(
            filled_received(&filled).balance,
            Balance::new(d("4"), d("4"))
        );
    }

    /// A resting buy holds its notional alone, since its fee comes out of the base it receives,
    /// and its fill settles exactly what it held.
    #[test]
    fn a_resting_received_buy_holds_only_its_notional() {
        let fee_model = FeeModelConfig::Percentage(PercentageFeeModel::new(d("0.001")));
        let mut venue = received(make_market_venue_with(
            "0",
            "10000",
            fee_model,
            SimFillConfig::default(),
        ));
        advance(&mut venue, time(1));
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(book("101", "102")),
                    time(1)
                )
                .is_empty()
        );

        let rested = venue.open_order(limit_request("b", Side::Buy, "10", "100", gtc()));
        assert_eq!(rested.events.len(), 1, "a 102 ask does not reach 100");
        assert_eq!(
            balance_of(&rested.events[0]).balance,
            Balance::new(d("10000"), d("9000"))
        );

        advance(&mut venue, time(2));
        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("98", "99")),
            time(2),
        );

        assert_eq!(
            events.len(),
            4,
            "the quote paid, the base received, the trade, then the terminal order"
        );
        assert_eq!(
            balance_of(&events[0]).balance,
            Balance::new(d("9000"), d("9000"))
        );
        assert_eq!(
            balance_of(&events[1]).balance,
            Balance::new(d("9.99"), d("9.99"))
        );
        assert_eq!(
            trade_of(&events[2]).fees,
            AssetFees::new(base(), d("0.01"), Some(d("1")))
        );
    }

    /// A fee cannot be converted to base at a price that is not positive, so such a buy is
    /// charged in quote, as under the default rule.
    #[test]
    fn a_received_buy_at_a_zero_price_is_charged_in_quote() {
        let fee_model = FeeModelConfig::PerContract(PerContractFeeModel {
            commission_per_contract: d("1"),
        });
        let mut venue = received(make_venue_with_fee("0", "10", fee_model));

        let outcome = venue.open_order(buy_request("1", market_prices("0")));

        assert_eq!(
            filled_balance(&outcome).balance,
            Balance::new(d("9"), d("9"))
        );
        assert_eq!(
            filled_received(&outcome).balance,
            Balance::new(d("1"), d("1"))
        );
        assert_eq!(filled_trade(&outcome).fees.asset, quote());
    }

    #[test]
    fn percentage_fee_with_zero_price_returns_zero_fee() {
        // Edge case: if fill_price is zero, fee computation must not divide by zero
        let fee_model = FeeModelConfig::Percentage(PercentageFeeModel::new(d("0.001")));
        let mut venue = make_venue_with_fee("10", "0", fee_model);

        // Sell 1 BTC at price 0 (degenerate case)
        // Fee (quote) = 0 * 0.001 * 1 = 0
        // Fee (base) = guarded by is_zero() check, returns 0
        let outcome = venue.open_order(sell_request("1", market_prices("0")));

        assert!(
            outcome.response.state.is_accepted(),
            "sell at zero price should succeed: {:?}",
            outcome.response.state
        );

        // Fee must be zero (not NaN or panic from division by zero)
        assert_eq!(
            filled_trade(&outcome).fees.fees,
            Decimal::ZERO,
            "fee must be zero when price is zero"
        );

        // Base balance: 10 - 1 = 9 (no fee deducted)
        let btc = venue.account.balance_mut(&base()).unwrap();
        assert_eq!(
            btc.balance.free,
            d("9"),
            "base balance must decrease by quantity only"
        );
    }

    /// A Market order the venue cannot price is rejected, not panicked on.
    ///
    /// A Market order has no limit price of its own to fall back on, so with no usable
    /// snapshot there is no price anywhere. This used to hit an `expect`. Because the async driver
    /// runs as a spawned task, that killed the exchange, dropped the request receiver, and turned
    /// every later order into `ExchangeOffline` -- so a backtest ran to completion over the whole
    /// dataset having filled nothing and surfaced only a `JoinError` at teardown.
    ///
    /// Both unpriceable cases are covered, because they mean different things: `None` is a caller
    /// that sampled no snapshot at all, `Some(empty)` is a cold start where one was sampled and the
    /// instrument had no price yet.
    #[test]
    fn a_market_order_that_cannot_be_priced_is_rejected_rather_than_panicking() {
        for market in [None, Some(MarketSnapshot::default())] {
            let mut venue = make_venue("10", "10000000");

            let outcome = venue.open_order(buy_request("1.0", market));

            assert!(
                outcome.events.is_empty(),
                "a rejected order must not notify a fill (market={market:?})"
            );
            assert!(
                matches!(
                    outcome.response.state,
                    OrderState::Inactive(InactiveOrderState::OpenFailed(
                        UnindexedOrderError::Rejected(_)
                    ))
                ),
                "expected a rejection, got {:?} (market={market:?})",
                outcome.response.state
            );

            let usd = venue.account.balance_mut(&quote()).unwrap();
            assert_eq!(
                usd.balance.free,
                d("10000000"),
                "a rejected order must not move the balance (market={market:?})"
            );
        }
    }

    /// A market order carrying a price, as `RequestOpen::price` documents it should not.
    fn priced_market_order(
        side: Side,
        price: &str,
        market: Option<MarketSnapshot>,
    ) -> OrderRequestOpen<ExchangeId, InstrumentNameExchange> {
        let mut request = request(instrument_name(), side, "1", market);
        request.state.price = Some(d(price));
        request
    }

    /// A price on a market order is ignored, as the live clients ignore it, so it is no fallback:
    /// with nothing to price from, the order is still unpriceable rather than filled at the price
    /// its sender happened to stamp.
    ///
    /// Both regimes can reach the fallback: a request-priced venue sent no usable snapshot, and a
    /// market-driven venue never fed the instrument.
    #[test]
    fn a_market_order_is_never_filled_at_a_price_it_carries() {
        let mut market_driven = make_market_venue("10", "10000000");
        advance(&mut market_driven, time(1));

        let cases = [
            ("request-priced", make_venue("10", "10000000"), None),
            (
                "request-priced",
                make_venue("10", "10000000"),
                Some(MarketSnapshot::default()),
            ),
            ("market-driven", market_driven, None),
        ];

        for (regime, mut venue, market) in cases {
            let outcome = venue.open_order(priced_market_order(Side::Buy, "1", market));

            assert!(
                matches!(
                    outcome.response.state,
                    OrderState::Inactive(InactiveOrderState::OpenFailed(
                        UnindexedOrderError::Rejected(ApiError::OrderRejected(_))
                    ))
                ),
                "expected the unpriceable rejection, got {:?} ({regime}, market={market:?})",
                outcome.response.state
            );
            assert!(
                outcome.events.is_empty(),
                "nothing filled ({regime}, market={market:?})"
            );
        }
    }

    /// Nor does a price on a market order bound its fill, as a limit would.
    #[test]
    fn a_market_order_is_not_clamped_by_a_price_it_carries() {
        for (side, stray) in [(Side::Buy, "90"), (Side::Sell, "110")] {
            let mut venue = make_venue("10", "10000000");
            let market = Some(MarketSnapshot {
                last_price: Some(d("100")),
                ..MarketSnapshot::default()
            });

            let outcome = venue.open_order(priced_market_order(side, stray, market));

            assert_eq!(
                filled_trade(&outcome).price,
                d("100"),
                "a {side:?} fills at the market, not clamped to its stray {stray}"
            );
        }
    }

    /// The rejection names which of the two unpriceable causes occurred, because their fixes
    /// differ: an absent snapshot is a wiring problem in the caller, an empty one is a timing
    /// problem in the data.
    #[test]
    fn an_unpriceable_rejection_distinguishes_an_absent_snapshot_from_an_empty_one() {
        let reason_of = |market| {
            let mut venue = make_venue("10", "10000000");
            match venue.open_order(buy_request("1.0", market)).response.state {
                OrderState::Inactive(InactiveOrderState::OpenFailed(
                    UnindexedOrderError::Rejected(ApiError::OrderRejected(reason)),
                )) => reason,
                other => panic!("expected an OrderRejected, got {other:?}"),
            }
        };

        assert!(
            reason_of(None).contains("no market snapshot"),
            "an absent snapshot must be named as such, got: {}",
            reason_of(None)
        );
        assert!(
            reason_of(Some(MarketSnapshot::default())).contains("no market price available yet"),
            "an empty snapshot must read as a cold start, got: {}",
            reason_of(Some(MarketSnapshot::default()))
        );
    }

    /// A Market order fills at the snapshot the request carried, and at nothing else.
    ///
    /// With the default `LastPriceFillModel` the fill price is the snapshot's `last_price`, so this
    /// pins that a market order priced purely from `RequestOpen::market` both fills and fills at
    /// the right price.
    #[test]
    fn a_market_order_fills_at_the_price_its_snapshot_carried() {
        let mut venue = make_venue("0", "10000");

        let outcome = venue.open_order(buy_request(
            "1.0",
            Some(MarketSnapshot::from_last_price(Some(d("100")))),
        ));

        let OrderState::Inactive(InactiveOrderState::FullyFilled(ref filled)) =
            outcome.response.state
        else {
            panic!("expected a filled order, got {:?}", outcome.response.state)
        };
        assert_eq!(
            filled.avg_price,
            Some(d("100")),
            "a market order must fill at its snapshot's last price"
        );
        assert_eq!(filled.filled_quantity, d("1.0"));

        assert_eq!(filled_trade(&outcome).price, d("100"));

        let usd = venue.account.balance_mut(&quote()).unwrap();
        assert_eq!(
            usd.balance.free,
            d("9900"),
            "a 1 BTC buy at 100 must debit 100 quote"
        );
    }

    /// A configured reservation is honoured, not refused.
    ///
    /// `total != free` is ordinary user configuration -- an `initial_state` copied from a live
    /// account with margin reserved. It was once an `assert_eq!` that panicked the exchange task on
    /// the first order, then a rejection, because a ledger where every order filled on arrival had
    /// no way to represent an amount held back. It has one now: the order draws on `free`, and the
    /// held amount is still held afterwards.
    #[test]
    fn a_configured_quote_reservation_survives_a_fill() {
        let mut venue = make_venue("10", "10000000");
        venue.account.balance_mut(&quote()).unwrap().balance.total = d("20000000");

        let outcome = venue.open_order(buy_request("1.0", market_prices("50000")));

        assert!(
            matches!(outcome.response.state, OrderState::Inactive(_)),
            "a market order fills on arrival, got {:?}",
            outcome.response.state
        );

        let usdt = venue.account.balance_mut(&quote()).unwrap().balance;
        assert_eq!(
            usdt.free,
            d("10000000") - d("50000"),
            "the fill draws the notional from the spendable side"
        );
        assert_eq!(
            usdt.total - usdt.free,
            d("10000000"),
            "the configured reservation must be untouched by an unrelated fill"
        );
    }

    /// The sell path debits the base asset, so the reservation must survive there too.
    #[test]
    fn a_configured_base_reservation_survives_a_fill() {
        let mut venue = make_venue("10", "10000000");
        venue.account.balance_mut(&base()).unwrap().balance.total = d("20");

        let outcome = venue.open_order(sell_request("1.0", market_prices("50000")));

        assert!(
            matches!(outcome.response.state, OrderState::Inactive(_)),
            "a market order fills on arrival, got {:?}",
            outcome.response.state
        );

        let btc = venue.account.balance_mut(&base()).unwrap().balance;
        assert_eq!(
            btc.free,
            d("10") - d("1"),
            "the fill delivers one base unit from the spendable side"
        );
        assert_eq!(
            btc.total - btc.free,
            d("10"),
            "the configured reservation must be untouched by an unrelated fill"
        );
    }

    /// An order larger than `free` is refused even when `total` would cover it.
    ///
    /// The whole point of a reservation is that the held portion is not spendable. Sizing against
    /// `total` would let one order spend what another is already holding.
    #[test]
    fn a_reservation_is_not_spendable() {
        let mut venue = make_venue("10", "100");
        // free 100, total 10_000_000: only 100 may be spent.
        venue.account.balance_mut(&quote()).unwrap().balance.total = d("10000000");

        let outcome = venue.open_order(buy_request("1.0", market_prices("50000")));

        assert!(
            matches!(
                outcome.response.state,
                OrderState::Inactive(InactiveOrderState::OpenFailed(
                    UnindexedOrderError::Rejected(ApiError::BalanceInsufficient(_, _))
                ))
            ),
            "expected an insufficient-balance rejection, got {:?}",
            outcome.response.state
        );
        assert!(
            outcome.events.is_empty(),
            "a refused order moves nothing, so it restates nothing"
        );

        let usdt = venue.account.balance_mut(&quote()).unwrap().balance;
        assert_eq!(usdt.free, d("100"), "a refused reserve must not move free");
        assert_eq!(
            usdt.total,
            d("10000000"),
            "a refused reserve must not move total"
        );
    }

    /// Orders come back in a total order, so two runs of one backtest produce one snapshot.
    ///
    /// The snapshot sorts with an *unstable* sort over a `FnvHashMap`'s values. Keyed on
    /// `instrument` alone every order on one instrument ties, leaving their relative order
    /// unspecified -- so a golden hash over the snapshot is a flake, and comparing two runs of the
    /// same backtest compares two different orderings. `cid` is unique per order, which makes the
    /// key total.
    #[test]
    fn an_account_snapshot_orders_one_instruments_orders_deterministically() {
        // Enough orders that a hash map's own iteration order is vanishingly unlikely to be sorted
        // by accident -- with three, a passing assertion would say nothing.
        const CIDS: [&str; 8] = ["h", "d", "a", "g", "c", "f", "b", "e"];

        let resting = |cid: &str| UnindexedOrder {
            key: OrderKey {
                exchange: EXCHANGE,
                instrument: instrument_name(),
                strategy: StrategyId::new("test"),
                cid: ClientOrderId::new(cid),
            },
            side: Side::Buy,
            price: Some(d("50000")),
            quantity: d("1"),
            kind: OrderKind::Limit,
            time_in_force: TimeInForce::GoodUntilCancelled { post_only: false },
            state: OrderState::active(Open {
                id: VenueOrderId::Assigned(OrderId::new(cid)),
                time_exchange: Default::default(),
                filled_quantity: Decimal::ZERO,
            }),
        };

        let mut config = spot_config("10", "10000000", FeeModelConfig::default());
        config.initial_state.instruments = vec![InstrumentAccountSnapshot {
            instrument: instrument_name(),
            orders: CIDS.into_iter().map(resting).collect(),
            orders_complete: true,
            position: PositionReport::Unreported,
            isolated: None,
        }];

        let venue = SimulatedVenue::new(&config, spot_instruments());

        let cids = venue
            .account_snapshot()
            .instruments
            .into_iter()
            .flat_map(|instrument| instrument.orders)
            .map(|order| order.key.cid)
            .collect::<Vec<_>>();

        let mut expected = CIDS.map(ClientOrderId::new).to_vec();
        expected.sort();
        assert_eq!(
            cids, expected,
            "orders on one instrument must be ordered by a key no two of them share"
        );
    }

    /// A venue seeded with orders carrying decimal ids mints its own past the highest of them, so
    /// no minted id repeats a seeded one. Anything keyed on the id alone — a position under
    /// `OmsMode::Hedging`, say — would otherwise merge the two orders.
    #[test]
    fn minted_order_ids_start_past_the_highest_decimal_id_seeded() {
        let resting = |cid: &str, id: &str| UnindexedOrder {
            key: OrderKey {
                exchange: EXCHANGE,
                instrument: instrument_name(),
                strategy: StrategyId::new("test"),
                cid: ClientOrderId::new(cid),
            },
            side: Side::Buy,
            price: Some(d("50000")),
            quantity: d("1"),
            kind: OrderKind::Limit,
            time_in_force: TimeInForce::GoodUntilCancelled { post_only: false },
            state: OrderState::active(Open {
                id: VenueOrderId::Assigned(OrderId::new(id)),
                time_exchange: Default::default(),
                filled_quantity: Decimal::ZERO,
            }),
        };

        let seeded_venue = |orders| {
            let mut config = spot_config("10", "10000000", FeeModelConfig::default());
            config.initial_state.instruments = vec![InstrumentAccountSnapshot {
                instrument: instrument_name(),
                orders,
                orders_complete: true,
                position: PositionReport::Unreported,
                isolated: None,
            }];
            SimulatedVenue::new(&config, spot_instruments())
        };

        // A non-decimal id can never equal a minted one, however it sorts.
        let mut venue = seeded_venue(vec![
            resting("a", "3"),
            resting("b", "1"),
            resting("c", "zzz"),
        ]);
        assert_eq!(venue.order_id_sequence_fetch_add(), OrderId::new("4"));
        assert_eq!(venue.order_id_sequence_fetch_add(), OrderId::new("5"));
        // Still a count of the orders this venue booked, not an id.
        assert_eq!(venue.order_sequence(), 2);

        // A seeded cancelled order's id is the venue's too, and counts the same way.
        let mut cancelled = resting("d", "9");
        cancelled.state = OrderState::inactive(Cancelled::new(
            OrderId::new("9"),
            Default::default(),
            Some(Decimal::ZERO),
        ));
        let mut venue = seeded_venue(vec![resting("a", "3"), cancelled]);
        assert_eq!(venue.order_id_sequence_fetch_add(), OrderId::new("10"));

        // With only a non-decimal id seeded, ids count from zero as they always have.
        let mut venue = seeded_venue(vec![resting("c", "zzz")]);
        assert_eq!(venue.order_id_sequence_fetch_add(), OrderId::new("0"));
    }

    /// With nothing seeded, ids count from zero as they always have.
    #[test]
    fn minted_order_ids_start_at_zero_when_nothing_is_seeded() {
        let config = spot_config("10", "10000000", FeeModelConfig::default());
        let mut venue = SimulatedVenue::new(&config, spot_instruments());

        assert_eq!(venue.order_id_sequence_fetch_add(), OrderId::new("0"));
    }

    /// A seeded `u64::MAX` leaves the next id one past it, rather than overflowing.
    #[test]
    fn a_seeded_u64_max_order_id_does_not_overflow_the_next() {
        let mut account = AccountState::try_from(
            spot_config("10", "10000000", FeeModelConfig::default()).initial_state,
        )
        .unwrap();
        let mut seeded = seeded_part_filled("48000", "1", "0");
        seeded.state.id = VenueOrderId::Assigned(OrderId::new(u64::MAX.to_string()));
        assert!(
            account.book(seeded, None).is_ok(),
            "the book is vacant under this id"
        );

        assert_eq!(first_unseeded_order_id(&account), u128::from(u64::MAX) + 1);
    }

    #[test]
    fn an_order_for_a_quantity_that_is_not_positive_is_rejected_before_the_ledger_moves() {
        for request in [
            buy_request("0", market_prices("50000")),
            sell_request("-1", market_prices("50000")),
        ] {
            let mut venue = make_venue("100", "10000000");
            let quantity = request.state.quantity;

            let outcome = venue.open_order(request);

            assert_eq!(
                rejection_reason(&outcome),
                format!(
                    "cannot open {} for {EXCHANGE}: quantity {quantity} is not positive",
                    instrument_name()
                )
            );
            assert!(outcome.events.is_empty(), "a refused order moves nothing");
            assert!(venue.trades(time(0)).is_empty(), "and nothing traded");
            assert!(venue.orders_open(&[]).is_empty(), "or rests");
            assert_eq!(free_quote(&venue), d("10000000"));
            assert_eq!(total_base(&venue), d("100"));
        }

        // Its kind is refused first: this venue holds no limit order, whatever its quantity.
        let mut venue = make_venue("100", "10000000");
        let outcome = venue.open_order(limit_request("limit", Side::Buy, "0", "50000", gtc()));
        let reason = rejection_reason(&outcome);
        assert!(
            reason.contains("does not support OrderKind::Limit"),
            "{reason}"
        );
    }

    /// A [`RequestPriced`](VenueRegime::RequestPriced) venue rejects a limit order on its kind,
    /// before any fill model is consulted.
    ///
    /// The clamp that bounds a fill by the order's own terms lives on the market-driven path, so
    /// this venue must never reach a pricing decision for an order it cannot hold. The snapshot is
    /// chosen so a lapse would be unmistakable: `MidpointFillModel` would price this buy at 50,000
    /// against a limit of 40,000 — a fill 25% above the order's own limit — so a `Filled` response
    /// here means the gate stopped holding, not merely that a rejection message changed.
    #[test]
    fn a_limit_order_is_rejected_before_a_fill_model_is_consulted() {
        let mut venue = make_venue("100", "10000000");
        venue.fill_model = Arc::new(SimFillConfig::Midpoint(crate::fill::MidpointFillModel));

        let mut request = buy_request("1", market_prices("50000"));
        request.state.kind = OrderKind::Limit;
        request.state.price = Some(d("40000"));

        let outcome = venue.open_order(request);

        assert!(
            outcome.events.is_empty(),
            "a rejected order moves no balance and books no trade"
        );
        match outcome.response.state {
            OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
                ApiError::OrderRejected(ref reason),
            ))) => assert!(
                reason.contains("does not support OrderKind::Limit"),
                "the rejection must name the unsupported kind, got: {reason}"
            ),
            other => panic!("a limit order must be rejected by kind, got: {other:?}"),
        }
    }

    // --- Stage 3b: limit orders -------------------------------------------------------------

    /// The regime gate, and the reason it exists: a venue with no feed could never match a resting
    /// order, so accepting one would be accepted-and-silently-never-filled.
    #[test]
    fn a_request_priced_venue_rejects_a_limit_order_and_says_what_would_accept_one() {
        let mut venue = make_venue("10", "1000000");
        assert_eq!(venue.regime(), VenueRegime::RequestPriced);

        let outcome = venue.open_order(limit_request("a", Side::Buy, "1", "48000", gtc()));

        assert!(
            outcome.events.is_empty(),
            "a rejected order moves no balance"
        );
        match outcome.response.state {
            OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
                ApiError::OrderRejected(ref reason),
            ))) => {
                assert!(
                    reason.contains("new_market_driven"),
                    "the rejection must name the constructor that would accept it, got: {reason}"
                );
            }
            ref other => panic!("a limit order must be rejected by the regime, got: {other:?}"),
        }
    }

    /// A limit order that the market has not reached rests, and the venue holds exactly what its
    /// fill will cost — no more, so no release-and-re-debit is ever needed.
    #[test]
    fn a_limit_order_that_does_not_cross_rests_and_reserves_what_its_fill_will_cost() {
        let (venue, rested) = venue_resting_one_buy("48000");

        // 48000 notional + 2bp maker fee on it.
        let reserved = d("48009.6");

        let balance = venue.balances(&[quote()]).remove(0);
        assert_eq!(
            balance.balance.total,
            d("1000000"),
            "resting an order spends nothing: `total` moves only on a fill"
        );
        assert_eq!(
            balance.balance.free,
            d("1000000") - reserved,
            "`free` falls by the notional plus the MAKER fee the fill will charge"
        );
        assert_eq!(
            balance.balance.used(),
            reserved,
            "the held portion is what a client sees as committed to the order"
        );

        assert_eq!(
            rested_open(&rested).filled_quantity,
            Decimal::ZERO,
            "the client is told an order is working with none of its quantity done"
        );

        let open = venue
            .orders_open(&[instrument_name()])
            .pop()
            .expect("the order is on the book");
        assert_eq!(open.price, Some(d("48000")));
        assert_eq!(
            open.state,
            *rested_open(&rested),
            "the book and the response describe the same order"
        );
    }

    /// A resting order is the passive side, so it is paid the price it quoted. Price improvement
    /// accrues to the aggressor that crossed it, never to the maker.
    #[test]
    fn a_resting_order_fills_at_its_own_limit_and_is_never_improved_by_the_book() {
        let (mut venue, _) = venue_resting_one_buy("48000");
        advance(&mut venue, time(2));

        // Straight through the limit: the offer is 100 better than the order asked for.
        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("47800", "47900")),
            time(2),
        );

        assert_eq!(
            events.len(),
            4,
            "one filled spot order owes two balances, a trade and a terminal order snapshot"
        );

        let trade = trade_of(&events[2]);
        assert_eq!(
            trade.price,
            d("48000"),
            "a resting order fills at its own limit; 47900 would credit it improvement no maker \
             can obtain"
        );
        assert_eq!(
            trade.fees.fees,
            d("9.6"),
            "2bp MAKER on 48000, not 10bp taker: the resting side supplied liquidity"
        );

        assert_eq!(
            filled_price(order_of(&events[3])),
            d("48000"),
            "the terminal snapshot reports the same price as the trade"
        );
    }

    /// The trade precedes the terminal order snapshot, which is not merely cosmetic: a consumer
    /// routing a fill to a position needs the order still to be live when the trade arrives.
    #[test]
    fn a_resting_fill_reports_its_trade_before_the_order_that_produced_it() {
        let (mut venue, _) = venue_resting_one_buy("48000");
        advance(&mut venue, time(2));

        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("47800", "47900")),
            time(2),
        );

        assert_eq!(
            balance_of(&events[0]).asset,
            quote(),
            "the balance the fill paid with comes first"
        );
        assert_eq!(
            balance_of(&events[1]).asset,
            base(),
            "then the balance it received"
        );
        assert!(
            matches!(events[2].kind, AccountEventKind::Trade(_)),
            "then the trade, got: {:?}",
            events[2].kind
        );
        assert!(
            matches!(events[3].kind, AccountEventKind::OrderSnapshot(_)),
            "and only then the order it terminated, got: {:?}",
            events[3].kind
        );
    }

    /// A completed order is reported as `Inactive(FullyFilled)` rather than as an `Open` carrying a
    /// complete fill. Both denote the same fact; only this one can carry the price it filled at.
    #[test]
    fn a_resting_fill_reports_its_order_as_terminal_rather_than_as_a_complete_open() {
        let (mut venue, _) = venue_resting_one_buy("48000");
        advance(&mut venue, time(2));

        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("47800", "47900")),
            time(2),
        );

        assert!(
            matches!(
                order_of(&events[3]).state,
                OrderState::Inactive(InactiveOrderState::FullyFilled(_))
            ),
            "got: {:?}",
            order_of(&events[3]).state
        );
        assert!(
            venue.orders_open(&[]).is_empty(),
            "a filled order leaves the book"
        );
    }

    /// Reserve exactly what will be settled: the client sees one restatement per asset a fill
    /// moves, and never a balance the account did not hold.
    #[test]
    fn a_resting_order_settles_exactly_what_it_reserved() {
        let (mut venue, _) = venue_resting_one_buy("48000");
        advance(&mut venue, time(2));

        let reserved = d("48009.6");
        let free_while_resting = venue.balances(&[quote()]).remove(0).balance.free;

        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("47800", "47900")),
            time(2),
        );

        let balance = balance_of(&events[0]);
        assert_eq!(
            balance.balance.total,
            d("1000000") - reserved,
            "`total` falls by exactly what was held"
        );
        assert_eq!(
            balance.balance.free, free_while_resting,
            "`free` was already reduced when the order rested, so the fill does not move it again"
        );
        assert_eq!(
            balance.balance.used(),
            Decimal::ZERO,
            "nothing is held any more: the order that held it is gone"
        );
    }

    // --- An order trades only what is left of it ---------------------------------------------

    /// An open buy at `price` that reached the book with `filled` of `quantity` already done, as a
    /// configured `initial_state` copied from a live account may seed one.
    fn seeded_part_filled(price: &str, quantity: &str, filled: &str) -> OpenOrder {
        as_open(Order {
            key: OrderKey {
                exchange: EXCHANGE,
                instrument: instrument_name(),
                strategy: StrategyId::new("test"),
                cid: ClientOrderId::new("part_filled"),
            },
            side: Side::Buy,
            price: Some(d(price)),
            quantity: d(quantity),
            kind: OrderKind::Limit,
            time_in_force: gtc(),
            state: OrderState::active(Open::new(
                VenueOrderId::Assigned(OrderId::new("part_filled")),
                time(1),
                d(filled),
            )),
        })
        .expect("the seeded order is Open")
    }

    /// A seeded order holds nothing, so an account that cannot pay for its fill is a mis-specified
    /// fixture, and the venue says so rather than cancelling the order as unaffordable.
    #[test]
    #[should_panic(expected = "cannot afford the fill of resting order part_filled")]
    fn a_seeded_order_the_account_cannot_afford_panics_when_it_fills() {
        let mut venue = make_market_venue("10", "100");
        advance(&mut venue, time(1));
        assert!(
            venue
                .account
                .book(seeded_part_filled("48000", "1", "0"), None)
                .is_ok()
        );

        advance(&mut venue, time(2));
        let _ = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("47800", "47900")),
            time(2),
        );
    }

    /// An order that reached the book part-filled trades only the rest of it.
    ///
    /// Settling and printing its whole quantity would charge the ledger a second time for a
    /// portion that traded before this venue ever held the order, and report a trade of a size
    /// that never happened. The two readings are far enough apart to be unmistakable: the whole
    /// order costs 48,009.6 of quote and its remainder 28,805.76.
    #[test]
    fn a_part_filled_order_on_the_book_settles_and_prints_only_its_remainder() {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(1));

        assert!(
            venue
                .account
                .book(
                    seeded_part_filled("48000", "1", "0.4"),
                    // As `initial_state` seeds one: the venue never took anything for it.
                    None,
                )
                .is_ok(),
            "the book is vacant under this id"
        );

        advance(&mut venue, time(2));
        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("47800", "47900")),
            time(2),
        );

        assert_eq!(
            events.len(),
            4,
            "one filled spot order owes two balances, a trade and a terminal order snapshot"
        );

        let trade = trade_of(&events[2]);
        assert_eq!(
            trade.quantity,
            d("0.6"),
            "0.6 is what was left to trade; printing 1 would report a fill that did not happen"
        );
        assert_eq!(
            trade.fees.fees,
            d("5.76"),
            "2bp maker on 0.6 at 48000, not on the whole quantity"
        );
        assert_eq!(
            trade.order_filled_quantity,
            Some(d("1")),
            "the order's cumulative is the 0.4 it arrived with plus the 0.6 this cross traded"
        );

        assert_eq!(
            balance_of(&events[0]).balance.total,
            d("1000000") - d("28805.76"),
            "the fill costs what the remainder costs; 48009.6 would pay a second time for the 0.4 \
             that traded elsewhere"
        );
    }

    /// A fill that completes a part-filled order reports no average price.
    ///
    /// This venue struck one of the two fills behind it and never saw the other, so the limit it
    /// filled at is this fill's price rather than the mean of both — and
    /// [`Filled::avg_price`](crate::order::state::Filled::avg_price) is optional for exactly that.
    /// A consumer needing the mean has the trades to compute it from. An order that reached the
    /// book with nothing done still reports the price it filled at, which
    /// `a_resting_order_fills_at_its_own_limit_and_is_never_improved_by_the_book` pins.
    #[test]
    fn a_fill_completing_a_part_filled_order_reports_no_average_price() {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(1));

        assert!(
            venue
                .account
                .book(seeded_part_filled("48000", "1", "0.4"), None)
                .is_ok(),
            "the book is vacant under this id"
        );

        advance(&mut venue, time(2));
        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("47800", "47900")),
            time(2),
        );

        let filled = match &order_of(&events[3]).state {
            OrderState::Inactive(InactiveOrderState::FullyFilled(filled)) => filled,
            other => panic!("expected a fully filled order, got: {other:?}"),
        };

        assert_eq!(
            filled.filled_quantity,
            d("1"),
            "the order has now done its whole quantity, which is what this field reports"
        );
        assert_eq!(
            filled.avg_price, None,
            "48000 is one of the two prices behind that quantity, not their mean"
        );
    }

    /// Resting the remainder of a part-filled order holds what is left of it, and the cross that
    /// completes it settles exactly that.
    ///
    /// `rest_order` is reached directly because nothing routes a part-filled order to it yet: this
    /// venue caps no fill, so an order that aggresses on arrival fills in full and never rests a
    /// remainder. The arithmetic is pinned all the same, because the two halves have to agree —
    /// holding against the whole quantity would reserve balance for a portion that has already
    /// settled, and the fill that released it would then settle less than was held.
    #[test]
    fn resting_a_part_filled_order_reserves_and_settles_exactly_its_remainder() {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(1));

        let terms = venue
            .instrument_terms(&instrument_name())
            .expect("the spot fixture is priceable");

        let (response, notifications) = venue.rest_order(
            limit_request("part_filled", Side::Buy, "1", "48000", gtc()),
            d("48000"),
            &terms,
            d("0.4"),
        );

        match &response.state {
            OrderState::Active(ActiveOrderState::Open(open)) => assert_eq!(
                open.filled_quantity,
                d("0.4"),
                "the order rests carrying what it has already done"
            ),
            other => panic!("expected a resting open order, got: {other:?}"),
        }

        match notifications {
            Some(OpenOrderNotifications::Rested { balance, .. }) => assert_eq!(
                balance.0.balance.free,
                d("1000000") - d("28805.76"),
                "0.6 at 48000 plus 2bp maker is held; 48009.6 would hold against the 0.4 that has \
                 already settled"
            ),
            other => panic!("a rested order restates one balance, got: {other:?}"),
        }

        advance(&mut venue, time(2));
        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("47800", "47900")),
            time(2),
        );

        assert_eq!(events.len(), 4);
        assert_eq!(
            trade_of(&events[2]).quantity,
            d("0.6"),
            "the cross prints the remainder that was held for"
        );
        assert_eq!(
            balance_of(&events[0]).balance.total,
            d("1000000") - d("28805.76"),
            "and settles exactly that: one restatement, with nothing left over to release"
        );
        assert_eq!(
            balance_of(&events[0]).balance.used(),
            Decimal::ZERO,
            "nothing is held any more: the order that held it is gone"
        );
    }

    /// Which of the three ways to aggress an order's terms asked for.
    ///
    /// Asserted on [`Disposition`] directly because nothing observable separates them yet: this
    /// venue caps no fill, so every arm below fills in full and leaves no remainder to dispose of.
    /// What an order asked for is a property of the order rather than of what the book held, and a
    /// size cap is what would make the difference visible — fill-or-kill refusing the partial fill
    /// immediate-or-cancel accepts, and a good-until-cancelled limit resting what neither keeps.
    #[test]
    fn a_marketable_order_aggresses_the_way_its_own_terms_asked_for() {
        let now = time(1);
        let gtd = TimeInForce::GoodTillDate { expiry: time(9) };

        assert_eq!(
            disposition(OrderKind::Limit, gtc(), true, now),
            Disposition::FillAndRest,
            "a limit order with somewhere to wait keeps whatever it could not fill"
        );
        assert_eq!(
            disposition(OrderKind::Limit, gtd, true, now),
            Disposition::FillAndRest,
            "a deadline it has not reached is still somewhere to wait"
        );
        assert_eq!(
            disposition(OrderKind::Limit, TimeInForce::ImmediateOrCancel, true, now),
            Disposition::FillAndCancel,
            "immediate-or-cancel asked not to wait"
        );
        assert_eq!(
            disposition(OrderKind::Limit, TimeInForce::FillOrKill, true, now),
            Disposition::FillOrNothing,
            "fill-or-kill would rather trade nothing than trade in part"
        );
        assert_eq!(
            disposition(OrderKind::Market, gtc(), true, now),
            Disposition::FillAndCancel,
            "an order carrying no limit price has nothing to wait at, whatever its time in force"
        );
        assert_eq!(
            disposition(OrderKind::Market, gtd, true, now),
            Disposition::FillAndCancel,
            "including one whose deadline is still ahead of it"
        );
        assert_eq!(
            disposition(OrderKind::Market, TimeInForce::FillOrKill, true, now),
            Disposition::FillOrNothing,
            "and all-or-nothing stays all-or-nothing whatever the kind"
        );
    }

    /// A limit order the market has already reached is the aggressor, so it takes the book's price
    /// bounded by its own limit, and pays the taker rate.
    #[test]
    fn a_marketable_limit_order_fills_on_arrival_at_the_book_bounded_by_its_limit() {
        let mut venue = make_market_venue_with(
            "10",
            "1000000",
            maker_taker_fee(),
            SimFillConfig::BidAsk(BidAskFillModel),
        );
        advance(&mut venue, time(1));
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(book("47800", "47900")),
                    time(1)
                )
                .is_empty()
        );

        // Willing to pay 48000; the offer is 47900, so it prints at the offer.
        let outcome = venue.open_order(limit_request("taker", Side::Buy, "1", "48000", gtc()));

        assert_eq!(
            outcome.events.len(),
            3,
            "a filled open owes both balances, then the trade"
        );
        let trade = filled_trade(&outcome);
        assert_eq!(
            trade.price,
            d("47900"),
            "the aggressor takes the offer, which is better than its limit"
        );
        assert_eq!(
            trade.fees.fees,
            d("47.9"),
            "10bp TAKER on 47900: it crossed the spread rather than resting"
        );
        assert!(
            venue.orders_open(&[]).is_empty(),
            "it filled on arrival, so it never rested"
        );
    }

    /// The clamp, on the **default** fill model. Marketability is judged on the book while the
    /// price comes from the model, and the two are separate readings of a sampled snapshot — so the
    /// model can return a price the order never agreed to pay. The order's own terms bound it.
    ///
    /// A clamp against [`MidpointFillModel`] or [`BidAskFillModel`] would be vacuous: both derive
    /// the price from the very side of the book that decided the order was marketable, so neither
    /// can exceed the limit that side already crossed.
    #[test]
    fn a_marketable_limit_order_never_fills_worse_than_its_limit() {
        let mut venue = make_market_venue_with(
            "10",
            "1000000",
            FeeModelConfig::default(),
            // `LastPriceFillModel`, which reads `last_price` and never consults the book.
            SimFillConfig::default(),
        );
        advance(&mut venue, time(1));

        // The offer is inside the limit, so the order is marketable -- but the trade price the
        // model reads is well above it.
        let stale = MarketSnapshot {
            best_bid: Some(d("46900")),
            best_ask: Some(d("47000")),
            last_price: Some(d("48000")),
        };
        assert!(
            venue
                .apply_market(&instrument_name(), MarketObservation::new(stale), time(1))
                .is_empty()
        );

        let outcome = venue.open_order(limit_request("clamped", Side::Buy, "1", "47100", gtc()));

        assert_eq!(
            filled_trade(&outcome).price,
            d("47100"),
            "the model priced it at 48000, which the order never agreed to pay"
        );
    }

    /// The two pricing rules are different rules, and this is the one point at which they must give
    /// the same answer. If they diverge here, one of them is wrong.
    #[test]
    fn the_two_pricing_rules_agree_where_the_book_meets_the_limit() {
        let limit = "48000";
        let touching = || book("47900", "48000");

        // Rule 1: marketable on arrival. The book is already at the limit when the order arrives.
        let mut aggressor = make_market_venue_with(
            "10",
            "1000000",
            maker_taker_fee(),
            SimFillConfig::BidAsk(BidAskFillModel),
        );
        advance(&mut aggressor, time(1));
        assert!(
            aggressor
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(touching()),
                    time(1)
                )
                .is_empty()
        );
        let on_arrival = aggressor.open_order(limit_request("a", Side::Buy, "1", limit, gtc()));
        let arrival_price = filled_trade(&on_arrival).price;

        // Rule 2: rested first, crossed later by a book that reaches exactly the same price.
        let mut maker = make_market_venue_with(
            "10",
            "1000000",
            maker_taker_fee(),
            SimFillConfig::BidAsk(BidAskFillModel),
        );
        advance(&mut maker, time(1));
        assert!(
            maker
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(book("49000", "49100")),
                    time(1)
                )
                .is_empty()
        );
        let rested = maker.open_order(limit_request("b", Side::Buy, "1", limit, gtc()));
        assert_eq!(rested.events.len(), 1, "it rested rather than filling");
        advance(&mut maker, time(2));
        let resting_events = maker.apply_market(
            &instrument_name(),
            MarketObservation::new(touching()),
            time(2),
        );
        let resting_price = trade_of(&resting_events[2]).price;

        assert_eq!(
            arrival_price,
            d(limit),
            "an order arriving when the book is at its limit fills at the limit"
        );
        assert_eq!(
            resting_price, arrival_price,
            "the two pricing rules must agree exactly at the crossing point; they may differ only \
             where the order genuinely is, or is not, marketable"
        );
    }

    /// Matching takes orders in the order the book holds them and stops at the first that does not
    /// cross — not at the first it happens to iterate over.
    #[test]
    fn matching_fills_in_price_time_order_and_stops_at_the_first_order_that_does_not_cross() {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(1));
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(book("49000", "49100")),
                    time(1)
                )
                .is_empty()
        );

        // Best bid last, to prove the fill order is the book's rather than the insertion order.
        for (cid, price) in [("worst", "47000"), ("mid", "48000"), ("best", "48500")] {
            let outcome = venue.open_order(limit_request(cid, Side::Buy, "1", price, gtc()));
            assert_eq!(outcome.events.len(), 1, "{cid} must rest");
        }

        advance(&mut venue, time(2));
        // Crosses `best` and `mid`, leaves `worst` alone.
        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("47900", "48000")),
            time(2),
        );

        let filled: Vec<_> = events
            .iter()
            .filter_map(|event| match &event.kind {
                AccountEventKind::Trade(trade) => Some(trade.price),
                _ => None,
            })
            .collect();

        assert_eq!(
            filled,
            vec![d("48500"), d("48000")],
            "best bid first, and each at its own limit"
        );
        assert_eq!(
            venue
                .orders_open(&[])
                .into_iter()
                .map(|order| order.key.cid)
                .collect::<Vec<_>>(),
            vec![ClientOrderId::new("worst")],
            "the order the market did not reach is untouched"
        );
    }

    /// A trades-only feed has no book at all, so marketability falls back to the trade price. A
    /// book-only rule would never match anything on such a feed.
    #[test]
    fn a_feed_with_no_book_matches_on_the_trade_price() {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(1));
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(traded("49000")),
                    time(1)
                )
                .is_empty()
        );

        let outcome = venue.open_order(limit_request("t", Side::Buy, "1", "48000", gtc()));
        assert_eq!(outcome.events.len(), 1, "49000 traded does not reach 48000");

        advance(&mut venue, time(2));
        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(traded("47500")),
            time(2),
        );

        assert_eq!(events.len(), 4, "a print through the limit fills it");
        assert_eq!(trade_of(&events[2]).price, d("48000"));
    }

    /// A price between the two sides of a book crosses neither, so a supplied book is never
    /// second-guessed by `last_price`.
    #[test]
    fn a_price_inside_the_spread_does_not_cross_a_resting_order() {
        let (mut venue, _) = venue_resting_one_buy("48000");
        advance(&mut venue, time(2));

        // The microprice sits inside the spread and below the limit; the offer does not.
        let inside = MarketSnapshot {
            best_bid: Some(d("47900")),
            best_ask: Some(d("48100")),
            last_price: Some(d("47950")),
        };

        assert!(
            venue
                .apply_market(&instrument_name(), MarketObservation::new(inside), time(2))
                .is_empty(),
            "the offer is 48100, so a 48000 bid is not crossed however the trade price reads"
        );
        assert_eq!(
            venue.orders_open(&[]).len(),
            1,
            "the order is still resting"
        );
    }

    /// A sell rests against the bid, pays with base, and settles the base it committed.
    #[test]
    fn a_resting_sell_reserves_base_and_settles_it() {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(1));
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(book("47000", "47100")),
                    time(1)
                )
                .is_empty()
        );

        let outcome = venue.open_order(limit_request("s", Side::Sell, "1", "48000", gtc()));
        assert_eq!(outcome.events.len(), 1, "47000 bid does not reach 48000");
        assert_eq!(
            balance_of(&outcome.events[0]).asset,
            base(),
            "a spot sell delivers the base asset, so that is what is held"
        );

        advance(&mut venue, time(2));
        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("48100", "48200")),
            time(2),
        );

        assert_eq!(trade_of(&events[2]).price, d("48000"), "at its own limit");
        let balance = balance_of(&events[0]);
        assert_eq!(balance.asset, base());
        // 1 BTC delivered, and nothing more: the fee is charged in quote.
        assert_eq!(balance.balance.total, d("10") - d("1"));
        let received = balance_of(&events[1]);
        assert_eq!(received.asset, quote());
        // 1 BTC at its 48000 limit, less the 2bp maker fee of 9.6.
        assert_eq!(received.balance.total, d("1000000") + d("48000") - d("9.6"));
    }

    /// A maker rebate is a negative fee, so the amount held is less than the notional and settling
    /// it leaves more behind than the notional alone would.
    #[test]
    fn a_maker_rebate_is_held_and_settled_as_a_smaller_amount_than_the_notional() {
        let rebate =
            FeeModelConfig::Percentage(PercentageFeeModel::maker_taker(d("-0.0001"), d("0.001")));
        let mut venue = make_market_venue_with("10", "1000000", rebate, SimFillConfig::default());
        advance(&mut venue, time(1));
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(book("49000", "49100")),
                    time(1)
                )
                .is_empty()
        );

        let outcome = venue.open_order(limit_request("r", Side::Buy, "1", "48000", gtc()));

        // 48000 notional less a 1bp rebate on it.
        let held = d("48000") - d("4.8");
        assert_eq!(
            balance_of(&outcome.events[0]).balance.used(),
            held,
            "a rebate means less is held than the notional"
        );

        advance(&mut venue, time(2));
        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("47800", "47900")),
            time(2),
        );

        assert_eq!(
            balance_of(&events[0]).balance.total,
            d("1000000") - held,
            "and exactly that less is settled, so the rebate is kept"
        );
        assert_eq!(trade_of(&events[2]).fees.fees, d("-4.8"));
    }

    /// An order the account cannot afford never reaches the book, and the ledger is untouched.
    #[test]
    fn a_limit_order_that_cannot_be_afforded_is_rejected_without_resting() {
        let mut venue = make_market_venue("10", "1000");
        advance(&mut venue, time(1));
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(book("49000", "49100")),
                    time(1)
                )
                .is_empty()
        );

        let outcome = venue.open_order(limit_request("poor", Side::Buy, "1", "48000", gtc()));

        assert!(
            outcome.events.is_empty(),
            "a refused reservation moves nothing"
        );
        assert!(matches!(
            outcome.response.state,
            OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
                ApiError::BalanceInsufficient(..)
            )))
        ));
        assert!(venue.orders_open(&[]).is_empty(), "it never rested");
        assert_eq!(
            venue.balances(&[quote()]).remove(0).balance.free,
            d("1000"),
            "the ledger is left exactly as it was"
        );
    }

    // --- Stage 3b: cancel -------------------------------------------------------------------

    /// Cancelling gives the held balance back and reports the quantity done, which this venue can
    /// only ever report as zero because it models no partial fills.
    #[test]
    fn a_cancel_releases_the_reservation_and_restates_the_balance() {
        let (mut venue, _) = venue_resting_one_buy("48000");
        advance(&mut venue, time(2));

        let outcome = venue.cancel_order(OrderEvent {
            key: OrderKey {
                exchange: EXCHANGE,
                instrument: instrument_name(),
                strategy: StrategyId::new("test"),
                cid: ClientOrderId::new("resting"),
            },
            state: RequestCancel { id: None },
        });

        assert_eq!(outcome.events.len(), 1, "a cancel restates one balance");
        let balance = balance_of(&outcome.events[0]);
        assert_eq!(
            balance.balance.free,
            d("1000000"),
            "everything held against the order is spendable again"
        );
        assert_eq!(
            balance.balance.total,
            d("1000000"),
            "nothing ever left the account, so `total` never moved"
        );

        let cancelled = outcome.response.state.expect("the order was on the book");
        assert_eq!(cancelled.filled_quantity, Some(Decimal::ZERO));
        assert_eq!(cancelled.time_exchange, time(2));
        assert!(venue.orders_open(&[]).is_empty());
    }

    /// The cancel-vs-fill race, which a non-zero `to_venue` latency makes reachable. The caller is
    /// told to reconcile against the fill rather than to retry.
    #[test]
    fn a_cancel_that_loses_the_race_to_its_own_fill_reports_the_fill() {
        let (mut venue, _) = venue_resting_one_buy("48000");
        advance(&mut venue, time(2));
        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("47800", "47900")),
            time(2),
        );
        assert_eq!(events.len(), 4, "the order filled first");

        let outcome = venue.cancel_order(OrderEvent {
            key: OrderKey {
                exchange: EXCHANGE,
                instrument: instrument_name(),
                strategy: StrategyId::new("test"),
                cid: ClientOrderId::new("resting"),
            },
            state: RequestCancel { id: None },
        });

        assert!(outcome.events.is_empty(), "a failed cancel moves nothing");
        assert!(
            matches!(
                outcome.response.state,
                Err(OrderError::Rejected(ApiError::OrderAlreadyFullyFilled))
            ),
            "got: {:?}",
            outcome.response.state
        );
    }

    /// A second cancel is a state conflict rather than an unknown order, and says so.
    #[test]
    fn a_second_cancel_reports_the_order_as_already_cancelled() {
        let (mut venue, _) = venue_resting_one_buy("48000");
        let cancel = || OrderEvent {
            key: OrderKey {
                exchange: EXCHANGE,
                instrument: instrument_name(),
                strategy: StrategyId::new("test"),
                cid: ClientOrderId::new("resting"),
            },
            state: RequestCancel { id: None },
        };

        assert!(venue.cancel_order(cancel()).response.state.is_ok());
        let second = venue.cancel_order(cancel());

        assert!(
            matches!(
                second.response.state,
                Err(OrderError::Rejected(ApiError::OrderAlreadyCancelled))
            ),
            "got: {:?}",
            second.response.state
        );
    }

    /// A cancelled order is reported by a later snapshot, so a client reconciling against the venue
    /// sees the terminal state rather than an order that merely vanished.
    #[test]
    fn a_cancelled_order_enters_the_account_snapshot() {
        let (mut venue, _) = venue_resting_one_buy("48000");
        venue.cancel_order(OrderEvent {
            key: OrderKey {
                exchange: EXCHANGE,
                instrument: instrument_name(),
                strategy: StrategyId::new("test"),
                cid: ClientOrderId::new("resting"),
            },
            state: RequestCancel { id: None },
        });

        let snapshot = venue.account_snapshot();
        let orders = &snapshot.instruments[0].orders;
        assert_eq!(orders.len(), 1);
        assert!(matches!(
            orders[0].state,
            OrderState::Inactive(InactiveOrderState::Cancelled(_))
        ));
    }

    // --- Stage 3b: time in force ------------------------------------------------------------

    /// Every time in force this venue cannot honour is rejected rather than treated as
    /// `GoodUntilCancelled`, which would silently leave an order working that its sender asked to
    /// have cancelled.
    #[test]
    fn a_limit_order_is_rejected_for_every_time_in_force_this_venue_cannot_honour() {
        let unsupported = [
            TimeInForce::GoodUntilEndOfDay,
            TimeInForce::AtOpen,
            TimeInForce::AtClose,
        ];

        for time_in_force in unsupported {
            let mut venue = make_market_venue("10", "1000000");
            advance(&mut venue, time(1));
            assert!(
                venue
                    .apply_market(
                        &instrument_name(),
                        MarketObservation::new(book("49000", "49100")),
                        time(1)
                    )
                    .is_empty()
            );

            let outcome =
                venue.open_order(limit_request("tif", Side::Buy, "1", "48000", time_in_force));

            assert!(
                outcome.events.is_empty(),
                "{time_in_force} must move no balance"
            );
            assert!(
                venue.orders_open(&[]).is_empty(),
                "{time_in_force} must not rest"
            );
            match outcome.response.state {
                OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
                    ApiError::OrderRejected(ref reason),
                ))) => assert!(
                    reason.contains("does not model"),
                    "the rejection must say what is missing, got: {reason}"
                ),
                ref other => panic!("{time_in_force} must be rejected, got: {other:?}"),
            }
        }
    }

    /// A time in force that only bounds *how long* an order works is moot for one that fills in
    /// full on arrival, and must not stop a market order filling.
    #[test]
    fn a_market_order_is_accepted_for_every_time_in_force_that_only_bounds_how_long_it_works() {
        for time_in_force in [
            TimeInForce::GoodUntilCancelled { post_only: false },
            TimeInForce::ImmediateOrCancel,
            TimeInForce::FillOrKill,
            TimeInForce::GoodTillDate { expiry: time(9) },
            TimeInForce::GoodUntilEndOfDay,
        ] {
            let mut venue = make_venue("10", "1000000");
            let mut request = buy_request("1", market_prices("48000"));
            request.state.time_in_force = time_in_force;

            let outcome = venue.open_order(request);

            assert!(
                matches!(
                    outcome.response.state,
                    OrderState::Inactive(InactiveOrderState::FullyFilled(_))
                ),
                "{time_in_force} on a market order must still fill, got: {:?}",
                outcome.response.state
            );
        }
    }

    /// The two kinds of time in force a market order cannot keep, as opposed to the many it makes
    /// moot.
    ///
    /// `AtOpen` and `AtClose` say *when* an order executes rather than how long it works, and
    /// honouring them needs a session calendar. Filling one on arrival would answer a question its
    /// sender did not ask, at a price that is not the auction it wanted — this library's own IBKR
    /// client turns them into real market-on-close orders, so they are not a flag to be ignored.
    /// `post_only` is refused because a market order takes liquidity by definition.
    #[test]
    fn a_market_order_is_rejected_for_a_time_in_force_it_cannot_keep() {
        for time_in_force in [
            TimeInForce::GoodUntilCancelled { post_only: true },
            TimeInForce::AtOpen,
            TimeInForce::AtClose,
        ] {
            let mut venue = make_venue("10", "1000000");
            let mut request = buy_request("1", market_prices("48000"));
            request.state.time_in_force = time_in_force;

            let outcome = venue.open_order(request);

            assert!(
                outcome.events.is_empty(),
                "{time_in_force} must move no balance"
            );
            match outcome.response.state {
                OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
                    ApiError::OrderRejected(ref reason),
                ))) => assert!(
                    reason.contains("does not model"),
                    "the rejection must say what is missing, got: {reason}"
                ),
                ref other => panic!("{time_in_force} must be rejected, got: {other:?}"),
            }
        }
    }

    // --- Stage 3b-ii: post-only -------------------------------------------------------------

    /// Post-only means "never take liquidity", so being marketable is what disqualifies the order.
    ///
    /// It retires having traded nothing rather than being rejected: the request was valid, and the
    /// venue did exactly what `post_only` asked of it.
    #[test]
    fn a_post_only_order_that_would_take_liquidity_is_cancelled_having_traded_nothing() {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(1));
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(book("49000", "49100")),
                    time(1)
                )
                .is_empty()
        );

        // Buying at 50000 crosses an ask of 49100, so this order would be the aggressor.
        let outcome = venue.open_order(limit_request(
            "post",
            Side::Buy,
            "1",
            "50000",
            TimeInForce::GoodUntilCancelled { post_only: true },
        ));

        assert!(outcome.events.is_empty(), "nothing was reserved or traded");
        assert!(venue.orders_open(&[]).is_empty(), "it must not rest");
        assert!(venue.trades(time(0)).is_empty(), "it must not trade");

        match outcome.response.state {
            OrderState::Inactive(InactiveOrderState::Cancelled(ref cancelled)) => {
                assert_eq!(cancelled.filled_quantity, Some(Decimal::ZERO))
            }
            ref other => panic!("a marketable post-only order must be cancelled, got: {other:?}"),
        }
    }

    /// The same order that does *not* cross is exactly what post-only is for, and rests normally.
    #[test]
    fn a_post_only_order_that_would_rest_is_accepted_and_reserves() {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(1));
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(book("49000", "49100")),
                    time(1)
                )
                .is_empty()
        );

        let outcome = venue.open_order(limit_request(
            "post",
            Side::Buy,
            "1",
            "48000",
            TimeInForce::GoodUntilCancelled { post_only: true },
        ));

        assert_eq!(rested_open(&outcome).filled_quantity, Decimal::ZERO);
        assert_eq!(venue.orders_open(&[]).len(), 1);
        assert_eq!(
            balance_of(&outcome.events[0]).balance.free,
            d("1000000") - d("48000") - d("9.6"),
            "resting post-only reserves the notional plus the 2bp maker fee its fill will charge"
        );
    }

    // --- Stage 3b-ii: immediate-or-cancel and fill-or-kill -----------------------------------

    /// Both retire unfilled when the book is not there to trade against, and neither rests.
    ///
    /// They coincide because this venue models no order size — see `disposition`.
    #[test]
    fn a_non_marketable_immediate_order_is_cancelled_having_traded_nothing() {
        for time_in_force in [TimeInForce::ImmediateOrCancel, TimeInForce::FillOrKill] {
            let mut venue = make_market_venue("10", "1000000");
            advance(&mut venue, time(1));
            assert!(
                venue
                    .apply_market(
                        &instrument_name(),
                        MarketObservation::new(book("49000", "49100")),
                        time(1)
                    )
                    .is_empty()
            );

            let outcome =
                venue.open_order(limit_request("ioc", Side::Buy, "1", "48000", time_in_force));

            assert!(
                outcome.events.is_empty(),
                "{time_in_force} must move no balance"
            );
            assert!(
                venue.orders_open(&[]).is_empty(),
                "{time_in_force} must not rest"
            );
            match outcome.response.state {
                OrderState::Inactive(InactiveOrderState::Cancelled(ref cancelled)) => assert_eq!(
                    cancelled.filled_quantity,
                    Some(Decimal::ZERO),
                    "{time_in_force} traded nothing"
                ),
                ref other => panic!("{time_in_force} must be cancelled, got: {other:?}"),
            }
        }
    }

    /// Marketable, and both fill in full against the book as the aggressor.
    #[test]
    fn a_marketable_immediate_order_fills_in_full() {
        for time_in_force in [TimeInForce::ImmediateOrCancel, TimeInForce::FillOrKill] {
            let mut venue = make_market_venue("10", "1000000");
            advance(&mut venue, time(1));
            assert!(
                venue
                    .apply_market(
                        &instrument_name(),
                        MarketObservation::new(traded("49000")),
                        time(1)
                    )
                    .is_empty()
            );

            let outcome =
                venue.open_order(limit_request("ioc", Side::Buy, "1", "50000", time_in_force));

            assert!(
                matches!(
                    outcome.response.state,
                    OrderState::Inactive(InactiveOrderState::FullyFilled(_))
                ),
                "{time_in_force} must fill, got: {:?}",
                outcome.response.state
            );
        }
    }

    // --- Stage 3b-ii: deadlines -------------------------------------------------------------

    /// A deadline in the future rests like any other order, and nothing retires it early.
    #[test]
    fn a_good_till_date_order_rests_until_its_deadline() {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(1));

        let outcome = venue.open_order(limit_request(
            "gtd",
            Side::Buy,
            "1",
            "48000",
            TimeInForce::GoodTillDate { expiry: time(9) },
        ));

        assert_eq!(rested_open(&outcome).filled_quantity, Decimal::ZERO);

        // Short of the deadline, so the sweep must find nothing.
        advance(&mut venue, time(8));
        assert_eq!(venue.orders_open(&[]).len(), 1, "still working at time(8)");
    }

    /// Advancing to the deadline retires the order, releases what it held, and says so in order.
    #[test]
    fn advancing_to_a_deadline_releases_the_reservation_then_reports_the_order() {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(1));

        let outcome = venue.open_order(limit_request(
            "gtd",
            Side::Buy,
            "1",
            "48000",
            TimeInForce::GoodTillDate { expiry: time(9) },
        ));
        let reserved = balance_of(&outcome.events[0]).balance.free;

        let events = venue.advance_time(time(9));

        assert_eq!(events.len(), 2, "one release and one terminal snapshot");
        assert_eq!(
            balance_of(&events[0]).balance.free,
            reserved + d("48000") + d("9.6"),
            "the release restates exactly what resting took"
        );

        let order = order_of(&events[1]);
        match order.state {
            OrderState::Inactive(InactiveOrderState::Expired(ref expired)) => {
                assert_eq!(expired.time_exchange, time(9));
                assert_eq!(expired.filled_quantity, Some(Decimal::ZERO));
            }
            ref other => panic!("the order must be reported expired, got: {other:?}"),
        }

        assert!(venue.orders_open(&[]).is_empty(), "it must leave the book");
    }

    /// The deadline is reached *at* its instant, not after it.
    ///
    /// The boundary is the whole contract: a caller reading "good till `T`" must be able to say
    /// whether the order is working at `T`, and this pins the answer to "no".
    #[test]
    fn a_deadline_is_reached_at_its_instant_not_after_it() {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(1));

        let _ = venue.open_order(limit_request(
            "gtd",
            Side::Buy,
            "1",
            "48000",
            TimeInForce::GoodTillDate { expiry: time(5) },
        ));

        // One second short: still working.
        advance(&mut venue, time(4));
        assert_eq!(venue.orders_open(&[]).len(), 1);

        // Exactly the stated instant: retired.
        assert_eq!(venue.advance_time(time(5)).len(), 2);
        assert!(venue.orders_open(&[]).is_empty());
    }

    /// A tick that both reaches a deadline and crosses the order retires it rather than filling it.
    ///
    /// The deadline is an unconditional cutoff: whether an order trades at the very instant it
    /// expires must not depend on whether the market happened to cross there.
    #[test]
    fn a_deadline_is_swept_before_the_tick_that_would_have_filled_it() {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(1));

        let _ = venue.open_order(limit_request(
            "gtd",
            Side::Buy,
            "1",
            "48000",
            TimeInForce::GoodTillDate { expiry: time(5) },
        ));

        // An ask of 47000 crosses a limit of 48000, so this tick would have filled the order — but
        // it also reaches the deadline.
        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("46900", "47000")),
            time(5),
        );

        assert_eq!(events.len(), 2, "a release and an expiry, not a fill");
        assert!(
            venue.trades(time(0)).is_empty(),
            "an expired order must not trade on the tick that retired it"
        );
        assert!(matches!(
            order_of(&events[1]).state,
            OrderState::Inactive(InactiveOrderState::Expired(_))
        ));
    }

    /// An order whose deadline has already passed on arrival never reaches the book.
    ///
    /// With no independent clock, an order accepted past its own deadline would work until
    /// something else happened to touch the venue — and if nothing did, for the rest of the run.
    #[test]
    fn a_good_till_date_order_that_has_already_expired_is_never_rested() {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(9));

        let outcome = venue.open_order(limit_request(
            "stale",
            Side::Buy,
            "1",
            "48000",
            TimeInForce::GoodTillDate { expiry: time(5) },
        ));

        assert!(outcome.events.is_empty(), "nothing was reserved");
        assert!(venue.orders_open(&[]).is_empty(), "it must not rest");
        match outcome.response.state {
            OrderState::Inactive(InactiveOrderState::Expired(ref expired)) => {
                assert_eq!(expired.time_exchange, time(9), "stamped when it was found");
                assert_eq!(expired.filled_quantity, Some(Decimal::ZERO));
            }
            ref other => panic!("a stale deadline must expire, not {other:?}"),
        }
    }

    /// A stale deadline retires the order even when the book would have filled it.
    ///
    /// The same unconditional cutoff as on the tick path: an order whose deadline has elapsed has
    /// stopped working, so whether it *could* have traded is not a question the venue asks. The
    /// alternative would execute an order its sender had already asked to be finished with, and
    /// make the outcome depend on where the book happened to be.
    #[test]
    fn a_stale_deadline_retires_an_order_the_book_would_have_filled() {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(9));
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(traded("47000")),
                    time(9)
                )
                .is_empty()
        );

        let outcome = venue.open_order(limit_request(
            "stale",
            Side::Buy,
            "1",
            "48000",
            TimeInForce::GoodTillDate { expiry: time(5) },
        ));

        assert!(
            matches!(
                outcome.response.state,
                OrderState::Inactive(InactiveOrderState::Expired(_))
            ),
            "a marketable order past its deadline must expire, not fill: {:?}",
            outcome.response.state
        );
        assert!(
            venue.trades(time(0)).is_empty(),
            "it must not trade on its way out"
        );
    }

    /// A cancel arriving after its order's deadline is told *why* it found nothing.
    #[test]
    fn a_cancel_after_a_deadline_is_answered_already_expired() {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(1));

        let _ = venue.open_order(limit_request(
            "gtd",
            Side::Buy,
            "1",
            "48000",
            TimeInForce::GoodTillDate { expiry: time(5) },
        ));
        assert_eq!(venue.advance_time(time(6)).len(), 2);

        let outcome = venue.cancel_order(OrderEvent {
            key: OrderKey {
                exchange: EXCHANGE,
                instrument: instrument_name(),
                strategy: StrategyId::new("test"),
                cid: ClientOrderId::new("gtd"),
            },
            state: RequestCancel { id: None },
        });

        assert_eq!(
            outcome.response.state,
            Err(OrderError::Rejected(ApiError::OrderAlreadyExpired)),
            "a cancel that lost to a deadline must not read as an unknown order"
        );
    }

    /// An expired order is still part of the account, and a later snapshot reports it.
    #[test]
    fn an_expired_order_enters_the_account_snapshot() {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(1));

        let _ = venue.open_order(limit_request(
            "gtd",
            Side::Buy,
            "1",
            "48000",
            TimeInForce::GoodTillDate { expiry: time(5) },
        ));
        assert_eq!(venue.advance_time(time(5)).len(), 2);

        let snapshot = venue.account_snapshot();
        let orders = &snapshot.instruments[0].orders;
        assert_eq!(orders.len(), 1);
        assert!(matches!(
            orders[0].state,
            OrderState::Inactive(InactiveOrderState::Expired(_))
        ));
    }

    /// Deadlines are swept in deadline order, so a run's events do not depend on map iteration.
    #[test]
    fn deadlines_are_swept_earliest_first() {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(1));

        // Booked latest-deadline first, so insertion order is the opposite of sweep order.
        for (cid, expiry) in [("late", time(7)), ("early", time(5)), ("middle", time(6))] {
            let _ = venue.open_order(limit_request(
                cid,
                Side::Buy,
                "1",
                "48000",
                TimeInForce::GoodTillDate { expiry },
            ));
        }

        let events = venue.advance_time(time(9));

        // Each retirement is a release then a snapshot, so the orders are at the odd indices.
        let swept: Vec<_> = events
            .iter()
            .skip(1)
            .step_by(2)
            .map(|event| order_of(event).key.cid.0.to_string())
            .collect();

        assert_eq!(swept, ["early", "middle", "late"]);
    }

    /// A deadline is a property of the clock, not of a book: an order on an instrument that never
    /// ticks again is still retired by activity elsewhere on the venue.
    #[test]
    fn a_deadline_on_a_quiet_instrument_is_swept_by_a_tick_on_another() {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(1));

        let _ = venue.open_order(limit_request(
            "gtd",
            Side::Buy,
            "1",
            "48000",
            TimeInForce::GoodTillDate { expiry: time(5) },
        ));

        // A market for an instrument this venue holds no order on.
        let elsewhere = InstrumentNameExchange::new("eth_usdt");
        let events = venue.apply_market(
            &elsewhere,
            MarketObservation::new(book("2000", "2001")),
            time(6),
        );

        assert_eq!(
            events.len(),
            2,
            "the quiet instrument's order still retires"
        );
        assert!(venue.orders_open(&[]).is_empty());
    }

    /// An order the venue took nothing for releases nothing, exactly as cancelling one does.
    #[test]
    fn expiring_an_order_seeded_with_no_reservation_restates_no_balance() {
        let expiry = time(5);
        let seeded = Order {
            key: OrderKey {
                exchange: EXCHANGE,
                instrument: instrument_name(),
                strategy: StrategyId::new("test"),
                cid: ClientOrderId::new("seeded"),
            },
            side: Side::Buy,
            price: Some(d("48000")),
            quantity: d("1"),
            kind: OrderKind::Limit,
            time_in_force: TimeInForce::GoodTillDate { expiry },
            state: OrderState::active(Open::new(
                VenueOrderId::Assigned(OrderId::new("seeded")),
                time(1),
                Decimal::ZERO,
            )),
        };

        let mut venue = make_market_venue("10", "1000000");
        assert!(
            venue
                .account
                .book(
                    as_open(seeded).expect("the seeded order is Open"),
                    // As `initial_state` seeds one: the venue never took anything for it.
                    None,
                )
                .is_ok(),
            "the book is vacant under this id"
        );

        let events = venue.advance_time(expiry);

        assert_eq!(events.len(), 1, "the terminal snapshot alone, no release");
        assert!(matches!(
            order_of(&events[0]).state,
            OrderState::Inactive(InactiveOrderState::Expired(_))
        ));
    }

    // --- Stage 4: market orders are priced from the book they arrive to ---------------------

    /// A market-driven venue prices a market order from its own book, ignoring the requester's.
    ///
    /// The request carries a deliberately different snapshot, so a fill at the venue's price can
    /// only have come from the venue's own market — the two are far enough apart that no fill
    /// model or rounding could confuse them.
    #[test]
    fn a_market_driven_venue_prices_a_market_order_from_its_own_book() {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(1));
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(traded("49000")),
                    time(1)
                )
                .is_empty()
        );

        // What the sender was looking at when it decided, which is not what the venue holds.
        let outcome = venue.open_order(buy_request("1.0", Some(traded("40000"))));

        assert_eq!(
            filled_price(&outcome.response),
            d("49000"),
            "the fill is struck against the venue's book, not the snapshot the request carried"
        );
    }

    /// The same request on a request-priced venue still fills at the snapshot it carried.
    ///
    /// The regime is the whole of the difference, which is why `MockExchange`'s results do not
    /// move: it drives a `RequestPriced` venue and reads `market()` as `None` forever.
    #[test]
    fn a_request_priced_venue_still_prices_a_market_order_from_the_request() {
        let mut venue = make_venue("10", "1000000");

        let outcome = venue.open_order(buy_request("1.0", Some(traded("40000"))));

        assert_eq!(
            filled_price(&outcome.response),
            d("40000"),
            "with no book of its own, the request's snapshot is still the only price source"
        );
    }

    /// A market-driven venue that has never been fed an instrument rejects a market order in it
    /// rather than reaching for the requester's snapshot.
    ///
    /// Falling back would make the fill depend on which of the two happened to hold a price, and
    /// would re-admit the request-priced behaviour the regime exists to distinguish. The request
    /// here carries a perfectly good snapshot, and is refused anyway.
    #[test]
    fn a_market_driven_venue_with_no_book_rejects_a_market_order_rather_than_using_the_request() {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(1));

        let outcome = venue.open_order(buy_request("1.0", Some(traded("49000"))));

        assert!(outcome.events.is_empty(), "nothing was debited or traded");
        match outcome.response.state {
            OrderState::Inactive(InactiveOrderState::OpenFailed(
                UnindexedOrderError::Rejected(ApiError::OrderRejected(ref reason)),
            )) => assert!(
                reason.contains("no market snapshot"),
                "the rejection must name the venue's absent market, got: {reason}"
            ),
            ref other => panic!("an unpriceable market order must be rejected, got: {other:?}"),
        }
    }

    // ---------------------------------------------------------------------------------------
    // A taker takes only what is on offer.
    // ---------------------------------------------------------------------------------------

    /// The same size on both sides, so a test need only say how much.
    fn sized(amount: &str) -> MarketDepth {
        MarketDepth::new(Some(d(amount)), Some(d(amount)))
    }

    /// A venue fed one book carrying `depth`, priced off that book rather than off a last trade.
    ///
    /// The offer is 47900 throughout, so a buy limited at 48000 is marketable and prints at 47900.
    fn venue_offering(depth: MarketDepth) -> SimulatedVenue {
        venue_offering_funded("1000000", depth)
    }

    fn venue_offering_funded(usdt: &str, depth: MarketDepth) -> SimulatedVenue {
        let mut venue = make_market_venue_with(
            "10",
            usdt,
            maker_taker_fee(),
            SimFillConfig::BidAsk(BidAskFillModel),
        );
        advance(&mut venue, time(1));
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(book("47800", "47900")).with_depth(depth),
                    time(1)
                )
                .is_empty(),
            "an empty book fills nothing"
        );
        venue
    }

    fn free_quote(venue: &SimulatedVenue) -> Decimal {
        venue.balances(&[quote()])[0].balance.free
    }

    fn total_quote(venue: &SimulatedVenue) -> Decimal {
        venue.balances(&[quote()])[0].balance.total
    }

    /// A market order has no limit price, so what the book could not fill has nowhere to wait.
    #[test]
    fn a_market_order_fills_what_the_book_has_and_cancels_what_it_has_not() {
        let mut venue = venue_offering(sized("0.4"));

        let outcome = venue.open_order(buy_request("1", None));

        assert_eq!(
            outcome.events.len(),
            3,
            "a fill owes both balances, then the trade"
        );
        let trade = filled_trade(&outcome);
        assert_eq!(
            trade.quantity,
            d("0.4"),
            "it took the whole offer and no more"
        );
        assert_eq!(trade.price, d("47900"));

        match &outcome.response.state {
            OrderState::Inactive(InactiveOrderState::Cancelled(cancelled)) => assert_eq!(
                cancelled.filled_quantity,
                Some(d("0.4")),
                "the remainder retires carrying what did trade"
            ),
            other => panic!("a market order's unfillable remainder is cancelled, got: {other:?}"),
        }
        assert!(
            venue.orders_open(&[]).is_empty(),
            "a market order has no price to rest the remainder at"
        );
    }

    /// The condition under which the two coincided has expired, which is this test.
    #[test]
    fn fill_or_kill_refuses_the_partial_fill_immediate_or_cancel_accepts() {
        // One book, one size, one order -- only the time in force differs.
        let mut immediate = venue_offering(sized("0.4"));
        let mut all_or_nothing = venue_offering(sized("0.4"));

        let ioc = immediate.open_order(limit_request(
            "ioc",
            Side::Buy,
            "1",
            "48000",
            TimeInForce::ImmediateOrCancel,
        ));
        let fok = all_or_nothing.open_order(limit_request(
            "fok",
            Side::Buy,
            "1",
            "48000",
            TimeInForce::FillOrKill,
        ));

        assert_eq!(
            filled_trade(&ioc).quantity,
            d("0.4"),
            "immediate-or-cancel keeps what the book could give it"
        );

        assert!(
            fok.events.is_empty(),
            "fill-or-kill would rather trade nothing than trade in part"
        );
        assert!(
            all_or_nothing.trades(time(0)).is_empty(),
            "and nothing reached the ledger either"
        );
        assert_eq!(
            free_quote(&all_or_nothing),
            d("1000000"),
            "a killed order moves no balance"
        );
    }

    /// One arrival, one balance -- whatever it did with the part the book could not fill.
    #[test]
    fn a_capped_limit_order_fills_what_it_can_and_rests_the_remainder() {
        let mut venue = venue_offering(sized("0.4"));

        let outcome = venue.open_order(limit_request("split", Side::Buy, "1", "48000", gtc()));

        assert_eq!(
            outcome.events.len(),
            3,
            "one arrival restates each asset once and prints one trade, even settling and holding \
             at once"
        );
        let trade = filled_trade(&outcome);
        assert_eq!(trade.quantity, d("0.4"));
        assert_eq!(
            trade.price,
            d("47900"),
            "the part that traded took the offer"
        );

        let open = rested_open(&outcome);
        assert_eq!(
            open.filled_quantity,
            d("0.4"),
            "the remainder rests carrying what has already traded"
        );
        assert_eq!(open.quantity_remaining(d("1")), d("0.6"));
        assert_eq!(venue.orders_open(&[]).len(), 1);

        // Settled the taker leg, still holding the maker one: 19179.16 spent, 28805.76 held.
        assert_eq!(total_quote(&venue), d("1000000") - d("19179.16"));
        assert_eq!(
            free_quote(&venue),
            d("1000000") - d("19179.16") - d("28805.76")
        );
    }

    /// The sell side of the same arrival: it pays with base and receives quote, so the base it
    /// settles and the base it holds for the remainder are one commitment, and the quote it
    /// receives for the part that traded funds neither.
    #[test]
    fn a_capped_spot_sell_settles_and_holds_base_and_receives_quote_for_what_traded() {
        let mut venue = venue_offering(sized("0.4"));

        let outcome = venue.open_order(limit_request("split", Side::Sell, "1", "47700", gtc()));

        assert_eq!(
            outcome.events.len(),
            3,
            "the base paid, the quote received, then the trade"
        );
        let trade = filled_trade(&outcome);
        assert_eq!(trade.quantity, d("0.4"));
        assert_eq!(trade.price, d("47800"), "the part that traded took the bid");

        // 0.4 delivered, 0.6 held for the remainder resting at its 47700 limit.
        let paid = filled_balance(&outcome);
        assert_eq!(paid.asset, base());
        assert_eq!(paid.balance, Balance::new(d("9.6"), d("9")));

        // 0.4 at 47800 is 19120, less the 10bp taker fee of 19.12.
        let received = filled_received(&outcome);
        assert_eq!(received.asset, quote());
        assert_eq!(
            received.balance,
            Balance::new(d("1019100.88"), d("1019100.88"))
        );
        assert_eq!(rested_open(&outcome).quantity_remaining(d("1")), d("0.6"));
    }

    /// An order that fills in part, rests, and is later crossed settles exactly the remainder --
    /// twice in total, summing to the original, with no third restatement.
    #[test]
    fn an_order_filled_in_part_then_crossed_settles_the_remainder_and_no_more() {
        let mut venue = venue_offering(sized("0.4"));

        let arrival = venue.open_order(limit_request("split", Side::Buy, "1", "48000", gtc()));
        let taker = filled_trade(&arrival).clone();

        // The market reaches what is resting.
        let fills = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("48000", "48000")),
            time(2),
        );
        assert_eq!(
            fills.len(),
            4,
            "a resting fill owes both balances, the trade, the order"
        );
        let maker = trade_of(&fills[2]);

        assert_eq!(maker.quantity, d("0.6"), "only the remainder crosses");
        assert_eq!(
            maker.price,
            d("48000"),
            "a maker is paid the price it quoted, not the one the book moved to"
        );
        assert_eq!(
            taker.quantity + maker.quantity,
            d("1"),
            "the two fills are the whole order, and no more than it"
        );

        assert_ne!(
            taker.id, maker.id,
            "one order printing twice must print two distinguishable trades"
        );
        assert_eq!(
            taker.order_id, maker.order_id,
            "and both must still say which order they belong to"
        );

        // 0.4 taken at 47900 plus 10bp, then 0.6 quoted at 48000 plus 2bp. Nothing else moved.
        let spent = d("19179.16") + d("28805.76");
        assert_eq!(total_quote(&venue), d("1000000") - spent);
        assert_eq!(
            free_quote(&venue),
            d("1000000") - spent,
            "the order is done, so nothing is still held against it"
        );
    }

    /// Reading a stored size does not consume it -- only filling against it does.
    #[test]
    fn a_second_order_on_one_observation_sees_only_what_the_first_left() {
        let mut venue = venue_offering(sized("1"));

        let first = venue.open_order(limit_request(
            "first",
            Side::Buy,
            "0.6",
            "48000",
            TimeInForce::ImmediateOrCancel,
        ));
        assert_eq!(filled_trade(&first).quantity, d("0.6"));

        let second = venue.open_order(limit_request(
            "second",
            Side::Buy,
            "0.6",
            "48000",
            TimeInForce::ImmediateOrCancel,
        ));
        assert_eq!(
            filled_trade(&second).quantity,
            d("0.4"),
            "the offer was displayed once, so the two of them share it"
        );

        let third = venue.open_order(limit_request(
            "third",
            Side::Buy,
            "0.6",
            "48000",
            TimeInForce::ImmediateOrCancel,
        ));
        assert!(
            third.events.is_empty(),
            "the offer is exhausted until the next observation replaces it"
        );
    }

    /// A new observation states what is on offer now; it is not an increment on what was.
    #[test]
    fn a_new_observation_replaces_the_remaining_size_rather_than_adding_to_it() {
        let mut venue = venue_offering(sized("1"));

        let taken = venue.open_order(limit_request(
            "first",
            Side::Buy,
            "0.6",
            "48000",
            TimeInForce::ImmediateOrCancel,
        ));
        assert_eq!(filled_trade(&taken).quantity, d("0.6"));

        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(book("47800", "47900")).with_depth(sized("1")),
                    time(2)
                )
                .is_empty()
        );

        let after = venue.open_order(limit_request(
            "second",
            Side::Buy,
            "1",
            "48000",
            TimeInForce::ImmediateOrCancel,
        ));
        assert_eq!(
            filled_trade(&after).quantity,
            d("1"),
            "the fresh observation offers a whole unit again"
        );
    }

    /// No size information is not no size. A price-only feed must keep filling exactly as it did.
    #[test]
    fn a_feed_supplying_no_size_caps_nothing() {
        let mut venue = venue_offering(MarketDepth::UNKNOWN);

        let outcome = venue.open_order(limit_request(
            "uncapped",
            Side::Buy,
            "5",
            "48000",
            TimeInForce::ImmediateOrCancel,
        ));

        assert_eq!(
            filled_trade(&outcome).quantity,
            d("5"),
            "an absent size caps nothing, however large the order"
        );
    }

    /// A reported *absence* of size is the other thing, and it does stop a fill.
    #[test]
    fn a_marketable_order_with_nothing_on_offer_rests_rather_than_filling() {
        let mut venue = venue_offering(MarketDepth::new(Some(d("1")), Some(Decimal::ZERO)));

        let outcome = venue.open_order(limit_request("nothing", Side::Buy, "1", "48000", gtc()));

        assert_eq!(
            outcome.events.len(),
            1,
            "nothing traded, so it owes only the hold it took"
        );
        assert_eq!(rested_open(&outcome).filled_quantity, Decimal::ZERO);
    }

    /// A capped order costs **more** than the same order filling outright: its remainder is held at
    /// the order's own limit while the fill struck a better price. So an account can afford the
    /// whole order and still not afford the split -- and it is refused whole rather than filled for
    /// the part it could pay for, which would be this venue choosing a disposition nobody asked for.
    #[test]
    fn an_order_that_cannot_fund_both_legs_is_refused_with_nothing_moved() {
        // 47947.90 buys the whole of it at the offer; the split wants 47984.92.
        const FUNDED: &str = "47950";

        let mut uncapped = venue_offering_funded(FUNDED, MarketDepth::UNKNOWN);
        let affordable =
            uncapped.open_order(limit_request("whole", Side::Buy, "1", "48000", gtc()));
        assert_eq!(
            filled_trade(&affordable).quantity,
            d("1"),
            "uncapped, this very order is affordable and fills outright"
        );

        let mut venue = venue_offering_funded(FUNDED, sized("0.4"));
        let outcome = venue.open_order(limit_request("split", Side::Buy, "1", "48000", gtc()));

        assert!(outcome.events.is_empty(), "a refused order moves nothing");
        assert!(
            matches!(
                outcome.response.state,
                OrderState::Inactive(InactiveOrderState::OpenFailed(_))
            ),
            "and says so, rather than filling the part it could afford: {:?}",
            outcome.response.state
        );
        assert_eq!(free_quote(&venue), d(FUNDED), "the ledger is as it was");
        assert_eq!(total_quote(&venue), d(FUNDED));
        assert!(venue.trades(time(0)).is_empty(), "and nothing traded");
        assert!(venue.orders_open(&[]).is_empty());
    }

    fn is_duplicate_cid(state: &UnindexedOrderState) -> bool {
        matches!(
            state,
            OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
                ApiError::DuplicateClientOrderId(_)
            )))
        )
    }

    /// An open under the id of a resting order is rejected, and the resting order keeps its size,
    /// its place and what is held against it.
    #[test]
    fn an_open_under_a_resting_id_is_rejected_and_the_resting_order_is_untouched() {
        let (mut venue, _) = venue_resting_one_buy("48000");
        let free = free_quote(&venue);

        // Same cid, a different size and price.
        let second = venue.open_order(limit_request("resting", Side::Buy, "0.5", "47000", gtc()));

        assert!(
            is_duplicate_cid(&second.response.state),
            "rejected as a duplicate: {:?}",
            second.response.state
        );
        assert!(second.events.is_empty(), "a rejection moves nothing");
        let [resting] = &venue.orders_open(&[])[..] else {
            panic!("one cid, one resting order");
        };
        assert_eq!(
            (resting.quantity, resting.price),
            (d("1"), Some(d("48000"))),
            "the resting order is the first one"
        );
        assert_eq!(
            free_quote(&venue),
            free,
            "its hold is still held, and only its"
        );
        assert_eq!(total_quote(&venue), d("1000000"));
    }

    /// The check covers every kind: a market order under a resting id is rejected before it can
    /// trade, although it would never have rested itself.
    #[test]
    fn a_market_order_under_a_resting_id_is_rejected_before_it_trades() {
        let (mut venue, _) = venue_resting_one_buy("48000");
        let mut market = buy_request("0.1", None);
        market.key.cid = ClientOrderId::new("resting");

        let outcome = venue.open_order(market);

        assert!(
            is_duplicate_cid(&outcome.response.state),
            "rejected as a duplicate: {:?}",
            outcome.response.state
        );
        assert!(venue.trades(time(0)).is_empty(), "nothing traded");
        assert_eq!(venue.orders_open(&[]).len(), 1);
    }

    /// A malformed request is reported as malformed, even under a resting id.
    #[test]
    fn a_malformed_open_under_a_resting_id_is_rejected_as_malformed() {
        let (mut venue, _) = venue_resting_one_buy("48000");

        let outcome = venue.open_order(limit_request(
            "resting",
            Side::Buy,
            "1",
            "47000",
            TimeInForce::AtOpen,
        ));

        assert!(
            matches!(
                outcome.response.state,
                OrderState::Inactive(InactiveOrderState::OpenFailed(_))
            ) && !is_duplicate_cid(&outcome.response.state),
            "rejected on its time in force: {:?}",
            outcome.response.state
        );
    }

    /// Once an order is cancelled its id is free, and what the venue reports under the id is the
    /// latest order: still working while it rests, cancelled once it is.
    #[test]
    fn a_cancelled_orders_id_is_free_again_and_the_latest_order_is_reported() {
        let (mut venue, _) = venue_resting_one_buy("48000");
        let cancel = |venue: &mut SimulatedVenue| {
            venue.cancel_order(OrderRequestCancel {
                key: limit_request("resting", Side::Buy, "1", "48000", gtc()).key,
                state: RequestCancel { id: None },
            })
        };
        assert!(cancel(&mut venue).response.state.is_ok());

        let second = venue.open_order(limit_request("resting", Side::Buy, "0.5", "47000", gtc()));

        assert!(
            matches!(
                second.response.state,
                OrderState::Active(ActiveOrderState::Open(_))
            ),
            "the id is free again: {:?}",
            second.response.state
        );
        assert!(
            venue.orders_ended(&[key_of("resting")]).is_empty(),
            "the order under the id is working, whatever became of the one before it"
        );
        let snapshot = venue.account_snapshot();
        let listed = snapshot
            .instruments
            .iter()
            .flat_map(|instrument| &instrument.orders)
            .filter(|order| order.key.cid == ClientOrderId::new("resting"))
            .count();
        assert_eq!(
            listed, 1,
            "a snapshot lists the id once, as the working order"
        );

        assert!(
            cancel(&mut venue).response.state.is_ok(),
            "and the cancel reaches it"
        );
        let [ended] = &venue.orders_ended(&[key_of("resting")])[..] else {
            panic!("the second order has ended");
        };
        assert_eq!(ended.quantity, d("0.5"), "the latest order under the id");
    }

    /// Once an order fills its id is free: an order under it rests, and a cancel reaches that
    /// order instead of being refused as "already filled".
    #[test]
    fn a_filled_orders_id_is_free_again() {
        let (mut venue, _) = venue_resting_one_buy("48000");
        let filled = venue.open_order(limit_request("reused", Side::Buy, "1", "49100", gtc()));
        assert!(
            matches!(
                filled.response.state,
                OrderState::Inactive(InactiveOrderState::FullyFilled(_))
            ),
            "crosses the ask, so fills on arrival"
        );

        let second = venue.open_order(limit_request("reused", Side::Buy, "1", "47000", gtc()));
        assert!(
            matches!(
                second.response.state,
                OrderState::Active(ActiveOrderState::Open(_))
            ),
            "the id is free again: {:?}",
            second.response.state
        );

        let cancelled = venue.cancel_order(OrderRequestCancel {
            key: limit_request("reused", Side::Buy, "1", "47000", gtc()).key,
            state: RequestCancel { id: None },
        });
        assert!(
            cancelled.response.state.is_ok(),
            "the cancel reaches the working order: {:?}",
            cancelled.response.state
        );
    }

    // --- How an order ended -------------------------------------------------------------------

    fn key_of(cid: &str) -> UnindexedOrderKey {
        OrderKey {
            exchange: EXCHANGE,
            instrument: instrument_name(),
            strategy: StrategyId::new("asker"),
            cid: ClientOrderId::new(cid),
        }
    }

    /// Every way an order can end on this venue is reported, under the key it was asked for, and
    /// an order still working or never held is left out.
    #[test]
    fn orders_ended_reports_each_ended_order_and_omits_the_rest() {
        let mut venue = make_market_venue("10", "1000000");
        advance(&mut venue, time(1));
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(book("49000", "49100")),
                    time(1)
                )
                .is_empty()
        );

        let filled = venue.open_order(limit_request("filled", Side::Buy, "1", "49100", gtc()));
        assert!(
            matches!(
                filled.response.state,
                OrderState::Inactive(InactiveOrderState::FullyFilled(_))
            ),
            "crosses the ask, so fills on arrival"
        );
        let _ = venue.open_order(limit_request("working", Side::Buy, "1", "48000", gtc()));
        let _ = venue.open_order(limit_request("cancelled", Side::Buy, "1", "47500", gtc()));
        let _ = venue.cancel_order(OrderEvent {
            key: key_of("cancelled"),
            state: RequestCancel { id: None },
        });
        let _ = venue.open_order(limit_request(
            "expired",
            Side::Buy,
            "1",
            "47000",
            TimeInForce::GoodTillDate { expiry: time(9) },
        ));
        assert_eq!(
            venue.advance_time(time(9)).len(),
            2,
            "the deadline retires it"
        );

        let asked = ["filled", "working", "cancelled", "expired", "unknown"].map(key_of);
        let ended = venue.orders_ended(&asked);

        assert_eq!(ended.len(), 3, "exactly the three ended orders: {ended:?}");
        assert!(
            ended
                .iter()
                .all(|order| order.key.strategy == StrategyId::new("asker")),
            "each comes back under the key it was asked for"
        );
        let ended_as = |cid: &str| {
            let Some(order) = ended
                .iter()
                .find(|order| order.key.cid == ClientOrderId::new(cid))
            else {
                panic!("{cid} is reported: {ended:?}");
            };
            order
        };
        let (filled, cancelled, expired) = (
            ended_as("filled"),
            ended_as("cancelled"),
            ended_as("expired"),
        );
        match &filled.state {
            InactiveOrderState::FullyFilled(state) => {
                assert_eq!(state.filled_quantity, d("1"));
                assert_eq!(state.avg_price, Some(d("49100")));
            }
            other => panic!("filled, got {other:?}"),
        }
        match &cancelled.state {
            InactiveOrderState::Cancelled(state) => {
                assert_eq!(state.filled_quantity, Some(Decimal::ZERO))
            }
            other => panic!("cancelled, got {other:?}"),
        }
        match &expired.state {
            InactiveOrderState::Expired(state) => assert_eq!(state.time_exchange, time(9)),
            other => panic!("expired, got {other:?}"),
        }

        assert!(
            venue.orders_ended(&[]).is_empty(),
            "an empty request asks about nothing, not about everything"
        );
    }

    /// A market order's unfillable remainder retires as a cancel carrying what did trade, and a
    /// lookup reports it so.
    #[test]
    fn orders_ended_reports_a_market_remainder_as_cancelled_with_its_fill() {
        let mut venue = venue_offering(sized("0.4"));
        let outcome = venue.open_order(buy_request("1", None));

        let ended = venue.orders_ended(std::slice::from_ref(&outcome.response.key));

        let [order] = ended.as_slice() else {
            panic!("the remainder's order is reported: {ended:?}");
        };
        match &order.state {
            InactiveOrderState::Cancelled(state) => {
                assert_eq!(state.filled_quantity, Some(d("0.4")))
            }
            other => panic!("cancelled carrying its fill, got {other:?}"),
        }
    }

    /// A resting order filled from the book is reported with the price it filled at, and one that
    /// reached the book part-filled with no average, as its own fill reported.
    #[test]
    fn orders_ended_reports_a_resting_fill_and_its_average_price_as_the_fill_did() {
        let (mut venue, _) = venue_resting_one_buy("48000");
        assert!(
            venue
                .account
                .book(seeded_part_filled("48000", "1", "0.4"), None)
                .is_ok(),
            "the book is vacant under this id"
        );
        advance(&mut venue, time(2));
        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("47800", "47900")),
            time(2),
        );
        assert_eq!(
            events.len(),
            8,
            "two fills, each two balances, a trade and an order"
        );

        let ended = venue.orders_ended(&[key_of("resting"), key_of("part_filled")]);

        let avg_price_of = |cid: &str| {
            let Some(order) = ended
                .iter()
                .find(|order| order.key.cid == ClientOrderId::new(cid))
            else {
                panic!("{cid} is reported: {ended:?}");
            };
            match &order.state {
                InactiveOrderState::FullyFilled(filled) => {
                    assert_eq!(filled.filled_quantity, d("1"));
                    filled.avg_price
                }
                other => panic!("{cid} filled, got {other:?}"),
            }
        };
        assert_eq!(avg_price_of("resting"), Some(d("48000")));
        assert_eq!(
            avg_price_of("part_filled"),
            None,
            "this venue saw only one of the two fills behind it"
        );
    }

    /// An order the configured `initial_state` reports as cancelled is reported as such.
    #[test]
    fn orders_ended_reports_an_order_the_initial_state_seeded_as_cancelled() {
        let seeded = Order {
            key: key_of("seeded"),
            side: Side::Buy,
            price: Some(d("48000")),
            quantity: d("1"),
            kind: OrderKind::Limit,
            time_in_force: gtc(),
            state: OrderState::inactive(Cancelled {
                id: OrderId::new("seeded"),
                time_exchange: time(0),
                filled_quantity: Some(d("0.25")),
            }),
        };
        let venue = SimulatedVenue::new(
            &spot_config_holding("10", "1000000", seeded),
            spot_instruments(),
        );

        let ended = venue.orders_ended(&[key_of("seeded")]);

        let [order] = ended.as_slice() else {
            panic!("the seeded cancel is reported: {ended:?}");
        };
        match &order.state {
            InactiveOrderState::Cancelled(cancelled) => {
                assert_eq!(cancelled.filled_quantity, Some(d("0.25")))
            }
            other => panic!("cancelled, got {other:?}"),
        }
    }

    /// An id asked about twice is reported once, under the first key that finds it, and a key
    /// naming another instrument does not find the order or stop a later key from finding it.
    #[test]
    fn orders_ended_reports_an_id_once_and_only_for_its_own_instrument() {
        let mut venue = venue_offering(sized("0.4"));
        let outcome = venue.open_order(buy_request("1", None));
        let key = outcome.response.key.clone();
        let other_instrument = OrderKey {
            instrument: InstrumentNameExchange::new("ETHUSDT"),
            ..key.clone()
        };
        let second_ask = OrderKey {
            strategy: StrategyId::new("second"),
            ..key.clone()
        };

        let ended = venue.orders_ended(&[key.clone(), second_ask]);
        let [order] = ended.as_slice() else {
            panic!("one entry for one id: {ended:?}");
        };
        assert_eq!(order.key, key, "the first key that finds it");

        let ended = venue.orders_ended(&[other_instrument.clone(), key.clone()]);
        let [order] = ended.as_slice() else {
            panic!("a key that finds nothing does not stop a later one: {ended:?}");
        };
        assert_eq!(order.key, key);

        assert!(
            venue.orders_ended(&[other_instrument]).is_empty(),
            "a key for another instrument does not find it"
        );
    }

    // --- Holding costs: charged at each boundary the clock reaches -----------------------------

    /// Hourly funding on the CFD at `rate` per hour, so a boundary falls on every whole hour.
    fn hourly_funding(rate: &str) -> Arc<dyn HoldingCostModel> {
        Arc::new(
            FundingModel::new(TimeDelta::hours(1))
                .with_rates(cfd_instrument_name(), RateSeries::constant(d(rate))),
        )
    }

    /// The `n`th whole hour after `time(0)`: `time(0)` is 2023-11-14T22:13:20Z.
    fn boundary(n: i64) -> DateTime<Utc> {
        time(2800 + 3600 * n)
    }

    /// A market-driven CFD venue charging `models`, its clock first moved to `time(1)`.
    fn make_cfd_venue_charging(
        usd: &str,
        models: Vec<Arc<dyn HoldingCostModel>>,
    ) -> SimulatedVenue {
        let mut venue = SimulatedVenue::new_market_driven(
            &config_from_balances(vec![funded(self::usd(), d(usd))], FeeModelConfig::default()),
            instruments_of(cfd_instrument()),
        )
        .with_holding_costs(models);
        advance(&mut venue, time(1));
        venue
    }

    /// The cash flows among `events`, each with the balance restated just before it.
    fn charges(
        events: &[UnindexedAccountEvent],
    ) -> Vec<(
        &AssetBalance<AssetNameExchange>,
        &CashFlow<AssetNameExchange, InstrumentNameExchange>,
    )> {
        events
            .chunks(2)
            .map(
                |pair| match (&pair[0].kind, pair.get(1).map(|event| &event.kind)) {
                    (
                        AccountEventKind::BalanceSnapshot(balance),
                        Some(AccountEventKind::CashFlow(flow)),
                    ) => (&balance.0, flow),
                    other => panic!("a charge is [balance, cash flow], got: {other:?}"),
                },
            )
            .collect()
    }

    /// The position is valued at the mid (5000), not the last trade (4000) it filled at: a long
    /// of 1 contract × 25 × 5000 pays 0.0001 of it, 12.5, as one restatement and one cash flow,
    /// both stamped at the boundary.
    #[test]
    fn a_position_held_across_a_boundary_is_charged_there_as_balance_then_cash_flow() {
        let mut venue = make_cfd_venue_charging("200000", vec![hourly_funding("0.0001")]);
        assert!(cfd_market(&mut venue, "4990", "5010", "4000").is_empty());
        cfd_market_fill(&mut venue, Side::Buy, "1");
        assert_eq!(free_usd(&venue), d("100000"));

        let events = venue.advance_time(boundary(0));
        let charged = charges(&events);

        assert_eq!(charged.len(), 1);
        let (balance, flow) = charged[0];
        assert_eq!(balance.asset, usd());
        assert_eq!(balance.balance, Balance::new(d("99987.5"), d("99987.5")));
        assert_eq!(balance.time_exchange, boundary(0));
        assert_eq!(
            *flow,
            CashFlow::new(
                CashFlowKind::Funding {
                    rate: Some(d("0.0001")),
                    position_quantity: Some(d("1")),
                },
                usd(),
                d("-12.5"),
                Some(cfd_instrument_name()),
                boundary(0),
                Some(CashFlowId::new("0")),
            )
        );
        assert_eq!(total_usd(&venue), d("99987.5"));
    }

    /// A clock that jumps over several boundaries charges each one, in time order and at its own
    /// stamp, and a clock moved to an instant already charged charges nothing again.
    #[test]
    fn a_gap_of_several_boundaries_is_caught_up_once_each() {
        let mut venue = make_cfd_venue_charging("200000", vec![hourly_funding("0.0001")]);
        assert!(cfd_market(&mut venue, "5000", "5000", "5000").is_empty());
        cfd_market_fill(&mut venue, Side::Sell, "1");

        let events = venue.advance_time(boundary(2) + TimeDelta::seconds(1));
        let charged = charges(&events);

        let stamps: Vec<_> = charged.iter().map(|(_, flow)| flow.time_exchange).collect();
        assert_eq!(stamps, vec![boundary(0), boundary(1), boundary(2)]);
        let ids: Vec<_> = charged.iter().map(|(_, flow)| flow.id.clone()).collect();
        assert_eq!(
            ids,
            ["0", "1", "2"].map(|id| Some(CashFlowId::new(id))).to_vec()
        );
        assert!(
            charged.iter().all(|(_, flow)| flow.amount == d("12.5")),
            "a short receives a positive funding rate"
        );
        assert_eq!(free_usd(&venue), d("75000") + d("37.5"));

        assert!(
            venue
                .advance_time(boundary(2) + TimeDelta::seconds(1))
                .is_empty()
        );
        assert!(
            venue.advance_time(boundary(1)).is_empty(),
            "the clock moving back"
        );
        assert_eq!(free_usd(&venue), d("75000") + d("37.5"));
    }

    /// Charging starts where the clock first moves, not at the epoch the clock starts at. A venue
    /// with no market values the position at its entry price.
    #[test]
    fn charging_starts_at_the_first_clock_move_and_values_at_entry_without_a_market() {
        let mut venue = make_cfd_venue("200000", FeeModelConfig::default())
            .with_holding_costs(vec![hourly_funding("0.0001")]);
        cfd_fill(&mut venue, Side::Buy, "1", "4000");

        assert!(
            venue
                .advance_time(boundary(0) + TimeDelta::seconds(1))
                .is_empty(),
            "the first move charges nothing before it"
        );

        let events = venue.advance_time(boundary(1));
        let charged = charges(&events);
        assert_eq!(charged.len(), 1);
        // 1 × 25 × 4000 × 0.0001, at the entry price.
        assert_eq!(charged[0].1.amount, d("-10"));
    }

    /// At a boundary's instant the venue charges before it fills: a position opened there is not
    /// charged for it, and one closed there is.
    #[test]
    fn a_position_opened_at_a_boundary_is_not_charged_for_it_and_one_closed_there_is() {
        let mut venue = make_cfd_venue_charging("200000", vec![hourly_funding("0.0001")]);
        assert!(cfd_market(&mut venue, "5000", "5000", "5000").is_empty());

        assert!(venue.advance_time(boundary(0)).is_empty());
        cfd_market_fill(&mut venue, Side::Buy, "1");

        let events = venue.advance_time(boundary(1));
        let stamps: Vec<_> = charges(&events)
            .iter()
            .map(|(_, flow)| flow.time_exchange)
            .collect();
        assert_eq!(stamps, vec![boundary(1)]);

        cfd_market_fill(&mut venue, Side::Sell, "1");
        assert!(venue.advance_time(boundary(3)).is_empty(), "flat");
    }

    /// A tick that passes a boundary charges it at the market as it stood before the tick.
    #[test]
    fn a_market_tick_past_a_boundary_charges_it_at_the_market_before_the_tick() {
        let mut venue = make_cfd_venue_charging("200000", vec![hourly_funding("0.0001")]);
        assert!(cfd_market(&mut venue, "5000", "5000", "5000").is_empty());
        cfd_market_fill(&mut venue, Side::Buy, "1");

        let six_thousand = MarketSnapshot {
            best_bid: Some(d("6000")),
            best_ask: Some(d("6000")),
            last_price: Some(d("6000")),
        };
        let events = venue.apply_market(
            &cfd_instrument_name(),
            MarketObservation::new(six_thousand),
            boundary(0) + TimeDelta::seconds(1),
        );

        let charged = charges(&events);
        assert_eq!(charged.len(), 1);
        assert_eq!(charged[0].1.amount, d("-12.5"), "valued at 5000, not 6000");
    }

    /// A charge the account cannot cover is still made: this venue models no liquidation to stop
    /// it, and leaving it out would understate the cost.
    #[test]
    fn a_charge_the_account_cannot_cover_takes_free_below_zero() {
        let mut venue = make_cfd_venue_charging("125000", vec![hourly_funding("0.0001")]);
        assert!(cfd_market(&mut venue, "5000", "5000", "5000").is_empty());
        cfd_market_fill(&mut venue, Side::Buy, "1");
        assert_eq!(free_usd(&venue), Decimal::ZERO);

        let events = venue.advance_time(boundary(0));

        assert_eq!(
            charges(&events)[0].0.balance,
            Balance::new(d("-12.5"), d("-12.5"))
        );
    }

    /// Run `f`, returning its value and the message of every WARN it logged on this thread.
    fn warnings<T>(f: impl FnOnce() -> T) -> (T, Vec<String>) {
        use std::sync::Mutex;
        use tracing_subscriber::layer::SubscriberExt;

        struct Warnings(Arc<Mutex<Vec<String>>>);

        struct Message<'a>(&'a mut String);

        impl tracing::field::Visit for Message<'_> {
            fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
                if field.name() == "message" {
                    *self.0 = format!("{value:?}");
                }
            }
        }

        impl<S: tracing::Subscriber> tracing_subscriber::Layer<S> for Warnings {
            fn on_event(
                &self,
                event: &tracing::Event<'_>,
                _: tracing_subscriber::layer::Context<'_, S>,
            ) {
                if *event.metadata().level() == tracing::Level::WARN {
                    let mut message = String::new();
                    event.record(&mut Message(&mut message));
                    self.0.lock().unwrap().push(message);
                }
            }
        }

        let warnings = Arc::new(Mutex::new(Vec::new()));
        let subscriber = tracing_subscriber::registry().with(Warnings(Arc::clone(&warnings)));
        let value = tracing::subscriber::with_default(subscriber, f);
        let warnings = warnings.lock().unwrap().clone();
        (value, warnings)
    }

    /// An account charged into a negative balance is warned once, on the charge that took it
    /// there, not again for each charge while it stays negative, nor for a credit.
    #[test]
    fn a_negative_balance_is_warned_of_on_the_charge_that_crosses_zero() {
        // Paid for three hours, then received while the balance is still below zero.
        let rates = RateSeries::new(vec![
            (DateTime::<Utc>::MIN_UTC, d("0.0001")),
            (boundary(3), d("-0.00001")),
        ])
        .unwrap();
        let funding =
            FundingModel::new(TimeDelta::hours(1)).with_rates(cfd_instrument_name(), rates);
        let mut venue = make_cfd_venue_charging("125000", vec![Arc::new(funding)]);
        assert!(cfd_market(&mut venue, "5000", "5000", "5000").is_empty());
        cfd_market_fill(&mut venue, Side::Buy, "1");

        let (events, logged) = warnings(|| venue.advance_time(boundary(2)));
        assert_eq!(charges(&events).len(), 3, "three charges, all below zero");
        assert_eq!(logged.len(), 1, "{logged:?}");
        assert!(logged[0].contains("could not cover"), "{logged:?}");

        let (events, logged) = warnings(|| venue.advance_time(boundary(3)));
        assert_eq!(charges(&events)[0].1.amount, d("1.25"), "the long receives");
        assert_eq!(free_usd(&venue), d("-36.25"));
        assert!(logged.is_empty(), "a credit is not warned of: {logged:?}");
    }

    /// A charge of zero is not reported: there is nothing to apply.
    #[test]
    fn a_zero_charge_is_not_reported() {
        let mut venue = make_cfd_venue_charging("200000", vec![hourly_funding("0")]);
        assert!(cfd_market(&mut venue, "5000", "5000", "5000").is_empty());
        cfd_market_fill(&mut venue, Side::Buy, "1");

        assert!(venue.advance_time(boundary(1)).is_empty());
    }

    /// The next deadline is the earlier of an order's expiry and a held position's boundary, and
    /// a flat venue with no expiring order has none.
    #[test]
    fn the_next_deadline_is_the_earliest_expiry_or_boundary() {
        let mut venue = make_cfd_venue_charging("200000", vec![hourly_funding("0.0001")]);
        assert!(cfd_market(&mut venue, "5000", "5000", "5000").is_empty());
        assert_eq!(venue.next_deadline(), None, "flat, no orders");

        cfd_market_fill(&mut venue, Side::Buy, "1");
        assert_eq!(venue.next_deadline(), Some(boundary(0)));

        // Rests without crossing, and holds nothing, since it only reduces the long.
        let expiry = boundary(0) - TimeDelta::seconds(60);
        let mut gtd = limit_request(
            "gtd",
            Side::Sell,
            "1",
            "6000",
            TimeInForce::GoodTillDate { expiry },
        );
        gtd.key.instrument = cfd_instrument_name();
        assert!(venue.open_order(gtd).response.state.is_accepted());
        assert_eq!(venue.next_deadline(), Some(expiry));

        let events = venue.advance_time(expiry);
        assert!(!events.is_empty(), "the order expired");
        assert_eq!(venue.next_deadline(), Some(boundary(0)));
    }

    /// A borrow fee on settlement days and financing on calendar days, both at 21:00 UTC, on a
    /// short. `time(1)` is Tuesday 2023-11-14 22:13:21Z, so the first cutoffs are Wednesday's
    /// and Thursday's. With T+1, Wednesday's borrow fee covers one day and Thursday's three; the
    /// short receives its negative financing rate once a day. At one boundary the models charge
    /// in the order they were given.
    #[test]
    fn a_short_pays_its_borrow_by_settlement_day_and_receives_its_financing() {
        let cutoff = NaiveTime::from_hms_opt(21, 0, 0).unwrap();
        let borrow = BorrowFeeModel::new(DailyAccrual::new(
            cutoff,
            Utc,
            AccrualDays::Settlement {
                calendar: Arc::new(WeekendsOnly),
                lag: 1,
            },
            DayCount::Act360,
        ))
        .with_rates(cfd_instrument_name(), RateSeries::constant(d("0.36")));
        let financing = FinancingModel::new(DailyAccrual::new(
            cutoff,
            Utc,
            AccrualDays::Calendar,
            DayCount::Act365,
        ))
        .with_rates(
            cfd_instrument_name(),
            FinancingRates::new(
                RateSeries::constant(d("0.073")),
                RateSeries::constant(d("-0.0365")),
            ),
        );
        let mut venue =
            make_cfd_venue_charging("200000", vec![Arc::new(borrow), Arc::new(financing)]);
        assert!(cfd_market(&mut venue, "5000", "5000", "5000").is_empty());
        cfd_market_fill(&mut venue, Side::Sell, "1");

        let friday = DateTime::parse_from_rfc3339("2023-11-17T00:00:00Z")
            .unwrap()
            .to_utc();
        let events = venue.advance_time(friday);
        let charged: Vec<_> = charges(&events)
            .iter()
            .map(|(_, flow)| (flow.time_exchange, flow.kind.clone(), flow.amount))
            .collect();

        let wednesday = DateTime::parse_from_rfc3339("2023-11-15T21:00:00Z")
            .unwrap()
            .to_utc();
        let thursday = wednesday + TimeDelta::days(1);
        let borrow_fee = CashFlowKind::BorrowFee {
            rate: Some(d("0.36")),
            quantity: Some(d("25")),
        };
        let financed = CashFlowKind::Financing {
            rate: Some(d("-0.0365")),
            notional: Some(d("125000")),
        };
        // 125,000 notional: 36% / 360 a day is 125, and 3.65% / 365 a day is 12.5.
        assert_eq!(
            charged,
            vec![
                (wednesday, borrow_fee.clone(), d("-125")),
                (wednesday, financed.clone(), d("12.5")),
                (thursday, borrow_fee, d("-375")),
                (thursday, financed, d("12.5")),
            ]
        );
    }

    /// Instruments charged at one boundary are charged in instrument order, whichever order the
    /// venue's positions happen to hash in.
    #[test]
    fn positions_charged_at_one_boundary_are_charged_in_instrument_order() {
        let nas = InstrumentNameExchange::new("nas100_usd");
        let dax = InstrumentNameExchange::new("dax40_usd");
        let mut instruments = instruments_of(cfd_instrument());
        let mut funding = FundingModel::new(TimeDelta::hours(1))
            .with_rates(cfd_instrument_name(), RateSeries::constant(d("0.0001")));
        for name in [&nas, &dax] {
            let mut other = cfd_instrument();
            other.name_exchange = name.clone();
            instruments.insert(name.clone(), other);
            funding = funding.with_rates(name.clone(), RateSeries::constant(d("0.0001")));
        }
        let mut venue = SimulatedVenue::new_market_driven(
            &config_from_balances(vec![funded(usd(), d("1000000"))], FeeModelConfig::default()),
            instruments,
        )
        .with_holding_costs(vec![Arc::new(funding)]);
        advance(&mut venue, time(1));

        for name in [cfd_instrument_name(), nas.clone(), dax.clone()] {
            let fills = venue.apply_market(
                &name,
                MarketObservation::new(market_prices("5000").unwrap()),
                time(1),
            );
            assert!(fills.is_empty());
            let outcome = venue.open_order(request(name, Side::Buy, "1", None));
            assert!(outcome.response.state.is_accepted());
        }

        let events = venue.advance_time(boundary(0));
        let order: Vec<_> = charges(&events)
            .iter()
            .map(|(_, flow)| flow.instrument.clone().unwrap())
            .collect();
        assert_eq!(order, vec![dax, nas, cfd_instrument_name()]);
    }

    /// A long flipped to a short before a boundary is charged there as the short it is.
    #[test]
    fn a_position_flipped_before_a_boundary_is_charged_as_what_it_became() {
        let mut venue = make_cfd_venue_charging("400000", vec![hourly_funding("0.0001")]);
        assert!(cfd_market(&mut venue, "5000", "5000", "5000").is_empty());
        cfd_market_fill(&mut venue, Side::Buy, "1");
        cfd_market_fill(&mut venue, Side::Sell, "2");

        let events = venue.advance_time(boundary(0));
        let charged = charges(&events);
        assert_eq!(charged.len(), 1);
        assert_eq!(
            charged[0].1.amount,
            d("12.5"),
            "a short receives a positive rate"
        );
    }

    /// A model breaking its contract is caught at the first read of its boundary, here the cache
    /// refresh on opening a position, before any driver could wake the venue for it forever.
    #[test]
    #[should_panic(expected = "which is not after")]
    fn a_model_whose_boundary_does_not_advance_panics_rather_than_charging_forever() {
        #[derive(Debug)]
        struct Stuck;
        impl HoldingCostModel for Stuck {
            fn next_boundary(
                &self,
                _: &InstrumentNameExchange,
                after: DateTime<Utc>,
            ) -> Option<DateTime<Utc>> {
                Some(after)
            }
            fn charge(&self, _: &HeldPosition<'_>, _: DateTime<Utc>) -> Option<HoldingCharge> {
                None
            }
        }

        let mut venue = make_cfd_venue_charging("200000", vec![Arc::new(Stuck)]);
        assert!(cfd_market(&mut venue, "5000", "5000", "5000").is_empty());
        cfd_market_fill(&mut venue, Side::Buy, "1");
        let _ = venue.advance_time(time(2));
    }

    // --- Locates and the short-sale restriction ------------------------------------------------

    /// A market-driven CFD venue lending as `table` says, its clock at `time(1)` and its book
    /// 4990 / 5000.
    fn make_cfd_venue_lending(table: ShortabilityTable) -> SimulatedVenue {
        let mut venue = SimulatedVenue::new_market_driven(
            &config_from_balances(
                vec![funded(self::usd(), d("10000000"))],
                FeeModelConfig::default(),
            ),
            instruments_of(cfd_instrument()),
        )
        .with_shortability(Arc::new(table));
        advance(&mut venue, time(1));
        assert!(cfd_market(&mut venue, "4990", "5000", "5000").is_empty());
        venue
    }

    fn lending(shortability: Shortability) -> ShortabilityTable {
        ShortabilityTable::new().with_shortability(cfd_instrument_name(), time(0), shortability)
    }

    /// The refusal an open was answered with, having moved nothing.
    fn borrow_rejection(outcome: &OpenOutcome) -> &BorrowReject {
        assert!(
            outcome.events.is_empty(),
            "a refused short moves nothing, so it owes no events"
        );
        match &outcome.response.state {
            OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
                ApiError::BorrowRejected(reject),
            ))) => reject,
            other => panic!("expected BorrowRejected, got: {other:?}"),
        }
    }

    fn open_cfd(venue: &mut SimulatedVenue, side: Side, quantity: &str) -> OpenOutcome {
        venue.open_order(cfd_request(side, quantity, None))
    }

    #[test]
    fn a_short_of_an_instrument_that_is_not_shortable_is_refused_before_the_ledger_moves() {
        let mut venue = make_cfd_venue_lending(lending(Shortability::new().with_shortable(false)));

        let outcome = open_cfd(&mut venue, Side::Sell, "1");

        let reject = borrow_rejection(&outcome);
        assert_eq!(reject.reason, BorrowRejectReason::NotShortable);
        assert_eq!(reject.venue_code, None);
        assert_eq!(reject.available, None);
        assert!(reject.message.contains("spx500_usd"), "{}", reject.message);
        assert_eq!(free_usd(&venue), d("10000000"));
        assert_eq!(cfd_position(&venue), None);
        assert!(venue.orders_open(&[]).is_empty());
    }

    /// A delisting time at or before the clock refuses the short even when the provider still
    /// calls the instrument shortable; one still ahead does not.
    #[test]
    fn a_short_at_or_after_the_delisting_time_is_refused_and_one_before_it_is_not() {
        let delisted = Shortability::new()
            .with_shortable(true)
            .with_delisting_at(time(1));
        let mut venue = make_cfd_venue_lending(lending(delisted));

        let outcome = open_cfd(&mut venue, Side::Sell, "1");

        let reject = borrow_rejection(&outcome);
        assert_eq!(reject.reason, BorrowRejectReason::NotShortable);
        assert!(reject.message.contains("delisted"), "{}", reject.message);
        assert_eq!(cfd_position(&venue), None);

        let ahead = Shortability::new()
            .with_shortable(true)
            .with_delisting_at(time(2));
        let mut venue = make_cfd_venue_lending(lending(ahead));
        cfd_market_fill(&mut venue, Side::Sell, "1");
        assert!(cfd_position(&venue).is_some(), "not delisted yet");
    }

    #[test]
    fn a_buy_and_a_sell_that_only_reduces_a_long_are_never_refused() {
        let mut venue = make_cfd_venue_lending(lending(Shortability::new().with_shortable(false)));

        cfd_market_fill(&mut venue, Side::Buy, "2");
        cfd_market_fill(&mut venue, Side::Sell, "1");
        cfd_market_fill(&mut venue, Side::Sell, "1");
        assert_eq!(cfd_position(&venue), None);

        let outcome = open_cfd(&mut venue, Side::Sell, "1");
        assert_eq!(
            borrow_rejection(&outcome).reason,
            BorrowRejectReason::NotShortable,
            "once flat, the next sell opens a short"
        );
    }

    #[test]
    fn a_sell_reducing_a_long_that_resting_sells_already_close_opens_a_short() {
        let mut venue = make_cfd_venue_lending(lending(Shortability::new().with_shortable(false)));
        cfd_market_fill(&mut venue, Side::Buy, "2");
        let rested = venue.open_order(cfd_limit("close", Side::Sell, "2", "5200"));
        assert!(rested_open(&rested).filled_quantity.is_zero());

        let outcome = open_cfd(&mut venue, Side::Sell, "1");

        assert_eq!(
            borrow_rejection(&outcome).reason,
            BorrowRejectReason::NotShortable
        );
    }

    /// The lender has 5 in total. The account's own short of 2 and its resting sell of 2 leave 1,
    /// so a sell of 2 is refused saying so, and a sell of 1 is not.
    #[test]
    fn a_short_past_what_is_available_net_of_the_own_short_and_resting_sells_is_refused() {
        let mut venue = make_cfd_venue_lending(lending(
            Shortability::new()
                .with_shortable(true)
                .with_available(d("5")),
        ));
        cfd_market_fill(&mut venue, Side::Sell, "2");
        let rested = venue.open_order(cfd_limit("rest", Side::Sell, "2", "5200"));
        assert!(rested_open(&rested).filled_quantity.is_zero());
        let free = free_usd(&venue);

        let outcome = open_cfd(&mut venue, Side::Sell, "2");

        let reject = borrow_rejection(&outcome);
        assert_eq!(reject.reason, BorrowRejectReason::InventoryUnavailable);
        assert_eq!(reject.available, Some(d("1")));
        assert_eq!(free_usd(&venue), free);
        assert_eq!(
            cfd_position(&venue).map(|(quantity, _)| quantity),
            Some(d("-2"))
        );

        cfd_market_fill(&mut venue, Side::Sell, "1");
        assert_eq!(
            cfd_position(&venue).map(|(quantity, _)| quantity),
            Some(d("-3"))
        );
    }

    #[test]
    fn what_is_available_is_never_reported_below_zero() {
        let mut venue = make_cfd_venue_lending(
            ShortabilityTable::new()
                .with_shortability(cfd_instrument_name(), time(0), Shortability::new())
                .with_shortability(
                    cfd_instrument_name(),
                    time(2),
                    Shortability::new().with_available(d("1")),
                ),
        );
        cfd_market_fill(&mut venue, Side::Sell, "3");
        advance(&mut venue, time(2));

        let outcome = open_cfd(&mut venue, Side::Sell, "1");

        let reject = borrow_rejection(&outcome);
        assert_eq!(reject.reason, BorrowRejectReason::InventoryUnavailable);
        assert_eq!(reject.available, Some(Decimal::ZERO));
    }

    /// From a long of 5, a sell of 9 opens a short of 4 and a sell of 8 one of 3: only the short
    /// part is measured against the 3 available.
    #[test]
    fn a_flip_is_gated_on_the_short_it_opens_only() {
        let mut venue = make_cfd_venue_lending(lending(Shortability::new().with_available(d("3"))));
        cfd_market_fill(&mut venue, Side::Buy, "5");

        let outcome = open_cfd(&mut venue, Side::Sell, "9");
        let reject = borrow_rejection(&outcome);
        assert_eq!(reject.reason, BorrowRejectReason::InventoryUnavailable);
        assert_eq!(reject.available, Some(d("3")));
        assert_eq!(
            cfd_position(&venue).map(|(quantity, _)| quantity),
            Some(d("5"))
        );

        cfd_market_fill(&mut venue, Side::Sell, "8");
        assert_eq!(
            cfd_position(&venue).map(|(quantity, _)| quantity),
            Some(d("-3"))
        );
    }

    #[test]
    fn a_short_sale_restriction_refuses_a_marketable_short_and_lets_one_above_the_bid_rest() {
        let mut venue =
            make_cfd_venue_lending(ShortabilityTable::new().with_short_sale_restriction(
                cfd_instrument_name(),
                time(0),
                time(10),
            ));

        // Reducing a long is not a short sale.
        cfd_market_fill(&mut venue, Side::Buy, "1");
        cfd_market_fill(&mut venue, Side::Sell, "1");

        let market = open_cfd(&mut venue, Side::Sell, "1");
        assert_eq!(
            borrow_rejection(&market).reason,
            BorrowRejectReason::ShortSaleRestricted
        );
        for (cid, limit) in [("at-bid", "4990"), ("below-bid", "4980")] {
            let outcome = venue.open_order(cfd_limit(cid, Side::Sell, "1", limit));
            assert_eq!(
                borrow_rejection(&outcome).reason,
                BorrowRejectReason::ShortSaleRestricted,
                "a sell limit at {limit} crosses the 4990 bid"
            );
        }

        let above = venue.open_order(cfd_limit("above-bid", Side::Sell, "1", "4995"));
        assert!(rested_open(&above).filled_quantity.is_zero());
        assert_eq!(cfd_position(&venue), None);

        // The restriction is read at the venue's clock, so it lifts when its window ends.
        advance(&mut venue, time(10));
        cfd_market_fill(&mut venue, Side::Sell, "1");
        assert_eq!(
            cfd_position(&venue).map(|(quantity, _)| quantity),
            Some(d("-1"))
        );
    }

    /// Whether a market sell is marketable is the fill model's to say, and one that can price it
    /// is refused for the restriction.
    #[test]
    fn a_restricted_market_short_the_fill_model_can_price_is_refused_for_the_restriction() {
        let mut venue =
            make_cfd_venue_lending(ShortabilityTable::new().with_short_sale_restriction(
                cfd_instrument_name(),
                time(0),
                time(10),
            ));
        venue.fill_model = Arc::new(SimFillConfig::Midpoint(crate::fill::MidpointFillModel));

        let outcome = open_cfd(&mut venue, Side::Sell, "1");

        assert_eq!(
            borrow_rejection(&outcome).reason,
            BorrowRejectReason::ShortSaleRestricted
        );
    }

    #[test]
    fn missing_shortability_data_allows_the_short() {
        let mut venue = make_cfd_venue_lending(
            ShortabilityTable::new()
                .with_shortability(
                    cfd_instrument_name(),
                    time(100),
                    Shortability::new().with_shortable(false),
                )
                .with_shortability(
                    InstrumentNameExchange::new("other"),
                    time(0),
                    Shortability::new().with_shortable(false),
                ),
        );

        cfd_market_fill(&mut venue, Side::Sell, "1");

        assert_eq!(
            cfd_position(&venue).map(|(quantity, _)| quantity),
            Some(d("-1"))
        );
    }

    /// Spot lends nothing either way: a sell of base the account does not hold is short of
    /// balance, whatever the provider says about lending.
    #[test]
    fn a_spot_short_is_refused_for_its_balance_not_by_the_provider() {
        let table = ShortabilityTable::new().with_shortability(
            instrument_name(),
            time(0),
            Shortability::new().with_shortable(false),
        );
        let mut venue = make_venue("0", "10000").with_shortability(Arc::new(table));

        let outcome = venue.open_order(sell_request("1", market_prices("50000")));

        match outcome.response.state {
            OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
                ApiError::BalanceInsufficient(..),
            ))) => {}
            other => panic!("expected BalanceInsufficient, got: {other:?}"),
        }
    }

    /// With no price to fill at, a restricted market sell is refused for what it is, unpriceable,
    /// naming which of the two unpriceable causes occurred, rather than for a restriction that
    /// judges a bid it could not fill against.
    #[test]
    fn a_restricted_short_with_no_price_is_refused_as_unpriceable() {
        let reason_of = |fill_model: SimFillConfig, market| {
            let mut venue = make_cfd_venue("10000000", FeeModelConfig::default())
                .with_shortability(Arc::new(
                    ShortabilityTable::new().with_short_sale_restriction(
                        cfd_instrument_name(),
                        time(0),
                        time(10),
                    ),
                ));
            venue.fill_model = Arc::new(fill_model);
            advance(&mut venue, time(1));
            match venue
                .open_order(cfd_request(Side::Sell, "1", market))
                .response
                .state
            {
                OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
                    ApiError::OrderRejected(reason),
                ))) => reason,
                other => panic!("expected the unpriceable OrderRejected, got: {other:?}"),
            }
        };

        let absent = reason_of(SimFillConfig::default(), None);
        assert!(absent.contains("no market snapshot"), "{absent}");
        let empty = reason_of(SimFillConfig::default(), Some(MarketSnapshot::default()));
        assert!(empty.contains("no market price available yet"), "{empty}");

        // A bid alone has no midpoint, so `MidpointFillModel` cannot price the sell.
        let bid_only = MarketSnapshot {
            best_bid: Some(d("4990")),
            ..MarketSnapshot::default()
        };
        let midpoint = reason_of(
            SimFillConfig::Midpoint(crate::fill::MidpointFillModel),
            Some(bid_only),
        );
        assert!(
            midpoint.contains("no market price available yet"),
            "{midpoint}"
        );
    }

    /// The checks apply in their documented order: not shortable before too little to lend,
    /// and too little to lend before the restriction.
    #[test]
    fn the_first_refusal_that_applies_is_the_one_reported() {
        let restricted = |shortability| {
            lending(shortability).with_short_sale_restriction(
                cfd_instrument_name(),
                time(0),
                time(10),
            )
        };

        let mut venue = make_cfd_venue_lending(restricted(
            Shortability::new()
                .with_shortable(false)
                .with_available(Decimal::ZERO),
        ));
        let outcome = open_cfd(&mut venue, Side::Sell, "1");
        assert_eq!(
            borrow_rejection(&outcome).reason,
            BorrowRejectReason::NotShortable
        );

        let mut venue = make_cfd_venue_lending(restricted(
            Shortability::new().with_available(Decimal::ZERO),
        ));
        let outcome = open_cfd(&mut venue, Side::Sell, "1");
        assert_eq!(
            borrow_rejection(&outcome).reason,
            BorrowRejectReason::InventoryUnavailable
        );
    }

    /// A flip from a long opens a short, so a restriction refuses it when it is marketable, while
    /// the sell that only closes the same long goes through.
    #[test]
    fn a_short_sale_restriction_refuses_a_marketable_flip_but_not_a_close() {
        let mut venue =
            make_cfd_venue_lending(ShortabilityTable::new().with_short_sale_restriction(
                cfd_instrument_name(),
                time(0),
                time(10),
            ));
        cfd_market_fill(&mut venue, Side::Buy, "2");

        let outcome = open_cfd(&mut venue, Side::Sell, "3");
        assert_eq!(
            borrow_rejection(&outcome).reason,
            BorrowRejectReason::ShortSaleRestricted
        );
        assert_eq!(
            cfd_position(&venue).map(|(quantity, _)| quantity),
            Some(d("2"))
        );

        cfd_market_fill(&mut venue, Side::Sell, "2");
        assert_eq!(cfd_position(&venue), None);
    }

    // ---------------------------------------------------------------------------------------
    // Market orders held for their instrument's next bar.
    // ---------------------------------------------------------------------------------------

    fn next_bar_config(usdt: &str, price: NextBarPrice) -> MockExecutionConfig {
        MockExecutionConfig {
            market_order_timing: MarketOrderTiming::NextBar(price),
            ..spot_config("10", usdt, FeeModelConfig::default())
        }
    }

    fn ohlc(open: &str, high: &str, low: &str, close: &str) -> MarketBar {
        MarketBar::new(d(open), d(high), d(low), d(close))
    }

    /// Feeds `bar` at `time(seconds)` as a candle feed does: a last price at its close, no size.
    fn feed_bar(
        venue: &mut SimulatedVenue,
        seconds: i64,
        bar: MarketBar,
    ) -> Vec<UnindexedAccountEvent> {
        feed_bar_sized(venue, seconds, bar, MarketDepth::UNKNOWN)
    }

    fn feed_bar_sized(
        venue: &mut SimulatedVenue,
        seconds: i64,
        bar: MarketBar,
        depth: MarketDepth,
    ) -> Vec<UnindexedAccountEvent> {
        let snapshot = MarketSnapshot::from_last_price(Some(bar.close));
        venue.apply_market(
            &instrument_name(),
            MarketObservation::new(snapshot)
                .with_depth(depth)
                .with_bar(Some(bar)),
            time(seconds),
        )
    }

    /// A venue holding market orders for the next bar, fed one bar at `time(1)` that closed at 100.
    fn venue_holding(price: NextBarPrice, usdt: &str) -> SimulatedVenue {
        let mut venue =
            SimulatedVenue::new_market_driven(&next_bar_config(usdt, price), spot_instruments());
        advance(&mut venue, time(1));
        assert!(feed_bar(&mut venue, 1, ohlc("95", "105", "90", "100")).is_empty());
        venue
    }

    fn market_order(
        cid: &str,
        side: Side,
        quantity: &str,
        time_in_force: TimeInForce,
    ) -> OrderRequestOpen<ExchangeId, InstrumentNameExchange> {
        let mut request = request(instrument_name(), side, quantity, None);
        request.key.cid = ClientOrderId::new(cid);
        request.state.time_in_force = time_in_force;
        request
    }

    fn ioc_buy(cid: &str, quantity: &str) -> OrderRequestOpen<ExchangeId, InstrumentNameExchange> {
        market_order(cid, Side::Buy, quantity, TimeInForce::ImmediateOrCancel)
    }

    fn total_base(venue: &SimulatedVenue) -> Decimal {
        venue.balances(&[base()])[0].balance.total
    }

    fn rejection_reason(outcome: &OpenOutcome) -> &str {
        match &outcome.response.state {
            OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
                ApiError::OrderRejected(reason),
            ))) => reason,
            other => panic!("expected an OrderRejected, got: {other:?}"),
        }
    }

    #[test]
    fn a_market_order_held_for_the_next_bar_is_open_and_holds_its_cost_at_the_current_price() {
        let mut venue = venue_holding(NextBarPrice::Open, "10000");

        let outcome = venue.open_order(ioc_buy("held", "1"));

        assert_eq!(
            rested_open(&outcome).filled_quantity,
            Decimal::ZERO,
            "accepted as open, with nothing traded yet"
        );
        assert_eq!(
            outcome.events.len(),
            1,
            "it owes the one balance its hold restates"
        );
        assert_eq!(
            balance_of(&outcome.events[0]).balance.free,
            d("9900"),
            "held at the close the order arrived on"
        );
        assert_eq!(total_quote(&venue), d("10000"), "and nothing paid yet");
        assert!(venue.trades(time(0)).is_empty());
        assert_eq!(venue.orders_open(&[]).len(), 1);
        assert!(venue.account.orders().holds(&instrument_name()));
    }

    #[test]
    fn the_next_bar_fills_a_held_order_at_its_open_and_settles_that_price() {
        let mut venue = venue_holding(NextBarPrice::Open, "10000");
        let _ = venue.open_order(ioc_buy("held", "1"));

        let events = feed_bar(&mut venue, 2, ohlc("102", "110", "98", "108"));

        assert_eq!(
            events.len(),
            4,
            "the balance paid, the one received, the trade, then the order: {events:?}"
        );
        let paid = balance_of(&events[0]);
        assert_eq!(paid.asset, quote());
        assert_eq!(
            (paid.balance.total, paid.balance.free),
            (d("9898"), d("9898")),
            "the hold is released and the fill settled at the open, not the close it was held at"
        );
        assert_eq!(balance_of(&events[1]).asset, base());

        let trade = trade_of(&events[2]);
        assert_eq!(
            (trade.price, trade.quantity, trade.time_exchange),
            (d("102"), d("1"), time(2)),
            "filled at the bar's open, stamped at the bar"
        );
        assert!(
            matches!(
                order_of(&events[3]).state,
                OrderState::Inactive(InactiveOrderState::FullyFilled(_))
            ),
            "{:?}",
            order_of(&events[3]).state
        );

        assert!(venue.orders_open(&[]).is_empty());
        assert!(!venue.account.orders().holds(&instrument_name()));
        assert_eq!(total_base(&venue), d("11"));
        assert_eq!(free_quote(&venue), d("9898"));
    }

    #[test]
    fn adverse_extreme_fills_a_held_buy_at_the_bar_high_and_a_sell_at_its_low() {
        for (side, expected) in [(Side::Buy, "110"), (Side::Sell, "98")] {
            let mut venue = venue_holding(NextBarPrice::AdverseExtreme, "10000");
            let _ = venue.open_order(market_order(
                "held",
                side,
                "1",
                TimeInForce::ImmediateOrCancel,
            ));

            let events = feed_bar(&mut venue, 2, ohlc("102", "110", "98", "108"));

            assert_eq!(trade_of(&events[2]).price, d(expected), "a {side:?}");
        }
    }

    #[test]
    fn a_tick_between_bars_does_not_release_a_held_order() {
        let mut venue = venue_holding(NextBarPrice::Open, "10000");
        let _ = venue.open_order(ioc_buy("held", "1"));

        let ticked = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(traded("101")),
            time(2),
        );

        assert!(ticked.is_empty(), "a tick is not a bar: {ticked:?}");
        assert!(venue.account.orders().holds(&instrument_name()));

        let events = feed_bar(&mut venue, 3, ohlc("103", "104", "102", "103"));
        assert_eq!(
            trade_of(&events[2]).price,
            d("103"),
            "the next bar fills it"
        );
    }

    #[test]
    fn a_held_order_fills_at_the_bar_price_moved_by_the_configured_slippage() {
        let config = MockExecutionConfig {
            slippage: SlippageConfig::fixed(d("0.01")).unwrap(),
            ..next_bar_config("10000", NextBarPrice::Open)
        };
        let mut venue = SimulatedVenue::new_market_driven(&config, spot_instruments());
        advance(&mut venue, time(1));
        assert!(feed_bar(&mut venue, 1, ohlc("95", "105", "90", "100")).is_empty());
        let _ = venue.open_order(ioc_buy("held", "1"));

        let events = feed_bar(&mut venue, 2, ohlc("102", "110", "98", "108"));

        assert_eq!(
            trade_of(&events[2]).price,
            d("103.02"),
            "the open, 1% against the buy"
        );
    }

    #[test]
    fn a_market_order_with_no_bar_to_wait_for_is_rejected_naming_the_setting() {
        // Fed ticks but never a bar: there is no next bar this venue could know to wait for.
        let mut ticked = SimulatedVenue::new_market_driven(
            &next_bar_config("10000", NextBarPrice::Open),
            spot_instruments(),
        );
        advance(&mut ticked, time(1));
        assert!(
            ticked
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(traded("100")),
                    time(1)
                )
                .is_empty()
        );
        // No feed at all.
        let mut request_priced = SimulatedVenue::new(
            &next_bar_config("10000", NextBarPrice::Open),
            spot_instruments(),
        );

        for (venue, request) in [
            (&mut ticked, ioc_buy("held", "1")),
            (&mut request_priced, buy_request("1", market_prices("100"))),
        ] {
            let outcome = venue.open_order(request);

            assert!(outcome.events.is_empty());
            assert!(
                rejection_reason(&outcome).contains("MarketOrderTiming::NextBar"),
                "{}",
                rejection_reason(&outcome)
            );
            assert_eq!(
                free_quote(venue),
                d("10000"),
                "a refused order holds nothing"
            );
        }
    }

    #[test]
    fn a_held_order_the_account_cannot_cover_is_refused_on_arrival() {
        let mut venue = venue_holding(NextBarPrice::Open, "99");

        let outcome = venue.open_order(ioc_buy("held", "1"));

        assert!(
            matches!(
                outcome.response.state,
                OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
                    ApiError::BalanceInsufficient(..)
                )))
            ),
            "{:?}",
            outcome.response.state
        );
        assert!(!venue.account.orders().holds(&instrument_name()));
    }

    #[test]
    fn a_held_order_is_cancelled_like_a_resting_one_and_releases_its_hold() {
        let mut venue = venue_holding(NextBarPrice::Open, "10000");
        let request = ioc_buy("held", "1");
        let key = request.key.clone();
        let _ = venue.open_order(request);

        let cancelled = venue.cancel_order(OrderEvent {
            key,
            state: RequestCancel { id: None },
        });

        assert!(cancelled.response.state.is_ok());
        assert_eq!(free_quote(&venue), d("10000"));
        assert!(!venue.account.orders().holds(&instrument_name()));
        assert!(
            feed_bar(&mut venue, 2, ohlc("102", "110", "98", "108")).is_empty(),
            "the next bar has nothing left to fill"
        );
    }

    /// A price on a held market order is ignored, as on arrival: the order is held priceless, so
    /// a tick through that price cannot match it as a limit, and a cancel leaves nothing held.
    #[test]
    fn a_held_market_order_carrying_a_price_is_held_without_it() {
        let mut venue = venue_holding(NextBarPrice::Open, "10000");
        let request = priced_market_order(Side::Buy, "200", None);
        let key = request.key.clone();

        let outcome = venue.open_order(request);
        assert_eq!(rested_open(&outcome).filled_quantity, Decimal::ZERO);
        assert_eq!(outcome.response.price, None, "reported as it is held");
        assert_eq!(venue.orders_open(&[])[0].price, None);

        let ticked = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(traded("150")),
            time(2),
        );
        assert!(
            ticked.is_empty(),
            "a tick below the stray price matches nothing: {ticked:?}"
        );

        let cancelled = venue.cancel_order(OrderEvent {
            key,
            state: RequestCancel { id: None },
        });
        assert!(cancelled.response.state.is_ok());
        assert!(!venue.account.orders().holds(&instrument_name()));
    }

    /// A held order whose deadline the bar reaches is retired by the sweep before the bar can
    /// release it, and leaves the held index with it.
    #[test]
    fn a_held_order_whose_deadline_the_bar_reaches_expires_unfilled() {
        let mut venue = venue_holding(NextBarPrice::Open, "10000");
        let _ = venue.open_order(market_order(
            "gtd",
            Side::Buy,
            "1",
            TimeInForce::GoodTillDate { expiry: time(2) },
        ));

        let events = feed_bar(&mut venue, 2, ohlc("102", "110", "98", "108"));

        assert_eq!(
            events.len(),
            2,
            "the released hold, then the order: {events:?}"
        );
        assert!(
            matches!(
                order_of(&events[1]).state,
                OrderState::Inactive(InactiveOrderState::Expired(_))
            ),
            "{:?}",
            order_of(&events[1]).state
        );
        assert!(venue.trades(time(0)).is_empty());
        assert_eq!(free_quote(&venue), d("10000"));
        assert!(!venue.account.orders().holds(&instrument_name()));
    }

    /// A held spot sell holds the base it would deliver, and the bar settles exactly that.
    #[test]
    fn a_held_spot_sell_holds_the_base_it_would_deliver() {
        let mut venue = venue_holding(NextBarPrice::Open, "10000");
        let free_base = |venue: &SimulatedVenue| venue.balances(&[base()])[0].balance.free;

        let _ = venue.open_order(market_order(
            "sell",
            Side::Sell,
            "1",
            TimeInForce::ImmediateOrCancel,
        ));
        assert_eq!(free_base(&venue), d("9"));
        assert_eq!(total_base(&venue), d("10"), "and nothing delivered yet");

        let events = feed_bar(&mut venue, 2, ohlc("102", "110", "98", "108"));

        assert_eq!(trade_of(&events[2]).price, d("102"));
        assert_eq!(total_base(&venue), d("9"));
        assert_eq!(free_base(&venue), d("9"));
    }

    #[test]
    fn a_held_order_the_account_can_no_longer_afford_at_the_bar_is_cancelled() {
        // 100 is held at the close the order arrived on, and the bar opens at 110.
        let mut venue = venue_holding(NextBarPrice::Open, "105");
        let _ = venue.open_order(ioc_buy("held", "1"));
        assert_eq!(free_quote(&venue), d("5"));

        let events = feed_bar(&mut venue, 2, ohlc("110", "112", "108", "111"));

        assert_eq!(
            events.len(),
            2,
            "the released hold, then the order: {events:?}"
        );
        assert_eq!(balance_of(&events[0]).balance.free, d("105"));
        assert!(
            matches!(
                &order_of(&events[1]).state,
                OrderState::Inactive(InactiveOrderState::Cancelled(cancelled))
                    if cancelled.filled_quantity == Some(Decimal::ZERO)
            ),
            "{:?}",
            order_of(&events[1]).state
        );
        assert!(venue.trades(time(0)).is_empty());
        assert_eq!(free_quote(&venue), d("105"));
    }

    #[test]
    fn a_bar_with_less_size_than_a_held_order_fills_immediate_or_cancel_in_part_and_kills_fill_or_kill()
     {
        let bar = ohlc("102", "110", "98", "108");

        let mut immediate = venue_holding(NextBarPrice::Open, "10000");
        let _ = immediate.open_order(ioc_buy("ioc", "1"));
        let events = feed_bar_sized(&mut immediate, 2, bar, sized("0.4"));
        assert_eq!(trade_of(&events[2]).quantity, d("0.4"));
        assert!(
            matches!(
                &order_of(&events[3]).state,
                OrderState::Inactive(InactiveOrderState::Cancelled(cancelled))
                    if cancelled.filled_quantity == Some(d("0.4"))
            ),
            "immediate-or-cancel keeps what the bar gave it: {:?}",
            order_of(&events[3]).state
        );
        assert_eq!(free_quote(&immediate), d("10000") - d("40.8"));

        let mut all_or_nothing = venue_holding(NextBarPrice::Open, "10000");
        let _ =
            all_or_nothing.open_order(market_order("fok", Side::Buy, "1", TimeInForce::FillOrKill));
        let events = feed_bar_sized(&mut all_or_nothing, 2, bar, sized("0.4"));
        assert_eq!(
            events.len(),
            2,
            "the released hold, then the order: {events:?}"
        );
        assert!(all_or_nothing.trades(time(0)).is_empty());
        assert_eq!(free_quote(&all_or_nothing), d("10000"));
    }

    /// Fill-or-kill kills only a part: a bar with size for the whole held order fills it.
    #[test]
    fn a_bar_with_size_for_the_whole_held_order_fills_fill_or_kill() {
        let mut venue = venue_holding(NextBarPrice::Open, "10000");
        let _ = venue.open_order(market_order("fok", Side::Buy, "1", TimeInForce::FillOrKill));

        let events = feed_bar_sized(&mut venue, 2, ohlc("102", "110", "98", "108"), sized("1"));

        assert_eq!(trade_of(&events[2]).quantity, d("1"));
        assert!(
            matches!(
                order_of(&events[3]).state,
                OrderState::Inactive(InactiveOrderState::FullyFilled(_))
            ),
            "{:?}",
            order_of(&events[3]).state
        );
    }

    #[test]
    fn orders_held_on_one_instrument_fill_in_arrival_order_against_one_size() {
        let mut venue = venue_holding(NextBarPrice::Open, "10000");
        let _ = venue.open_order(ioc_buy("first", "1"));
        let _ = venue.open_order(ioc_buy("second", "1"));

        let events = feed_bar_sized(&mut venue, 2, ohlc("102", "110", "98", "108"), sized("1.5"));

        let fills = events
            .iter()
            .filter_map(|event| match &event.kind {
                AccountEventKind::Trade(trade) => Some((
                    trade.client_order_id.clone().unwrap().0.to_string(),
                    trade.quantity,
                )),
                _ => None,
            })
            .collect::<Vec<_>>();
        assert_eq!(
            fills,
            [
                ("first".to_string(), d("1")),
                ("second".to_string(), d("0.5"))
            ],
            "earliest first, and the second gets what the first left"
        );
    }

    #[test]
    fn expiring_the_held_orders_retires_each_as_expired_and_releases_its_hold() {
        let mut venue = venue_holding(NextBarPrice::Open, "10000");
        let _ = venue.open_order(ioc_buy("held", "1"));

        let events = venue.expire_held(time(5));

        assert_eq!(
            events.len(),
            2,
            "the released hold, then the order: {events:?}"
        );
        assert_eq!(balance_of(&events[0]).balance.free, d("10000"));
        let order = order_of(&events[1]);
        assert!(
            matches!(
                &order.state,
                OrderState::Inactive(InactiveOrderState::Expired(expired))
                    if expired.filled_quantity == Some(Decimal::ZERO)
                        && expired.time_exchange == time(5)
            ),
            "{:?}",
            order.state
        );
        assert!(venue.orders_open(&[]).is_empty());
        assert!(
            venue.expire_held(time(6)).is_empty(),
            "nothing is held twice"
        );
        assert!(feed_bar(&mut venue, 7, ohlc("102", "110", "98", "108")).is_empty());
    }

    #[test]
    fn a_limit_order_is_not_held_for_the_next_bar() {
        let mut venue = venue_holding(NextBarPrice::Open, "10000");

        let outcome = venue.open_order(limit_request("limit", Side::Buy, "1", "101", gtc()));

        assert_eq!(
            filled_trade(&outcome).price,
            d("100"),
            "a marketable limit still fills on arrival"
        );
        assert!(!venue.account.orders().holds(&instrument_name()));
    }

    // ---------------------------------------------------------------------------------------
    // Market orders on a stale market.
    // ---------------------------------------------------------------------------------------

    fn stale_config(max_age: Duration) -> MockExecutionConfig {
        MockExecutionConfig {
            stale_market: StaleMarketPolicy::Wait { max_age },
            ..spot_config("10", "10000", FeeModelConfig::default())
        }
    }

    /// Ten seconds: a market last observed fresh at `time(1)` is stale from `time(12)`.
    const MAX_AGE: Duration = Duration::from_secs(10);

    /// A venue waiting out markets more than [`MAX_AGE`] old, fed a trade at 100 at `time(1)`.
    fn venue_waiting() -> SimulatedVenue {
        let mut venue =
            SimulatedVenue::new_market_driven(&stale_config(MAX_AGE), spot_instruments());
        advance(&mut venue, time(1));
        assert!(observe(&mut venue, 1, traded("100")).is_empty());
        venue
    }

    /// Feeds a fresh observation of `snapshot` at `time(seconds)`.
    fn observe(
        venue: &mut SimulatedVenue,
        seconds: i64,
        snapshot: MarketSnapshot,
    ) -> Vec<UnindexedAccountEvent> {
        venue.apply_market(
            &instrument_name(),
            MarketObservation::new(snapshot),
            time(seconds),
        )
    }

    /// Feeds an observation of `snapshot` at `time(seconds)` that carries its price forward
    /// without anything having traded, as a zero-volume bar does.
    fn observe_idle(
        venue: &mut SimulatedVenue,
        seconds: i64,
        snapshot: MarketSnapshot,
    ) -> Vec<UnindexedAccountEvent> {
        venue.apply_market(
            &instrument_name(),
            MarketObservation::new(snapshot).with_fresh(false),
            time(seconds),
        )
    }

    fn gtc_buy(cid: &str, quantity: &str) -> OrderRequestOpen<ExchangeId, InstrumentNameExchange> {
        market_order(cid, Side::Buy, quantity, gtc())
    }

    fn trades_in(
        events: &[UnindexedAccountEvent],
    ) -> Vec<&Trade<AssetNameExchange, InstrumentNameExchange>> {
        events
            .iter()
            .filter_map(|event| match &event.kind {
                AccountEventKind::Trade(trade) => Some(trade),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn a_market_observed_fresh_within_the_max_age_fills_on_arrival() {
        let mut venue = venue_waiting();
        // Exactly `MAX_AGE` old is still fresh.
        advance(&mut venue, time(11));

        let outcome = venue.open_order(gtc_buy("fresh", "1"));

        assert_eq!(filled_trade(&outcome).price, d("100"));
        assert!(!venue.account.orders().holds(&instrument_name()));
    }

    #[test]
    fn a_market_order_on_a_stale_market_waits_open_holding_its_cost() {
        let mut venue = venue_waiting();
        advance(&mut venue, time(12));

        let outcome = venue.open_order(gtc_buy("waiting", "1"));

        assert_eq!(rested_open(&outcome).filled_quantity, Decimal::ZERO);
        assert_eq!(
            outcome.events.len(),
            1,
            "it owes the one balance its hold restates"
        );
        assert_eq!(
            balance_of(&outcome.events[0]).balance.free,
            d("9900"),
            "held at the stale price it arrived on"
        );
        assert!(venue.trades(time(0)).is_empty());
        assert!(venue.account.orders().holds(&instrument_name()));
    }

    #[test]
    fn the_next_fresh_observation_fills_a_waiting_order_at_its_price() {
        let mut venue = venue_waiting();
        advance(&mut venue, time(12));
        let _ = venue.open_order(gtc_buy("waiting", "1"));

        let events = observe(&mut venue, 20, traded("105"));

        assert_eq!(
            events.len(),
            4,
            "the balance paid, the one received, the trade, then the order: {events:?}"
        );
        assert_eq!(
            balance_of(&events[0]).balance.free,
            d("9895"),
            "the hold is released and the fill settled at the fresh price"
        );
        let trade = trade_of(&events[2]);
        assert_eq!(
            (trade.price, trade.quantity, trade.time_exchange),
            (d("105"), d("1"), time(20)),
            "filled at the observation's price, stamped at it"
        );
        assert!(matches!(
            order_of(&events[3]).state,
            OrderState::Inactive(InactiveOrderState::FullyFilled(_))
        ));
        assert!(!venue.account.orders().holds(&instrument_name()));
        assert_eq!(total_base(&venue), d("11"));
    }

    #[test]
    fn a_waiting_order_fills_after_the_resting_orders_its_observation_crosses() {
        let mut venue = venue_waiting();
        let _ = venue.open_order(limit_request("resting", Side::Buy, "1", "99", gtc()));
        advance(&mut venue, time(12));
        let _ = venue.open_order(gtc_buy("waiting", "1"));

        let events = observe(&mut venue, 20, traded("98"));

        let prices = trades_in(&events)
            .iter()
            .map(|trade| (trade.client_order_id.clone(), trade.price))
            .collect::<Vec<_>>();
        assert_eq!(
            prices,
            vec![
                (Some(ClientOrderId::new("resting")), d("99")),
                (Some(ClientOrderId::new("waiting")), d("98")),
            ],
            "the resting order was crossed by the observation, the waiting one arrived after it"
        );
    }

    #[test]
    fn an_observation_that_is_not_fresh_neither_refreshes_the_market_nor_releases_an_order() {
        let mut venue = venue_waiting();
        // Carries a price forward at `time(5)`, but the market was last fresh at `time(1)`.
        assert!(observe_idle(&mut venue, 5, traded("101")).is_empty());
        advance(&mut venue, time(12));

        let outcome = venue.open_order(gtc_buy("waiting", "1"));
        assert_eq!(
            balance_of(&outcome.events[0]).balance.free,
            d("9899"),
            "it waits, holding the price the idle observation carried"
        );

        assert!(observe_idle(&mut venue, 13, traded("102")).is_empty());
        assert!(venue.account.orders().holds(&instrument_name()));

        let events = observe(&mut venue, 14, traded("103"));
        assert_eq!(trade_of(&events[2]).price, d("103"));
    }

    #[test]
    fn a_market_never_observed_fresh_is_stale() {
        let mut venue =
            SimulatedVenue::new_market_driven(&stale_config(MAX_AGE), spot_instruments());
        advance(&mut venue, time(1));
        assert!(observe_idle(&mut venue, 1, traded("100")).is_empty());

        let outcome = venue.open_order(ioc_buy("immediate", "1"));
        let reason = rejection_reason(&outcome);
        assert!(reason.contains("never observed fresh"), "{reason}");

        let outcome = venue.open_order(gtc_buy("waiting", "1"));
        assert_eq!(rested_open(&outcome).filled_quantity, Decimal::ZERO);
    }

    #[test]
    fn an_immediate_or_cancel_or_fill_or_kill_order_on_a_stale_market_is_rejected_naming_the_policy()
     {
        for time_in_force in [TimeInForce::ImmediateOrCancel, TimeInForce::FillOrKill] {
            let mut venue = venue_waiting();
            advance(&mut venue, time(12));

            let outcome = venue.open_order(market_order("now", Side::Buy, "1", time_in_force));

            assert!(outcome.events.is_empty());
            let reason = rejection_reason(&outcome);
            assert!(
                reason.contains("StaleMarketPolicy::Wait")
                    && reason.contains(&time(1).to_string())
                    && reason.contains(&time_in_force.to_string()),
                "{reason}"
            );
            assert_eq!(
                free_quote(&venue),
                d("10000"),
                "a refused order holds nothing"
            );
            assert!(!venue.account.orders().holds(&instrument_name()));
        }
    }

    #[test]
    fn a_market_order_on_an_unpriced_instrument_is_rejected_as_unpriceable_not_as_stale() {
        let mut venue =
            SimulatedVenue::new_market_driven(&stale_config(MAX_AGE), spot_instruments());
        advance(&mut venue, time(1));
        assert!(observe(&mut venue, 1, MarketSnapshot::default()).is_empty());

        for request in [gtc_buy("waiting", "1"), ioc_buy("immediate", "1")] {
            let outcome = venue.open_order(request);

            let reason = rejection_reason(&outcome);
            assert!(
                reason.contains("cannot price") && !reason.contains("StaleMarketPolicy"),
                "{reason}"
            );
        }
    }

    #[test]
    fn a_venue_with_no_market_feed_rejects_market_orders_naming_the_policy() {
        let mut venue = SimulatedVenue::new(&stale_config(MAX_AGE), spot_instruments());

        let outcome = venue.open_order(buy_request("1", market_prices("100")));

        assert!(
            rejection_reason(&outcome).contains("StaleMarketPolicy::Wait needs a market feed"),
            "{}",
            rejection_reason(&outcome)
        );
        assert_eq!(free_quote(&venue), d("10000"));
    }

    #[test]
    fn a_max_age_longer_than_any_run_never_makes_a_market_stale() {
        let mut venue =
            SimulatedVenue::new_market_driven(&stale_config(Duration::MAX), spot_instruments());
        advance(&mut venue, time(1));
        assert!(observe(&mut venue, 1, traded("100")).is_empty());
        advance(&mut venue, time(1_000_000));

        let outcome = venue.open_order(ioc_buy("immediate", "1"));

        assert_eq!(filled_trade(&outcome).price, d("100"));
    }

    #[test]
    fn a_waiting_order_the_fresh_market_cannot_price_is_cancelled_and_releases_its_hold() {
        let mut venue = venue_waiting();
        advance(&mut venue, time(12));
        let _ = venue.open_order(gtc_buy("waiting", "1"));

        // A bid alone: nothing a buy can be priced from.
        let events = observe(
            &mut venue,
            20,
            MarketSnapshot::new(Some(d("99")), None, None),
        );

        assert_eq!(
            events.len(),
            2,
            "the released hold, then the order: {events:?}"
        );
        assert_eq!(balance_of(&events[0]).balance.free, d("10000"));
        assert!(matches!(
            &order_of(&events[1]).state,
            OrderState::Inactive(InactiveOrderState::Cancelled(cancelled))
                if cancelled.filled_quantity == Some(Decimal::ZERO)
        ));
        assert!(!venue.account.orders().holds(&instrument_name()));
    }

    #[test]
    fn only_a_fresh_observation_releases_a_waiting_order_never_the_clock() {
        let mut venue = venue_waiting();
        advance(&mut venue, time(12));
        let _ = venue.open_order(gtc_buy("waiting", "1"));

        advance(&mut venue, time(1_000));

        assert!(venue.account.orders().holds(&instrument_name()));
        assert!(venue.trades(time(0)).is_empty());
    }

    #[test]
    fn a_waiting_order_still_waiting_at_the_end_of_the_data_expires() {
        let mut venue = venue_waiting();
        advance(&mut venue, time(12));
        let _ = venue.open_order(gtc_buy("waiting", "1"));

        let events = venue.expire_held(time(30));

        assert_eq!(events.len(), 2, "{events:?}");
        assert_eq!(balance_of(&events[0]).balance.free, d("10000"));
        assert!(matches!(
            order_of(&events[1]).state,
            OrderState::Inactive(InactiveOrderState::Expired(_))
        ));
    }

    #[test]
    fn only_a_bar_released_under_next_bar_fills_ahead_of_its_observation() {
        let bar = ohlc("102", "110", "98", "108");
        let fresh_bar = MarketObservation::new(traded("108")).with_bar(Some(bar));
        let idle_bar = fresh_bar.with_fresh(false);
        let tick = MarketObservation::new(traded("108"));

        // Waiting for a fresh observation, which it follows as a resting fill does.
        let mut waiting = venue_waiting();
        advance(&mut waiting, time(12));
        let _ = waiting.open_order(gtc_buy("waiting", "1"));
        assert!(waiting.account.orders().holds(&instrument_name()));
        assert!(!waiting.fills_ahead_of(&instrument_name(), &fresh_bar));

        // Held for the next bar: any bar releases it, but nothing else does.
        let mut held = venue_holding(NextBarPrice::Open, "10000");
        assert!(
            !held.fills_ahead_of(&instrument_name(), &fresh_bar),
            "nothing held yet"
        );
        let _ = held.open_order(ioc_buy("held", "1"));
        assert!(held.fills_ahead_of(&instrument_name(), &fresh_bar));
        assert!(held.fills_ahead_of(&instrument_name(), &idle_bar));
        assert!(!held.fills_ahead_of(&instrument_name(), &tick));

        // Both: only a bar something traded in releases it.
        let mut both = venue_holding_fresh_bars();
        let _ = both.open_order(gtc_buy("held", "1"));
        assert!(both.fills_ahead_of(&instrument_name(), &fresh_bar));
        assert!(!both.fills_ahead_of(&instrument_name(), &idle_bar));
    }

    /// A venue holding market orders for the next bar something traded in, fed one at `time(1)`
    /// that closed at 100.
    fn venue_holding_fresh_bars() -> SimulatedVenue {
        let config = MockExecutionConfig {
            stale_market: StaleMarketPolicy::Wait { max_age: MAX_AGE },
            ..next_bar_config("10000", NextBarPrice::Open)
        };
        let mut venue = SimulatedVenue::new_market_driven(&config, spot_instruments());
        advance(&mut venue, time(1));
        assert!(feed_bar(&mut venue, 1, ohlc("95", "105", "90", "100")).is_empty());
        venue
    }

    #[test]
    fn under_next_bar_an_idle_bar_cancels_held_immediate_orders_and_leaves_the_rest_held() {
        let mut venue = venue_holding_fresh_bars();
        let _ = venue.open_order(ioc_buy("immediate", "1"));
        let _ = venue.open_order(market_order("all", Side::Buy, "1", TimeInForce::FillOrKill));
        let _ = venue.open_order(gtc_buy("patient", "1"));

        let bar = ohlc("100", "100", "100", "100");
        let snapshot = MarketSnapshot::from_last_price(Some(bar.close));
        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(snapshot)
                .with_bar(Some(bar))
                .with_fresh(false),
            time(2),
        );

        assert_eq!(
            events.len(),
            4,
            "a released hold and a cancel for each: {events:?}"
        );
        for (order, cid) in [(&events[1], "immediate"), (&events[3], "all")] {
            let order = order_of(order);
            assert_eq!(order.key.cid, ClientOrderId::new(cid));
            assert!(matches!(
                &order.state,
                OrderState::Inactive(InactiveOrderState::Cancelled(cancelled))
                    if cancelled.filled_quantity == Some(Decimal::ZERO)
            ));
        }
        assert_eq!(
            free_quote(&venue),
            d("9900"),
            "only the patient order's hold remains"
        );
        assert_eq!(
            venue.account.orders().held_on(&instrument_name()),
            [ClientOrderId::new("patient")]
        );

        let events = feed_bar(&mut venue, 3, ohlc("103", "104", "102", "103"));
        assert_eq!(
            trade_of(&events[2]).price,
            d("103"),
            "the next bar something traded in fills it at its open"
        );
    }

    #[test]
    fn under_next_bar_an_immediate_order_on_a_stale_market_is_rejected_and_a_patient_one_held() {
        let mut venue = venue_holding_fresh_bars();
        advance(&mut venue, time(12));

        let outcome = venue.open_order(ioc_buy("immediate", "1"));
        assert!(
            rejection_reason(&outcome).contains("StaleMarketPolicy::Wait"),
            "{}",
            rejection_reason(&outcome)
        );

        let outcome = venue.open_order(gtc_buy("patient", "1"));
        assert_eq!(rested_open(&outcome).filled_quantity, Decimal::ZERO);
        assert!(venue.account.orders().holds(&instrument_name()));
    }

    // ---------------------------------------------------------------------------------------
    // Limit orders on a stale market.
    // ---------------------------------------------------------------------------------------

    fn gtc_limit(
        cid: &str,
        side: Side,
        quantity: &str,
        limit: &str,
    ) -> OrderRequestOpen<ExchangeId, InstrumentNameExchange> {
        limit_request(cid, side, quantity, limit, gtc())
    }

    fn post_only() -> TimeInForce {
        TimeInForce::GoodUntilCancelled { post_only: true }
    }

    /// The orders resting on the book for matching on `side`, best first.
    fn resting_on(venue: &SimulatedVenue, side: Side) -> Vec<ClientOrderId> {
        venue
            .account
            .orders()
            .resting(&instrument_name(), side)
            .map(|order| order.key.cid.clone())
            .collect()
    }

    #[test]
    fn a_limit_order_on_a_stale_market_waits_open_holding_what_it_would_cost_arriving_now() {
        // The stale market is 100: a buy at 105 would take it, capped at the limit, and a buy at
        // 95 would rest at its limit.
        for (limit, free) in [("105", "9900"), ("95", "9905")] {
            let mut venue = venue_waiting();
            advance(&mut venue, time(12));

            let outcome = venue.open_order(gtc_limit("waiting", Side::Buy, "1", limit));

            assert_eq!(rested_open(&outcome).filled_quantity, Decimal::ZERO);
            assert_eq!(outcome.events.len(), 1, "{:?}", outcome.events);
            assert_eq!(balance_of(&outcome.events[0]).balance.free, d(free));
            assert!(venue.trades(time(0)).is_empty());
            assert!(venue.account.orders().holds(&instrument_name()));
            assert!(
                resting_on(&venue, Side::Buy).is_empty(),
                "held, so nothing matches it"
            );
            assert_eq!(
                venue
                    .account
                    .orders()
                    .get(&ClientOrderId::new("waiting"))
                    .unwrap()
                    .price,
                Some(d(limit)),
                "held with its limit"
            );
        }
    }

    #[test]
    fn a_held_limit_order_the_fresh_market_crosses_fills_as_a_taker_at_the_fresh_price() {
        let mut venue = venue_waiting();
        advance(&mut venue, time(12));
        let _ = venue.open_order(gtc_limit("waiting", Side::Buy, "1", "105"));

        let events = observe(&mut venue, 20, traded("102"));

        assert_eq!(events.len(), 4, "{events:?}");
        assert_eq!(balance_of(&events[0]).balance.free, d("9898"));
        let trade = trade_of(&events[2]);
        assert_eq!(
            (trade.price, trade.quantity, trade.time_exchange),
            (d("102"), d("1"), time(20)),
            "at the fresh market, better than its limit, stamped at the observation"
        );
        assert!(matches!(
            &order_of(&events[3]).state,
            OrderState::Inactive(InactiveOrderState::FullyFilled(filled))
                if filled.avg_price == Some(d("102"))
        ));
        assert!(!venue.account.orders().holds(&instrument_name()));
        assert!(venue.account.orders().is_empty());
        assert_eq!(total_base(&venue), d("11"));
    }

    #[test]
    fn a_held_limit_order_is_capped_at_its_limit_however_far_the_slippage_moves_it() {
        let config = MockExecutionConfig {
            slippage: SlippageConfig::fixed(d("0.1")).unwrap(),
            ..stale_config(MAX_AGE)
        };
        let mut venue = SimulatedVenue::new_market_driven(&config, spot_instruments());
        advance(&mut venue, time(1));
        assert!(observe(&mut venue, 1, traded("100")).is_empty());
        advance(&mut venue, time(12));
        let _ = venue.open_order(gtc_limit("waiting", Side::Buy, "1", "105"));

        // 102 slipped by 10% is 112.2, over the limit.
        let events = observe(&mut venue, 20, traded("102"));

        assert_eq!(trade_of(&events[2]).price, d("105"));
    }

    #[test]
    fn a_held_limit_order_the_fresh_market_does_not_cross_joins_the_book_at_its_limit() {
        let mut venue = venue_waiting();
        advance(&mut venue, time(12));
        let _ = venue.open_order(gtc_limit("waiting", Side::Buy, "1", "105"));

        let events = observe(&mut venue, 20, traded("110"));

        assert_eq!(
            events.len(),
            2,
            "the hold restated, then the order: {events:?}"
        );
        assert_eq!(
            balance_of(&events[0]).balance.free,
            d("9895"),
            "now held at its limit, as the maker it rests as"
        );
        let order = order_of(&events[1]);
        assert!(matches!(
            &order.state,
            OrderState::Active(ActiveOrderState::Open(open))
                if open.time_exchange == time(20) && open.filled_quantity.is_zero()
        ));
        assert!(!venue.account.orders().holds(&instrument_name()));
        assert_eq!(
            resting_on(&venue, Side::Buy),
            [ClientOrderId::new("waiting")]
        );

        let events = observe(&mut venue, 21, traded("104"));
        assert_eq!(
            trade_of(&events[2]).price,
            d("105"),
            "resting, it fills at its limit"
        );
    }

    #[test]
    fn a_limit_order_on_a_stale_market_is_decided_by_the_fresh_market_not_the_stale_one() {
        // At the stale 100 a buy at 101 crosses and a buy at 99 does not. The fresh 95 crosses
        // both, and both are filled at it: the one that looked passive is not filled worse.
        let mut venue = venue_waiting();
        advance(&mut venue, time(12));
        let _ = venue.open_order(gtc_limit("crossing", Side::Buy, "1", "101"));
        let _ = venue.open_order(gtc_limit("passive", Side::Buy, "1", "99"));

        let events = observe(&mut venue, 20, traded("95"));

        let prices = trades_in(&events)
            .iter()
            .map(|trade| (trade.client_order_id.clone(), trade.price))
            .collect::<Vec<_>>();
        assert_eq!(
            prices,
            vec![
                (Some(ClientOrderId::new("crossing")), d("95")),
                (Some(ClientOrderId::new("passive")), d("95")),
            ],
            "earliest arrival first"
        );
    }

    #[test]
    fn a_held_limit_order_the_fresh_size_cannot_fill_rests_the_rest_at_its_limit() {
        let mut venue = venue_waiting();
        advance(&mut venue, time(12));
        let _ = venue.open_order(gtc_limit("waiting", Side::Buy, "1", "105"));

        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("101", "102"))
                .with_depth(MarketDepth::new(Some(d("1")), Some(d("0.4")))),
            time(20),
        );

        assert_eq!(events.len(), 4, "{events:?}");
        assert_eq!(
            balance_of(&events[0]).balance.free,
            d("9896.20"),
            "0.4 paid at 102 and 0.6 held at 105: 10000 - 40.8 - 63"
        );
        let trade = trade_of(&events[2]);
        assert_eq!(
            (trade.price, trade.quantity, trade.order_filled_quantity),
            (d("102"), d("0.4"), Some(d("0.4")))
        );
        assert!(matches!(
            &order_of(&events[3]).state,
            OrderState::Active(ActiveOrderState::Open(open)) if open.filled_quantity == d("0.4")
        ));
        assert_eq!(
            resting_on(&venue, Side::Buy),
            [ClientOrderId::new("waiting")]
        );

        let events = observe(&mut venue, 21, traded("104"));
        let trade = trade_of(&events[2]);
        assert_eq!(
            (trade.price, trade.quantity, trade.order_filled_quantity),
            (d("105"), d("0.6"), Some(d("1"))),
            "the remainder fills at its limit, as the maker"
        );
        assert_eq!(free_quote(&venue), d("9896.20"));
    }

    #[test]
    fn a_held_post_only_order_the_fresh_market_crosses_is_cancelled_and_one_it_does_not_rests() {
        let mut venue = venue_waiting();
        advance(&mut venue, time(12));
        let outcome = venue.open_order(limit_request("maker", Side::Buy, "1", "105", post_only()));
        assert_eq!(
            balance_of(&outcome.events[0]).balance.free,
            d("9895"),
            "held at its limit, as the maker it promises to be"
        );

        let events = observe(&mut venue, 20, traded("104"));

        assert_eq!(events.len(), 2, "{events:?}");
        assert_eq!(balance_of(&events[0]).balance.free, d("10000"));
        assert!(matches!(
            &order_of(&events[1]).state,
            OrderState::Inactive(InactiveOrderState::Cancelled(cancelled))
                if cancelled.filled_quantity == Some(Decimal::ZERO)
        ));

        advance(&mut venue, time(40));
        let _ = venue.open_order(limit_request("passive", Side::Buy, "1", "100", post_only()));
        let events = observe(&mut venue, 41, traded("104"));
        assert!(matches!(
            &order_of(&events[1]).state,
            OrderState::Active(ActiveOrderState::Open(_))
        ));
        assert_eq!(
            resting_on(&venue, Side::Buy),
            [ClientOrderId::new("passive")]
        );
    }

    #[test]
    fn an_immediate_or_cancel_or_fill_or_kill_limit_on_a_stale_market_is_rejected_whether_or_not_it_crosses()
     {
        for (time_in_force, limit) in [
            (TimeInForce::ImmediateOrCancel, "105"),
            (TimeInForce::ImmediateOrCancel, "95"),
            (TimeInForce::FillOrKill, "105"),
            (TimeInForce::FillOrKill, "95"),
        ] {
            let mut venue = venue_waiting();
            advance(&mut venue, time(12));

            let outcome =
                venue.open_order(limit_request("now", Side::Buy, "1", limit, time_in_force));

            assert!(outcome.events.is_empty());
            let reason = rejection_reason(&outcome);
            assert!(
                reason.contains("StaleMarketPolicy::Wait")
                    && reason.contains(&time_in_force.to_string()),
                "{reason}"
            );
            assert!(venue.account.orders().is_empty());
        }
    }

    #[test]
    fn a_limit_order_past_its_deadline_on_a_stale_market_expires_rather_than_waits() {
        let mut venue = venue_waiting();
        advance(&mut venue, time(12));

        let outcome = venue.open_order(limit_request(
            "late",
            Side::Buy,
            "1",
            "105",
            TimeInForce::GoodTillDate { expiry: time(12) },
        ));

        assert!(matches!(
            outcome.response.state,
            OrderState::Inactive(InactiveOrderState::Expired(_))
        ));
        assert!(venue.account.orders().is_empty());
    }

    #[test]
    fn a_held_limit_order_reaching_its_deadline_expires_and_releases_its_hold() {
        let mut venue = venue_waiting();
        advance(&mut venue, time(12));
        let _ = venue.open_order(limit_request(
            "dated",
            Side::Buy,
            "1",
            "105",
            TimeInForce::GoodTillDate { expiry: time(15) },
        ));

        let events = observe(&mut venue, 15, traded("102"));

        assert!(trades_in(&events).is_empty(), "{events:?}");
        assert!(events.iter().any(|event| matches!(
            &event.kind,
            AccountEventKind::OrderSnapshot(order)
                if matches!(order.0.state, OrderState::Inactive(InactiveOrderState::Expired(_)))
        )));
        assert_eq!(free_quote(&venue), d("10000"));
        assert!(venue.account.orders().is_empty());
    }

    #[test]
    fn a_held_limit_order_can_be_cancelled_and_one_still_held_at_the_end_of_the_data_expires() {
        let mut venue = venue_waiting();
        advance(&mut venue, time(12));
        let _ = venue.open_order(gtc_limit("cancelled", Side::Buy, "1", "105"));
        let _ = venue.open_order(gtc_limit("expired", Side::Buy, "1", "95"));

        let cancelled = venue.cancel_order(OrderRequestCancel {
            key: gtc_limit("cancelled", Side::Buy, "1", "105").key,
            state: RequestCancel { id: None },
        });
        assert!(cancelled.response.state.is_ok());
        assert_eq!(free_quote(&venue), d("9905"));
        assert_eq!(
            venue.account.orders().held_on(&instrument_name()),
            [ClientOrderId::new("expired")]
        );

        let events = venue.expire_held(time(30));
        assert_eq!(events.len(), 2, "{events:?}");
        assert_eq!(balance_of(&events[0]).balance.free, d("10000"));
        assert!(matches!(
            order_of(&events[1]).state,
            OrderState::Inactive(InactiveOrderState::Expired(_))
        ));
        assert!(venue.account.orders().is_empty());
    }

    #[test]
    fn a_limit_order_on_an_unpriced_instrument_rests_as_it_does_without_the_policy() {
        let mut venue =
            SimulatedVenue::new_market_driven(&stale_config(MAX_AGE), spot_instruments());
        advance(&mut venue, time(12));

        let outcome = venue.open_order(gtc_limit("resting", Side::Buy, "1", "100"));

        assert_eq!(rested_open(&outcome).filled_quantity, Decimal::ZERO);
        assert!(!venue.account.orders().holds(&instrument_name()));
        assert_eq!(
            resting_on(&venue, Side::Buy),
            [ClientOrderId::new("resting")]
        );
    }

    /// On a fresh market, and on a stale one, where it is refused rather than held for a release
    /// with nothing to trade.
    #[test]
    fn an_order_for_a_quantity_that_is_not_positive_is_refused_rather_than_held() {
        for (now, quantity) in [(1, "0"), (1, "-1"), (12, "0"), (12, "-1")] {
            for request in [
                gtc_limit("limit", Side::Buy, quantity, "105"),
                gtc_buy("market", quantity),
            ] {
                let mut venue = venue_waiting();
                advance(&mut venue, time(now));

                let outcome = venue.open_order(request);

                assert_eq!(
                    rejection_reason(&outcome),
                    format!(
                        "cannot open {} for {EXCHANGE}: quantity {quantity} is not positive",
                        instrument_name()
                    )
                );
                assert!(outcome.events.is_empty(), "a refused order moves nothing");
                assert!(
                    venue.account.orders().is_empty(),
                    "and is neither held nor rested"
                );
                assert_eq!(free_quote(&venue), d("10000"));
                assert!(
                    observe(&mut venue, 20, traded("102")).is_empty(),
                    "so a fresh observation has nothing to release"
                );
            }
        }
    }

    #[test]
    fn a_held_limit_order_the_account_can_no_longer_afford_is_cancelled_and_hands_back_its_draw() {
        let config = MockExecutionConfig {
            slippage: uniform(5),
            ..MockExecutionConfig {
                stale_market: StaleMarketPolicy::Wait { max_age: MAX_AGE },
                ..spot_config("10", "100", FeeModelConfig::default())
            }
        };
        let mut venue = SimulatedVenue::new_market_driven(&config, spot_instruments());
        advance(&mut venue, time(1));
        assert!(observe(&mut venue, 1, traded("100")).is_empty());
        advance(&mut venue, time(12));
        // Held at the stale 100: the account's whole balance.
        let outcome = venue.open_order(gtc_limit("waiting", Side::Buy, "1", "105"));
        assert_eq!(balance_of(&outcome.events[0]).balance.free, Decimal::ZERO);

        let events = observe(&mut venue, 20, traded("104"));

        assert_eq!(
            events.len(),
            2,
            "the released hold, then the order: {events:?}"
        );
        assert_eq!(balance_of(&events[0]).balance.free, d("100"));
        assert!(matches!(
            &order_of(&events[1]).state,
            OrderState::Inactive(InactiveOrderState::Cancelled(cancelled))
                if cancelled.filled_quantity == Some(Decimal::ZERO)
        ));
        assert!(venue.account.orders().is_empty());
        assert_eq!(venue.slippage, Slippage::new(uniform(5)));
    }

    #[test]
    fn a_held_sell_limit_order_fills_at_the_fresh_price_or_rests_at_its_limit() {
        let mut venue = venue_waiting();
        advance(&mut venue, time(12));
        // Both cross the stale 100; the fresh 97 crosses only the first.
        let _ = venue.open_order(gtc_limit("crossed", Side::Sell, "1", "95"));
        let _ = venue.open_order(gtc_limit("passive", Side::Sell, "1", "99"));

        let events = observe(&mut venue, 20, traded("97"));

        let prices = trades_in(&events)
            .iter()
            .map(|trade| (trade.client_order_id.clone(), trade.price))
            .collect::<Vec<_>>();
        assert_eq!(
            prices,
            vec![(Some(ClientOrderId::new("crossed")), d("97"))],
            "above its limit, at the fresh price"
        );
        assert_eq!(
            resting_on(&venue, Side::Sell),
            [ClientOrderId::new("passive")]
        );
        assert_eq!(total_base(&venue), d("9"));
    }

    #[test]
    fn a_held_limit_order_paying_its_fee_in_a_third_asset_takes_the_fee_apart_at_its_release() {
        let config = MockExecutionConfig {
            stale_market: StaleMarketPolicy::Wait { max_age: MAX_AGE },
            ..fee_asset_config("10")
        };
        let mut venue = fee_asset_venue_from(&config, true);
        advance(&mut venue, time(12));
        let _ = venue.open_order(gtc_limit("waiting", Side::Buy, "1", "51000"));

        let events = observe(&mut venue, 20, traded("50000"));

        assert_eq!(
            restated(&events)
                .iter()
                .map(|(asset, _)| asset.clone())
                .collect::<Vec<_>>(),
            [quote(), base(), bnb()],
            "paid, received, then the fee: {events:?}"
        );
        let trade = trades_in(&events)[0];
        assert_eq!(trade.price, d("50000"));
        // 10bp of 50,000 is 50 USDT, a quarter off in BNB at 600.
        assert_eq!(
            restated(&events)[2].1.free,
            d("10") - d("50") * d("0.75") / d("600")
        );
        assert_eq!(restated(&events)[0].1.total, d("50000"), "no fee in USDT");
    }

    fn cfd_venue_with(usd: &str, stale_market: StaleMarketPolicy) -> SimulatedVenue {
        let config = MockExecutionConfig {
            stale_market,
            ..config_from_balances(vec![funded(self::usd(), d(usd))], FeeModelConfig::default())
        };
        let mut venue =
            SimulatedVenue::new_market_driven(&config, instruments_of(cfd_instrument()));
        advance(&mut venue, time(1));
        venue
    }

    /// A released CFD order settles exactly as the same order arriving to the market that released
    /// it: against the position as it stands then, closing the long and opening a short, with the
    /// remainder the size there cannot fill held against the position the fill leaves.
    #[test]
    fn a_held_cfd_limit_order_settles_against_the_position_at_its_release_as_on_arrival() {
        let fresh = MarketObservation::new(MarketSnapshot {
            best_bid: Some(d("4950")),
            best_ask: Some(d("4960")),
            last_price: Some(d("4950")),
        });
        for depth in [MarketDepth::UNKNOWN, MarketDepth::new(Some(d("1.5")), None)] {
            let observation = fresh.with_depth(depth);

            let mut held = cfd_venue_with(
                "400000",
                StaleMarketPolicy::Wait {
                    max_age: Duration::from_secs(10),
                },
            );
            assert!(cfd_market(&mut held, "5000", "5000", "5000").is_empty());
            cfd_market_fill(&mut held, Side::Buy, "1");
            advance(&mut held, time(12));
            let outcome = held.open_order(cfd_limit("flip", Side::Sell, "2", "4900"));
            assert!(outcome.response.state.is_accepted());
            assert!(held.account.orders().holds(&cfd_instrument_name()));
            let released = held.apply_market(&cfd_instrument_name(), observation, time(12));
            assert!(!trades_in(&released).is_empty(), "{released:?}");

            let mut arriving = cfd_venue_with("400000", StaleMarketPolicy::Off);
            assert!(cfd_market(&mut arriving, "5000", "5000", "5000").is_empty());
            cfd_market_fill(&mut arriving, Side::Buy, "1");
            advance(&mut arriving, time(12));
            assert!(
                arriving
                    .apply_market(&cfd_instrument_name(), observation, time(12))
                    .is_empty()
            );
            let _ = arriving.open_order(cfd_limit("flip", Side::Sell, "2", "4900"));

            assert_eq!(
                (free_usd(&held), total_usd(&held), cfd_position(&held)),
                (
                    free_usd(&arriving),
                    total_usd(&arriving),
                    cfd_position(&arriving)
                ),
                "depth {depth:?}"
            );
            assert_eq!(
                resting_count(&held),
                resting_count(&arriving),
                "depth {depth:?}"
            );
        }
    }

    fn resting_count(venue: &SimulatedVenue) -> usize {
        venue
            .account
            .orders()
            .resting(&cfd_instrument_name(), Side::Sell)
            .count()
    }

    #[test]
    fn under_wait_an_observation_that_is_not_fresh_crosses_no_resting_order() {
        let mut venue = venue_waiting();
        let _ = venue.open_order(gtc_limit("resting", Side::Buy, "1", "99"));
        let _ = venue.open_order(gtc_limit("selling", Side::Sell, "1", "101"));

        assert!(observe_idle(&mut venue, 5, traded("95")).is_empty());
        assert!(observe_idle(&mut venue, 6, traded("105")).is_empty());
        assert_eq!(
            resting_on(&venue, Side::Buy),
            [ClientOrderId::new("resting")]
        );
        assert_eq!(
            resting_on(&venue, Side::Sell),
            [ClientOrderId::new("selling")]
        );

        let events = observe(&mut venue, 7, traded("98"));
        assert_eq!(
            trade_of(&events[2]).price,
            d("99"),
            "a fresh observation crosses it"
        );
    }

    #[test]
    fn without_the_policy_an_observation_that_is_not_fresh_still_crosses_a_resting_order() {
        let mut venue = SimulatedVenue::new_market_driven(
            &spot_config("10", "10000", FeeModelConfig::default()),
            spot_instruments(),
        );
        advance(&mut venue, time(1));
        assert!(observe(&mut venue, 1, traded("100")).is_empty());
        let _ = venue.open_order(gtc_limit("resting", Side::Buy, "1", "99"));

        let events = observe_idle(&mut venue, 5, traded("95"));

        assert_eq!(trade_of(&events[2]).price, d("99"));
    }

    #[test]
    fn a_held_limit_order_is_not_released_by_an_observation_that_is_not_fresh() {
        let mut venue = venue_waiting();
        advance(&mut venue, time(12));
        let _ = venue.open_order(gtc_limit("waiting", Side::Buy, "1", "105"));

        assert!(observe_idle(&mut venue, 13, traded("90")).is_empty());
        assert!(venue.account.orders().holds(&instrument_name()));

        let events = observe(&mut venue, 14, traded("103"));
        assert_eq!(trade_of(&events[2]).price, d("103"));
    }

    #[test]
    fn under_next_bar_a_limit_order_on_a_stale_market_is_decided_against_the_next_fresh_bar() {
        let mut venue = venue_holding_fresh_bars();
        advance(&mut venue, time(12));
        let _ = venue.open_order(gtc_limit("crossed", Side::Buy, "1", "104"));
        let _ = venue.open_order(gtc_limit("passive", Side::Buy, "1", "101"));
        let bar = ohlc("102", "106", "101", "105");
        assert!(venue.fills_ahead_of(
            &instrument_name(),
            &MarketObservation::new(traded("105")).with_bar(Some(bar))
        ));

        let events = feed_bar(&mut venue, 13, bar);

        let prices = trades_in(&events)
            .iter()
            .map(|trade| (trade.client_order_id.clone(), trade.price))
            .collect::<Vec<_>>();
        assert_eq!(
            prices,
            vec![(Some(ClientOrderId::new("crossed")), d("102"))],
            "the open crosses 104 and fills it there; it does not cross 101, which rests"
        );
        assert_eq!(
            resting_on(&venue, Side::Buy),
            [ClientOrderId::new("passive")]
        );
    }

    #[test]
    fn under_next_bar_a_held_limit_order_its_open_does_not_cross_can_be_crossed_by_its_close() {
        let mut venue = venue_holding_fresh_bars();
        advance(&mut venue, time(12));
        let _ = venue.open_order(gtc_limit("waiting", Side::Buy, "1", "101"));

        let events = feed_bar(&mut venue, 13, ohlc("102", "103", "99", "100"));

        let trades = trades_in(&events);
        assert_eq!(trades.len(), 1, "{events:?}");
        assert_eq!(
            trades[0].price,
            d("101"),
            "rested at its limit when the open did not reach it, then crossed by the close"
        );
        assert!(venue.account.orders().is_empty());
    }

    #[test]
    fn under_next_bar_a_limit_order_on_a_fresh_market_is_decided_on_arrival() {
        let mut venue = venue_holding_fresh_bars();

        let outcome = venue.open_order(gtc_limit("crossing", Side::Buy, "1", "104"));

        assert_eq!(filled_trade(&outcome).price, d("100"));
    }

    #[test]
    fn a_held_limit_buy_that_rests_a_remainder_holds_the_loan_left_against_it() {
        let config = MockExecutionConfig {
            stale_market: StaleMarketPolicy::Wait { max_age: MAX_AGE },
            ..margin_config("0", "100", "2")
        };
        let mut venue = SimulatedVenue::new_market_driven(&config, spot_instruments());
        advance(&mut venue, time(1));
        assert!(observe(&mut venue, 1, traded("100")).is_empty());
        advance(&mut venue, time(12));
        // 1.5 at the stale 100 needs 150 of the 100 held: 50 is lent.
        let outcome = venue.open_order(gtc_limit("waiting", Side::Buy, "1.5", "100"));
        assert_eq!(
            balance_of(&outcome.events[0]).balance,
            Balance::new_margin(d("150"), Decimal::ZERO, d("50"), Decimal::ZERO)
        );

        // 0.5 at 80 and 1 held at 100 need 140: 40 of the loan is still used, 10 is repaid.
        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("79", "80"))
                .with_depth(MarketDepth::new(Some(d("1")), Some(d("0.5")))),
            time(20),
        );
        assert_eq!(
            balance_of(&events[0]).balance,
            Balance::new_margin(d("100"), Decimal::ZERO, d("40"), Decimal::ZERO)
        );
        assert_eq!(trade_of(&events[2]).quantity, d("0.5"));

        let cancelled = venue.cancel_order(OrderRequestCancel {
            key: gtc_limit("waiting", Side::Buy, "1.5", "100").key,
            state: RequestCancel { id: None },
        });
        assert!(cancelled.response.state.is_ok());
        assert_eq!(
            venue.balances(&[quote()])[0].balance,
            Balance::new_margin(d("60"), d("60"), Decimal::ZERO, Decimal::ZERO),
            "cancelling the remainder repays the 40 it held"
        );
    }

    #[test]
    fn cancelling_a_released_remainder_repays_only_its_own_loan_and_not_one_already_owed() {
        // Owing 20 USDT already, the account has 100 of its own and 120 to spend.
        let config = MockExecutionConfig {
            stale_market: StaleMarketPolicy::Wait { max_age: MAX_AGE },
            spot_margin: Some(
                SpotMarginConfig::new(quote(), d("2"), MarginEffect::Borrow).unwrap(),
            ),
            ..config_from_balances(
                vec![
                    funded(base(), Decimal::ZERO),
                    AssetBalance::new(
                        quote(),
                        Balance::new_margin(d("120"), d("120"), d("20"), Decimal::ZERO),
                        Utc::now(),
                    ),
                ],
                FeeModelConfig::default(),
            )
        };
        let mut venue = SimulatedVenue::new_market_driven(&config, spot_instruments());
        advance(&mut venue, time(1));
        assert!(observe(&mut venue, 1, traded("100")).is_empty());
        advance(&mut venue, time(12));
        // 150 at the stale 100 lends 30 more.
        let _ = venue.open_order(gtc_limit("waiting", Side::Buy, "1.5", "100"));

        // 0.5 at 80 and 1 held at 100 need 140: 10 of the 30 is repaid, 20 still used.
        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("79", "80"))
                .with_depth(MarketDepth::new(Some(d("1")), Some(d("0.5")))),
            time(20),
        );
        assert_eq!(
            balance_of(&events[0]).balance,
            Balance::new_margin(d("100"), Decimal::ZERO, d("40"), Decimal::ZERO)
        );

        let cancelled = venue.cancel_order(OrderRequestCancel {
            key: gtc_limit("waiting", Side::Buy, "1.5", "100").key,
            state: RequestCancel { id: None },
        });
        assert!(cancelled.response.state.is_ok());
        assert_eq!(
            venue.balances(&[quote()])[0].balance,
            Balance::new_margin(d("80"), d("80"), d("20"), Decimal::ZERO),
            "the remainder repays the 20 it borrowed, and the 20 owed before stays owed"
        );
    }

    // ---------------------------------------------------------------------------------------
    // Spot margin: what the venue lends, holds and repays.
    // ---------------------------------------------------------------------------------------

    fn margin_config(btc: &str, usdt: &str, max_leverage: &str) -> MockExecutionConfig {
        MockExecutionConfig {
            spot_margin: Some(
                SpotMarginConfig::new(quote(), d(max_leverage), MarginEffect::Borrow).unwrap(),
            ),
            ..spot_config(btc, usdt, FeeModelConfig::default())
        }
    }

    /// A venue with no feed of its own, pricing each order from its request.
    fn margin_venue(btc: &str, usdt: &str, max_leverage: &str) -> SimulatedVenue {
        SimulatedVenue::new(&margin_config(btc, usdt, max_leverage), spot_instruments())
    }

    /// A fed venue, its book at 49,000 / 49,100, so a sell limit above the bid rests.
    fn margin_market_venue(btc: &str, usdt: &str) -> SimulatedVenue {
        let mut venue =
            SimulatedVenue::new_market_driven(&margin_config(btc, usdt, "3"), spot_instruments());
        advance(&mut venue, time(1));
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(book("49000", "49100")),
                    time(1)
                )
                .is_empty()
        );
        venue
    }

    /// `asset`'s balance as the venue reports it now.
    fn balance_now(venue: &SimulatedVenue, asset: AssetNameExchange) -> Balance {
        venue.balances(&[asset])[0].balance
    }

    /// The reason a rejection for an unaffordable order gives.
    fn insufficient_reason(outcome: &OpenOutcome) -> &str {
        match &outcome.response.state {
            OrderState::Inactive(InactiveOrderState::OpenFailed(OrderError::Rejected(
                ApiError::BalanceInsufficient(_, reason),
            ))) => reason,
            other => panic!("expected BalanceInsufficient, got: {other:?}"),
        }
    }

    #[test]
    fn a_cash_venue_reports_no_loans_and_refuses_a_sell_of_base_it_lacks() {
        let mut venue = make_venue("0.25", "100000");

        let outcome = venue.open_order(sell_request("1", market_prices("50000")));

        assert!(
            !insufficient_reason(&outcome).contains("Borrowable"),
            "{}",
            insufficient_reason(&outcome)
        );
        assert_eq!(
            balance_now(&venue, base()),
            Balance::new(d("0.25"), d("0.25"))
        );
    }

    #[test]
    fn a_margin_sell_borrows_only_the_shortfall_of_base() {
        let mut venue = margin_venue("0.25", "100000", "3");

        let outcome = venue.open_order(sell_request("1", market_prices("50000")));

        assert_eq!(
            filled_balance(&outcome).balance,
            Balance::new_margin(Decimal::ZERO, Decimal::ZERO, d("0.75"), Decimal::ZERO),
            "the sell delivers all the base it borrowed and what the account held"
        );
        assert_eq!(
            filled_received(&outcome).balance,
            Balance::new_margin(d("150000"), d("150000"), Decimal::ZERO, Decimal::ZERO)
        );
        assert_eq!(filled_trade(&outcome).quantity, d("1"));
    }

    #[test]
    fn a_margin_sell_of_base_the_account_never_held_borrows_it() {
        let config = MockExecutionConfig {
            spot_margin: Some(
                SpotMarginConfig::new(quote(), d("3"), MarginEffect::Borrow).unwrap(),
            ),
            ..config_from_balances(vec![funded(quote(), d("10000"))], FeeModelConfig::default())
        };
        let mut venue = SimulatedVenue::new(&config, spot_instruments());

        let outcome = venue.open_order(sell_request("0.1", market_prices("50000")));

        assert_eq!(
            filled_balance(&outcome).balance,
            Balance::new_margin(Decimal::ZERO, Decimal::ZERO, d("0.1"), Decimal::ZERO),
            "the sell opens a base balance with the loan, and delivers what it borrowed"
        );
    }

    #[test]
    fn a_margin_buy_borrows_quote_valued_through_the_inverse_of_its_pair() {
        // Valued in BTC, so a USDT loan is valued at the inverse of BTCUSDT's price.
        let config = MockExecutionConfig {
            spot_margin: Some(SpotMarginConfig::new(base(), d("2"), MarginEffect::Borrow).unwrap()),
            ..spot_config("1", "0", FeeModelConfig::default())
        };
        let mut venue = SimulatedVenue::new(&config, spot_instruments());

        // Equity of 1 BTC at leverage 2 lends up to 1 BTC's worth: 50,000 USDT.
        let outcome = venue.open_order(buy_request("1.5", market_prices("50000")));
        assert!(
            insufficient_reason(&outcome).contains("Borrowable: 50000"),
            "{}",
            insufficient_reason(&outcome)
        );

        let outcome = venue.open_order(buy_request("0.5", market_prices("50000")));
        assert_eq!(
            filled_balance(&outcome).balance,
            Balance::new_margin(Decimal::ZERO, Decimal::ZERO, d("25000"), Decimal::ZERO)
        );
        assert_eq!(balance_now(&venue, base()).total, d("1.5"));
    }

    #[test]
    fn a_margin_buy_repays_interest_then_principal_and_frees_the_rest() {
        let config = MockExecutionConfig {
            spot_margin: Some(
                SpotMarginConfig::new(quote(), d("3"), MarginEffect::Borrow).unwrap(),
            ),
            ..config_from_balances(
                vec![
                    AssetBalance::new(
                        base(),
                        Balance::new_margin(Decimal::ZERO, Decimal::ZERO, d("0.75"), d("0.01")),
                        Utc::now(),
                    ),
                    funded(quote(), d("100000")),
                ],
                FeeModelConfig::default(),
            )
        };
        let mut venue = SimulatedVenue::new(&config, spot_instruments());

        let outcome = venue.open_order(with_effect(
            buy_request("1", market_prices("50000")),
            MarginEffect::Repay,
        ));

        assert_eq!(
            filled_received(&outcome).balance,
            Balance::new_margin(d("0.24"), d("0.24"), Decimal::ZERO, Decimal::ZERO),
            "1 BTC repays 0.01 of interest and 0.75 of principal, leaving 0.24 free"
        );
    }

    #[test]
    fn a_buy_smaller_than_the_debt_repays_interest_before_principal() {
        let config = MockExecutionConfig {
            spot_margin: Some(
                SpotMarginConfig::new(quote(), d("3"), MarginEffect::Borrow).unwrap(),
            ),
            ..config_from_balances(
                vec![
                    AssetBalance::new(
                        base(),
                        Balance::new_margin(Decimal::ZERO, Decimal::ZERO, d("0.75"), d("0.01")),
                        Utc::now(),
                    ),
                    funded(quote(), d("100000")),
                ],
                FeeModelConfig::default(),
            )
        };
        let mut venue = SimulatedVenue::new(&config, spot_instruments());

        let outcome = venue.open_order(with_effect(
            buy_request("0.11", market_prices("50000")),
            MarginEffect::Repay,
        ));

        assert_eq!(
            filled_received(&outcome).balance,
            Balance::new_margin(Decimal::ZERO, Decimal::ZERO, d("0.65"), Decimal::ZERO)
        );
    }

    #[test]
    fn a_borrow_beyond_the_leverage_limit_is_refused_naming_what_would_be_lent() {
        // Equity of 10,000 USDT at leverage 2 lends up to 10,000 USDT's worth: 0.2 BTC.
        let mut venue = margin_venue("0", "10000", "2");

        let outcome = venue.open_order(sell_request("0.3", market_prices("50000")));
        assert!(
            insufficient_reason(&outcome).contains("Borrowable: 0.2"),
            "{}",
            insufficient_reason(&outcome)
        );
        assert_eq!(
            balance_now(&venue, base()),
            Balance::new_margin(Decimal::ZERO, Decimal::ZERO, Decimal::ZERO, Decimal::ZERO),
            "a refused order borrows nothing"
        );

        let outcome = venue.open_order(sell_request("0.2", market_prices("50000")));
        assert_eq!(filled_trade(&outcome).quantity, d("0.2"));
    }

    #[test]
    fn debt_already_owed_counts_against_what_the_venue_lends() {
        // Equity 10,000 at leverage 2 lends 10,000 USDT's worth in all.
        let mut venue = margin_venue("0", "10000", "2");
        let outcome = venue.open_order(sell_request("0.15", market_prices("50000")));
        assert_eq!(filled_trade(&outcome).quantity, d("0.15"));

        // 7,500 of the 10,000 is owed, so 2,500 is left: 0.05 BTC.
        let outcome = venue.open_order(sell_request("0.06", market_prices("50000")));
        assert!(
            insufficient_reason(&outcome).contains("Borrowable: 0.05"),
            "{}",
            insufficient_reason(&outcome)
        );
    }

    #[test]
    fn a_leverage_of_one_lends_nothing_but_every_balance_reports_its_loan() {
        let mut venue = margin_venue("0", "10000", "1");

        for balance in venue.balances(&[base(), quote()]) {
            assert_eq!(
                balance.balance.margin,
                Some(MarginDetails::default()),
                "{balance:?}"
            );
        }

        let outcome = venue.open_order(sell_request("0.1", market_prices("50000")));
        assert!(
            insufficient_reason(&outcome).contains("Borrowable: 0"),
            "{}",
            insufficient_reason(&outcome)
        );
    }

    #[test]
    fn no_side_effect_lends_nothing_and_repays_nothing() {
        let config = MockExecutionConfig {
            spot_margin: Some(
                SpotMarginConfig::new(quote(), d("3"), MarginEffect::NoSideEffect).unwrap(),
            ),
            ..config_from_balances(
                vec![
                    AssetBalance::new(
                        base(),
                        Balance::new_margin(Decimal::ZERO, Decimal::ZERO, d("0.5"), Decimal::ZERO),
                        Utc::now(),
                    ),
                    funded(quote(), d("100000")),
                ],
                FeeModelConfig::default(),
            )
        };
        let mut venue = SimulatedVenue::new(&config, spot_instruments());

        let outcome = venue.open_order(sell_request("0.1", market_prices("50000")));
        assert!(
            !insufficient_reason(&outcome).contains("Borrowable"),
            "{}",
            insufficient_reason(&outcome)
        );

        let outcome = venue.open_order(buy_request("1", market_prices("50000")));
        assert_eq!(
            filled_received(&outcome).balance,
            Balance::new_margin(d("1"), d("1"), d("0.5"), Decimal::ZERO),
            "the bought base is free; the loan is left as it was"
        );
    }

    #[test]
    fn an_asset_the_venue_cannot_value_is_not_lent() {
        // No instrument pairs BTC with EUR, so a BTC loan cannot be valued.
        let config = MockExecutionConfig {
            spot_margin: Some(
                SpotMarginConfig::new(AssetNameExchange::new("EUR"), d("3"), MarginEffect::Borrow)
                    .unwrap(),
            ),
            ..spot_config("0", "100000", FeeModelConfig::default())
        };
        let mut venue = SimulatedVenue::new(&config, spot_instruments());

        let outcome = venue.open_order(sell_request("0.1", market_prices("50000")));
        assert!(
            insufficient_reason(&outcome).contains("Borrowable: 0"),
            "{}",
            insufficient_reason(&outcome)
        );
    }

    #[test]
    fn a_cfd_order_is_not_lent_its_margin() {
        let config = MockExecutionConfig {
            spot_margin: Some(SpotMarginConfig::new(usd(), d("3"), MarginEffect::Borrow).unwrap()),
            ..config_from_balances(vec![funded(usd(), d("1000"))], FeeModelConfig::default())
        };
        let mut venue = SimulatedVenue::new(&config, instruments_of(cfd_instrument()));

        let outcome = venue.open_order(cfd_request(Side::Sell, "1", market_prices("5000")));
        assert!(
            insufficient_reason(&outcome).contains("Borrowable: 0"),
            "{}",
            insufficient_reason(&outcome)
        );
        assert_eq!(
            balance_now(&venue, usd()),
            Balance::new_margin(d("1000"), d("1000"), Decimal::ZERO, Decimal::ZERO)
        );
    }

    /// The error an order was refused with.
    fn open_error(outcome: &OpenOutcome) -> &UnindexedOrderError {
        match &outcome.response.state {
            OrderState::Inactive(InactiveOrderState::OpenFailed(error)) => error,
            other => panic!("expected the order to be refused, got: {other:?}"),
        }
    }

    /// A margin account owing 0.75 BTC and 0.01 of interest on it, with `effect` as its default.
    fn config_owing_base(effect: MarginEffect) -> MockExecutionConfig {
        MockExecutionConfig {
            spot_margin: Some(SpotMarginConfig::new(quote(), d("3"), effect).unwrap()),
            ..config_from_balances(
                vec![
                    AssetBalance::new(
                        base(),
                        Balance::new_margin(Decimal::ZERO, Decimal::ZERO, d("0.75"), d("0.01")),
                        Utc::now(),
                    ),
                    funded(quote(), d("100000")),
                ],
                FeeModelConfig::default(),
            )
        }
    }

    /// A fed venue for `config`, its book at 49,000 / 49,100.
    fn market_venue_for(config: &MockExecutionConfig) -> SimulatedVenue {
        let mut venue = SimulatedVenue::new_market_driven(config, spot_instruments());
        advance(&mut venue, time(1));
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(book("49000", "49100")),
                    time(1),
                )
                .is_empty()
        );
        venue
    }

    #[test]
    fn a_borrow_order_repays_nothing_from_what_it_receives() {
        let mut venue =
            SimulatedVenue::new(&config_owing_base(MarginEffect::Borrow), spot_instruments());

        let outcome = venue.open_order(buy_request("1", market_prices("50000")));

        assert_eq!(
            filled_received(&outcome).balance,
            Balance::new_margin(d("1"), d("1"), d("0.75"), d("0.01")),
            "the bought base is free and the loan, interest included, is left owed"
        );
    }

    #[test]
    fn a_request_effect_overrides_the_configured_default() {
        // A venue that borrows by default, told not to: the sell is refused as on a cash account.
        let mut venue = margin_venue("0", "100000", "3");
        let outcome = venue.open_order(with_effect(
            sell_request("1", market_prices("50000")),
            MarginEffect::NoSideEffect,
        ));
        assert!(
            !insufficient_reason(&outcome).contains("Borrowable"),
            "{}",
            insufficient_reason(&outcome)
        );

        // A venue that borrows nothing by default, told to: the same sell borrows its base.
        let config = MockExecutionConfig {
            spot_margin: Some(
                SpotMarginConfig::new(quote(), d("3"), MarginEffect::NoSideEffect).unwrap(),
            ),
            ..spot_config("0", "100000", FeeModelConfig::default())
        };
        let mut venue = SimulatedVenue::new(&config, spot_instruments());
        let outcome = venue.open_order(with_effect(
            sell_request("1", market_prices("50000")),
            MarginEffect::Borrow,
        ));
        assert_eq!(
            filled_balance(&outcome).balance,
            Balance::new_margin(Decimal::ZERO, Decimal::ZERO, d("1"), Decimal::ZERO)
        );
    }

    #[test]
    fn a_repay_order_borrows_nothing() {
        let mut venue = margin_venue("0.25", "100000", "3");

        let outcome = venue.open_order(with_effect(
            sell_request("1", market_prices("50000")),
            MarginEffect::Repay,
        ));

        assert!(
            !insufficient_reason(&outcome).contains("Borrowable"),
            "{}",
            insufficient_reason(&outcome)
        );
        assert_eq!(
            balance_now(&venue, base()),
            Balance::new_margin(d("0.25"), d("0.25"), Decimal::ZERO, Decimal::ZERO),
            "a refused order borrows nothing"
        );
    }

    #[test]
    fn a_cfd_order_naming_a_borrow_or_repay_is_refused_unsent() {
        let config = MockExecutionConfig {
            spot_margin: Some(SpotMarginConfig::new(usd(), d("3"), MarginEffect::Borrow).unwrap()),
            ..config_from_balances(vec![funded(usd(), d("1000"))], FeeModelConfig::default())
        };
        let mut venue = SimulatedVenue::new(&config, instruments_of(cfd_instrument()));

        for effect in [MarginEffect::Borrow, MarginEffect::Repay] {
            let outcome = venue.open_order(with_effect(
                cfd_request(Side::Buy, "1", market_prices("5000")),
                effect,
            ));
            assert_eq!(
                open_error(&outcome),
                &UnindexedOrderError::UnsupportedMarginEffect(effect)
            );
        }
        assert_eq!(
            balance_now(&venue, usd()),
            Balance::new_margin(d("1000"), d("1000"), Decimal::ZERO, Decimal::ZERO),
            "a refused order touches nothing"
        );

        // `NoSideEffect` is honoured: a CFD never borrows, so it is not refused for its effect
        // whatever else the venue makes of it.
        let outcome = venue.open_order(with_effect(
            cfd_request(Side::Buy, "0.01", market_prices("5000")),
            MarginEffect::NoSideEffect,
        ));
        assert!(
            !matches!(
                &outcome.response.state,
                OrderState::Inactive(InactiveOrderState::OpenFailed(
                    UnindexedOrderError::UnsupportedMarginEffect(_)
                ))
            ),
            "{:?}",
            outcome.response.state
        );
    }

    #[test]
    fn a_cash_venue_takes_no_effect_but_no_side_effect() {
        let mut venue = make_venue("1", "100000");

        for effect in [MarginEffect::Borrow, MarginEffect::Repay] {
            let outcome = venue.open_order(with_effect(
                sell_request("0.1", market_prices("50000")),
                effect,
            ));
            assert_eq!(
                open_error(&outcome),
                &UnindexedOrderError::UnsupportedMarginEffect(effect)
            );
        }

        let outcome = venue.open_order(with_effect(
            sell_request("0.1", market_prices("50000")),
            MarginEffect::NoSideEffect,
        ));
        assert_eq!(filled_trade(&outcome).quantity, d("0.1"));
    }

    #[test]
    fn a_resting_order_repays_from_its_fill_as_it_was_placed_to() {
        // The venue borrows by default, but this buy was placed to repay: its effect rides on the
        // order, not on the configuration, so the fill that comes later repays the 0.76 owed.
        let mut venue = market_venue_for(&config_owing_base(MarginEffect::Borrow));
        let rested = venue.open_order(with_effect(
            limit_request("rest", Side::Buy, "1", "49050", gtc()),
            MarginEffect::Repay,
        ));
        assert_eq!(rested_open(&rested).filled_quantity, Decimal::ZERO);

        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("48900", "49000")),
            time(2),
        );

        assert_eq!(
            balance_of(&events[1]).balance,
            Balance::new_margin(d("0.24"), d("0.24"), Decimal::ZERO, Decimal::ZERO),
            "1 BTC repays 0.01 of interest and 0.75 of principal, leaving 0.24 free"
        );
    }

    #[test]
    fn a_resting_order_placed_to_borrow_repays_nothing_from_its_fill() {
        let mut venue = market_venue_for(&config_owing_base(MarginEffect::Repay));
        venue.open_order(with_effect(
            limit_request("rest", Side::Buy, "1", "49050", gtc()),
            MarginEffect::Borrow,
        ));

        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("48900", "49000")),
            time(2),
        );

        assert_eq!(
            balance_of(&events[1]).balance,
            Balance::new_margin(d("1"), d("1"), d("0.75"), d("0.01")),
            "the loan is left owed although the venue's default would have repaid it"
        );
    }

    #[test]
    fn without_auto_repay_at_cancel_a_cancelled_order_leaves_its_loan_owed() {
        let config = MockExecutionConfig {
            spot_margin: Some(
                SpotMarginConfig::new(quote(), d("3"), MarginEffect::Borrow)
                    .unwrap()
                    .with_auto_repay_at_cancel(false),
            ),
            ..spot_config("0", "100000", FeeModelConfig::default())
        };
        let mut venue = market_venue_for(&config);
        venue.open_order(limit_request("rest", Side::Sell, "1", "50000", gtc()));

        let cancelled = venue.cancel_order(OrderRequestCancel {
            key: limit_request("rest", Side::Sell, "1", "50000", gtc()).key,
            state: RequestCancel { id: None },
        });

        assert!(cancelled.response.state.is_ok());
        assert_eq!(
            balance_of(&cancelled.events[0]).balance,
            Balance::new_margin(d("1"), d("1"), d("1"), Decimal::ZERO),
            "the released base is free again and the loan that paid for it stays owed"
        );
    }

    #[test]
    fn a_resting_sell_borrows_when_placed_and_a_cancel_repays_it() {
        let mut venue = margin_market_venue("0", "100000");

        let outcome = venue.open_order(limit_request("rest", Side::Sell, "1", "50000", gtc()));
        assert_eq!(rested_open(&outcome).filled_quantity, Decimal::ZERO);
        assert_eq!(
            balance_of(&outcome.events[0]).balance,
            Balance::new_margin(d("1"), Decimal::ZERO, d("1"), Decimal::ZERO),
            "the borrowed base is held against the order"
        );

        let cancelled = venue.cancel_order(OrderRequestCancel {
            key: limit_request("rest", Side::Sell, "1", "50000", gtc()).key,
            state: RequestCancel { id: None },
        });
        assert!(cancelled.response.state.is_ok());
        assert_eq!(
            balance_of(&cancelled.events[0]).balance,
            Balance::new_margin(Decimal::ZERO, Decimal::ZERO, Decimal::ZERO, Decimal::ZERO),
            "the cancel repays what the order borrowed"
        );
    }

    #[test]
    fn a_resting_sell_that_fills_keeps_its_loan() {
        let mut venue = margin_market_venue("0", "100000");
        venue.open_order(limit_request("rest", Side::Sell, "1", "50000", gtc()));

        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("50100", "50200")),
            time(2),
        );

        assert_eq!(
            balance_of(&events[0]).balance,
            Balance::new_margin(Decimal::ZERO, Decimal::ZERO, d("1"), Decimal::ZERO)
        );
        assert_eq!(trade_of(&events[2]).quantity, d("1"));
    }

    #[test]
    fn a_partly_filled_sell_holds_its_loan_against_the_remainder() {
        let mut venue = margin_market_venue("0.4", "100000");
        // Only 0.5 bid at 49,000, so a marketable sell of 1 fills half and rests half.
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(book("49000", "49100"))
                        .with_depth(MarketDepth::new(Some(d("0.5")), None)),
                    time(2),
                )
                .is_empty()
        );

        let outcome = venue.open_order(limit_request("part", Side::Sell, "1", "49000", gtc()));
        assert_eq!(rested_open(&outcome).filled_quantity, d("0.5"));
        assert_eq!(
            filled_balance(&outcome).balance,
            Balance::new_margin(d("0.5"), Decimal::ZERO, d("0.6"), Decimal::ZERO),
            "0.4 held plus 0.6 borrowed: 0.5 sold and 0.5 held against the rest"
        );

        let cancelled = venue.cancel_order(OrderRequestCancel {
            key: limit_request("part", Side::Sell, "1", "49000", gtc()).key,
            state: RequestCancel { id: None },
        });
        assert_eq!(
            balance_of(&cancelled.events[0]).balance,
            Balance::new_margin(Decimal::ZERO, Decimal::ZERO, d("0.1"), Decimal::ZERO),
            "the fill spent the account's own 0.4 first, so the cancel repays 0.5 of the loan"
        );
    }

    #[test]
    fn a_held_market_sell_borrows_when_accepted_and_keeps_the_loan_when_its_bar_fills_it() {
        let config = MockExecutionConfig {
            market_order_timing: MarketOrderTiming::NextBar(NextBarPrice::Open),
            ..margin_config("0", "1000", "3")
        };
        let mut venue = SimulatedVenue::new_market_driven(&config, spot_instruments());
        advance(&mut venue, time(1));
        assert!(feed_bar(&mut venue, 1, ohlc("95", "105", "90", "100")).is_empty());

        let outcome = venue.open_order(market_order("held", Side::Sell, "2", gtc()));
        assert_eq!(
            balance_of(&outcome.events[0]).balance,
            Balance::new_margin(d("2"), Decimal::ZERO, d("2"), Decimal::ZERO)
        );

        let events = feed_bar(&mut venue, 2, ohlc("98", "99", "97", "98"));
        assert_eq!(
            balance_of(&events[0]).balance,
            Balance::new_margin(Decimal::ZERO, Decimal::ZERO, d("2"), Decimal::ZERO)
        );
        assert_eq!(trade_of(&events[2]).price, d("98"));
    }

    #[test]
    fn a_held_market_sell_that_expires_repays_its_loan() {
        let config = MockExecutionConfig {
            market_order_timing: MarketOrderTiming::NextBar(NextBarPrice::Open),
            ..margin_config("0", "1000", "3")
        };
        let mut venue = SimulatedVenue::new_market_driven(&config, spot_instruments());
        advance(&mut venue, time(1));
        assert!(feed_bar(&mut venue, 1, ohlc("95", "105", "90", "100")).is_empty());
        venue.open_order(market_order("held", Side::Sell, "2", gtc()));

        let events = venue.expire_held(time(2));

        assert_eq!(
            balance_of(&events[0]).balance,
            Balance::new_margin(Decimal::ZERO, Decimal::ZERO, Decimal::ZERO, Decimal::ZERO)
        );
    }

    /// A venue holding market orders for the next bar, on margin, with 100 USDT and no BTC, fed
    /// one bar that closed at 100.
    fn margin_venue_holding() -> SimulatedVenue {
        let config = MockExecutionConfig {
            market_order_timing: MarketOrderTiming::NextBar(NextBarPrice::Open),
            ..margin_config("0", "100", "2")
        };
        let mut venue = SimulatedVenue::new_market_driven(&config, spot_instruments());
        advance(&mut venue, time(1));
        assert!(feed_bar(&mut venue, 1, ohlc("95", "105", "90", "100")).is_empty());
        venue
    }

    #[test]
    fn a_held_buy_costed_higher_at_its_bar_borrows_the_difference() {
        let mut venue = margin_venue_holding();
        // 150 at the close of 100: 50 borrowed of the 100 equity allows.
        let outcome = venue.open_order(market_order("held", Side::Buy, "1.5", gtc()));
        assert_eq!(
            balance_of(&outcome.events[0]).balance,
            Balance::new_margin(d("150"), Decimal::ZERO, d("50"), Decimal::ZERO)
        );

        // 180 at an open of 120: 30 more borrowed, within the 50 left.
        let events = feed_bar(&mut venue, 2, ohlc("120", "121", "119", "120"));
        assert_eq!(
            balance_of(&events[0]).balance,
            Balance::new_margin(Decimal::ZERO, Decimal::ZERO, d("80"), Decimal::ZERO)
        );
        assert_eq!(trade_of(&events[2]).price, d("120"));
    }

    #[test]
    fn a_held_buy_costed_lower_at_its_bar_repays_the_loan_it_no_longer_needs() {
        let mut venue = margin_venue_holding();
        // 150 at the close of 100: 50 borrowed.
        venue.open_order(market_order("held", Side::Buy, "1.5", gtc()));

        // 120 at an open of 80: the 100 the account had pays first, so 20 of the loan is used
        // and the other 30 is repaid.
        let events = feed_bar(&mut venue, 2, ohlc("80", "81", "79", "80"));
        assert_eq!(
            balance_of(&events[0]).balance,
            Balance::new_margin(Decimal::ZERO, Decimal::ZERO, d("20"), Decimal::ZERO)
        );
        assert_eq!(
            balance_of(&events[1]).balance,
            Balance::new_margin(d("1.5"), d("1.5"), Decimal::ZERO, Decimal::ZERO)
        );
        assert_eq!(trade_of(&events[2]).price, d("80"));
    }

    #[test]
    fn a_held_buy_unaffordable_at_its_bar_is_cancelled_and_repays_its_loan() {
        let mut venue = margin_venue_holding();
        venue.open_order(market_order("held", Side::Buy, "1.5", gtc()));

        // 375 at an open of 250 needs 225 more than the 150 held, and only 50 more may be lent.
        let events = feed_bar(&mut venue, 2, ohlc("250", "251", "249", "250"));

        assert_eq!(
            balance_of(&events[0]).balance,
            Balance::new_margin(d("100"), d("100"), Decimal::ZERO, Decimal::ZERO),
            "the cancel repays the 50 the order borrowed when it was accepted"
        );
        assert!(matches!(
            order_of(&events[1]).state,
            OrderState::Inactive(InactiveOrderState::Cancelled(_))
        ));
    }

    /// [`margin_venue_holding`], with `config` adjusted by `adjust`.
    fn margin_venue_holding_with(
        adjust: impl FnOnce(SpotMarginConfig) -> SpotMarginConfig,
        effect: MarginEffect,
    ) -> SimulatedVenue {
        let mut config = MockExecutionConfig {
            market_order_timing: MarketOrderTiming::NextBar(NextBarPrice::Open),
            ..margin_config("0", "100", "2")
        };
        config.spot_margin = Some(adjust(
            SpotMarginConfig::new(quote(), d("2"), effect).unwrap(),
        ));
        let mut venue = SimulatedVenue::new_market_driven(&config, spot_instruments());
        advance(&mut venue, time(1));
        assert!(feed_bar(&mut venue, 1, ohlc("95", "105", "90", "100")).is_empty());
        venue
    }

    #[test]
    fn without_auto_repay_at_cancel_a_held_buy_costed_lower_keeps_the_loan_it_no_longer_needs() {
        let mut venue = margin_venue_holding_with(
            |config| config.with_auto_repay_at_cancel(false),
            MarginEffect::Borrow,
        );
        venue.open_order(market_order("held", Side::Buy, "1.5", gtc()));

        // 120 at an open of 80: 20 of the 50 loan is used, and the other 30 stays owed.
        let events = feed_bar(&mut venue, 2, ohlc("80", "81", "79", "80"));

        assert_eq!(
            balance_of(&events[0]).balance,
            Balance::new_margin(d("30"), d("30"), d("50"), Decimal::ZERO)
        );
    }

    #[test]
    fn without_auto_repay_at_cancel_a_held_buy_unaffordable_at_its_bar_keeps_its_loan() {
        let mut venue = margin_venue_holding_with(
            |config| config.with_auto_repay_at_cancel(false),
            MarginEffect::Borrow,
        );
        venue.open_order(market_order("held", Side::Buy, "1.5", gtc()));

        let events = feed_bar(&mut venue, 2, ohlc("250", "251", "249", "250"));

        assert_eq!(
            balance_of(&events[0]).balance,
            Balance::new_margin(d("150"), d("150"), d("50"), Decimal::ZERO),
            "the cancel gives the hold back and leaves the 50 the order borrowed owed"
        );
        assert!(matches!(
            order_of(&events[1]).state,
            OrderState::Inactive(InactiveOrderState::Cancelled(_))
        ));
    }

    #[test]
    fn without_auto_repay_at_cancel_a_held_sell_that_expires_keeps_its_loan() {
        let mut venue = margin_venue_holding_with(
            |config| config.with_auto_repay_at_cancel(false),
            MarginEffect::Borrow,
        );
        venue.open_order(market_order("held", Side::Sell, "1", gtc()));

        let events = venue.expire_held(time(2));

        assert_eq!(
            balance_of(&events[0]).balance,
            Balance::new_margin(d("1"), d("1"), d("1"), Decimal::ZERO)
        );
    }

    #[test]
    fn a_held_buy_costed_afresh_at_its_bar_borrows_as_it_was_placed_to() {
        // The venue borrows nothing by default, but this buy was placed to borrow: at its bar
        // the fill is costed afresh, and the 30 more it needs is lent because of the effect it
        // was placed with, not the configuration's.
        let mut venue = margin_venue_holding_with(|config| config, MarginEffect::NoSideEffect);
        let mut request = market_order("held", Side::Buy, "1.5", gtc());
        request.state = request.state.with_margin_effect(MarginEffect::Borrow);
        venue.open_order(request);

        let events = feed_bar(&mut venue, 2, ohlc("120", "121", "119", "120"));

        assert_eq!(
            balance_of(&events[0]).balance,
            Balance::new_margin(Decimal::ZERO, Decimal::ZERO, d("80"), Decimal::ZERO)
        );
        assert_eq!(trade_of(&events[2]).price, d("120"));
    }

    /// A margin venue also holding `eth`, which no instrument values, owing `eth_owed` of it.
    fn margin_venue_with_eth(eth: &str, eth_owed: &str) -> SimulatedVenue {
        let config = MockExecutionConfig {
            spot_margin: Some(
                SpotMarginConfig::new(quote(), d("2"), MarginEffect::Borrow).unwrap(),
            ),
            ..config_from_balances(
                vec![
                    funded(base(), Decimal::ZERO),
                    funded(quote(), d("10000")),
                    AssetBalance::new(
                        AssetNameExchange::new("ETH"),
                        Balance::new_margin(d(eth), d(eth), d(eth_owed), Decimal::ZERO),
                        Utc::now(),
                    ),
                ],
                FeeModelConfig::default(),
            )
        };
        SimulatedVenue::new(&config, spot_instruments())
    }

    #[test]
    fn an_asset_the_venue_cannot_value_counts_as_no_equity() {
        // 5 ETH the venue cannot value adds nothing: 10,000 USDT at leverage 2 lends 0.2 BTC.
        let mut venue = margin_venue_with_eth("5", "0");

        let outcome = venue.open_order(sell_request("0.3", market_prices("50000")));
        assert!(
            insufficient_reason(&outcome).contains("Borrowable: 0.2"),
            "{}",
            insufficient_reason(&outcome)
        );
    }

    #[test]
    fn a_debt_the_venue_cannot_value_stops_it_lending() {
        let mut venue = margin_venue_with_eth("5", "1");

        let outcome = venue.open_order(sell_request("0.1", market_prices("50000")));
        assert!(
            insufficient_reason(&outcome).contains("Borrowable: 0"),
            "{}",
            insufficient_reason(&outcome)
        );
    }

    #[test]
    fn interest_owed_counts_as_debt_against_what_the_venue_lends() {
        let config = MockExecutionConfig {
            spot_margin: Some(
                SpotMarginConfig::new(quote(), d("2"), MarginEffect::Borrow).unwrap(),
            ),
            ..config_from_balances(
                vec![
                    AssetBalance::new(
                        base(),
                        Balance::new_margin(Decimal::ZERO, Decimal::ZERO, d("0.05"), d("0.01")),
                        Utc::now(),
                    ),
                    funded(quote(), d("20000")),
                ],
                FeeModelConfig::default(),
            )
        };
        let mut venue = SimulatedVenue::new(&config, spot_instruments());

        // 0.06 BTC owed is 3,000: equity 17,000 at leverage 2 lends 17,000, less the 3,000
        // already owed, leaving 14,000: 0.28 BTC.
        let outcome = venue.open_order(sell_request("1", market_prices("50000")));
        assert!(
            insufficient_reason(&outcome).contains("Borrowable: 0.28"),
            "{}",
            insufficient_reason(&outcome)
        );
    }

    #[test]
    fn an_asset_a_margin_account_first_receives_reports_its_loan() {
        let config = MockExecutionConfig {
            spot_margin: Some(
                SpotMarginConfig::new(quote(), d("3"), MarginEffect::Borrow).unwrap(),
            ),
            ..config_from_balances(
                vec![funded(quote(), d("100000"))],
                FeeModelConfig::default(),
            )
        };
        let mut venue = SimulatedVenue::new(&config, spot_instruments());

        let outcome = venue.open_order(buy_request("1", market_prices("50000")));

        assert_eq!(
            filled_received(&outcome).balance,
            Balance::new_margin(d("1"), d("1"), Decimal::ZERO, Decimal::ZERO)
        );
    }

    #[test]
    fn an_asset_priced_at_zero_is_not_lent() {
        let mut venue = margin_venue("0", "10000", "2");

        let outcome = venue.open_order(sell_request("0.1", market_prices("0")));
        assert!(
            insufficient_reason(&outcome).contains("Borrowable: 0"),
            "{}",
            insufficient_reason(&outcome)
        );
    }

    #[test]
    fn a_pair_quoting_the_asset_in_another_does_not_value_it() {
        // AAVEBTC prices BTC in AAVE, not in the valuation asset, though it sorts first by name.
        let mut instruments = spot_instruments();
        let aave_btc = Instrument {
            exchange: EXCHANGE,
            name_internal: InstrumentNameInternal::new("aavebtc"),
            name_exchange: InstrumentNameExchange::new("AAVEBTC"),
            underlying: Underlying {
                base: AssetNameExchange::new("AAVE"),
                quote: base(),
            },
            quote: InstrumentQuoteAsset::UnderlyingQuote,
            kind: InstrumentKind::Spot,
            spec: None,
            data_venue: None,
        };
        instruments.insert(aave_btc.name_exchange.clone(), aave_btc);
        let mut venue =
            SimulatedVenue::new_market_driven(&margin_config("0", "10000", "2"), instruments);
        advance(&mut venue, time(1));
        for (name, snapshot) in [
            (instrument_name(), book("50000", "50000")),
            (InstrumentNameExchange::new("AAVEBTC"), book("0.05", "0.05")),
        ] {
            assert!(
                venue
                    .apply_market(&name, MarketObservation::new(snapshot), time(1))
                    .is_empty()
            );
        }

        // Valued at 50,000 through BTCUSDT: equity 10,000 at leverage 2 lends 0.2 BTC.
        let outcome = venue.open_order(market_order(
            "sell",
            Side::Sell,
            "0.3",
            TimeInForce::ImmediateOrCancel,
        ));
        assert!(
            insufficient_reason(&outcome).contains("Borrowable: 0.2"),
            "{}",
            insufficient_reason(&outcome)
        );
    }

    // ---------------------------------------------------------------------------------------
    // Margin interest: charged when a loan is taken, then at each boundary while it is open.
    // ---------------------------------------------------------------------------------------

    /// 87.6% a year on the Act365 basis is exactly 0.01% an hour.
    const HOURLY_BASIS_POINT: &str = "0.876";

    /// Hourly interest on loans of `asset` at [`HOURLY_BASIS_POINT`].
    fn hourly_interest(asset: AssetNameExchange) -> PeriodicMarginInterest {
        PeriodicMarginInterest::new(TimeDelta::hours(1), DayCount::Act365)
            .with_rates(asset, RateSeries::constant(d(HOURLY_BASIS_POINT)))
    }

    /// The cash flow reporting `interest` charged on `principal` of `asset` at `time`.
    fn interest_flow(
        asset: AssetNameExchange,
        principal: &str,
        interest: &str,
        time: DateTime<Utc>,
        timing: InterestTiming,
        id: &str,
    ) -> CashFlow<AssetNameExchange, InstrumentNameExchange> {
        CashFlow::new(
            CashFlowKind::MarginInterest {
                rate: Some(d(HOURLY_BASIS_POINT)),
                principal: Some(d(principal)),
                timing: Some(timing),
            },
            asset,
            -d(interest),
            None,
            time,
            Some(CashFlowId::new(id)),
        )
    }

    fn cash_flow_of(
        event: &UnindexedAccountEvent,
    ) -> &CashFlow<AssetNameExchange, InstrumentNameExchange> {
        match &event.kind {
            AccountEventKind::CashFlow(flow) => flow,
            other => panic!("expected a cash flow, got: {other:?}"),
        }
    }

    /// A request-priced margin venue holding 0.25 BTC, charged hourly on BTC loans, which has
    /// just sold 1 BTC at 50,000, borrowing 0.75, at `time(1)`.
    fn margin_venue_short_btc() -> SimulatedVenue {
        let mut venue = margin_venue("0.25", "100000", "3")
            .with_margin_interest(Arc::new(hourly_interest(base())));
        advance(&mut venue, time(1));
        venue.open_order(sell_request("1", market_prices("50000")));
        venue
    }

    #[test]
    fn a_sell_that_borrows_is_charged_a_period_of_interest_reported_after_its_balances() {
        let mut venue = margin_venue("0.25", "100000", "3")
            .with_margin_interest(Arc::new(hourly_interest(base())));
        advance(&mut venue, time(1));

        let outcome = venue.open_order(sell_request("1", market_prices("50000")));

        assert_eq!(
            filled_balance(&outcome).balance,
            Balance::new_margin(Decimal::ZERO, Decimal::ZERO, d("0.75"), d("0.000075")),
            "the interest is added to the loan, leaving total and free as they were"
        );
        assert_eq!(
            *cash_flow_of(&outcome.events[2]),
            interest_flow(
                base(),
                "0.75",
                "0.000075",
                time(1),
                InterestTiming::OnBorrow,
                "0"
            ),
            "charged on the amount lent, stamped at the borrow, after both balances"
        );
        assert_eq!(filled_trade(&outcome).quantity, d("1"));
    }

    #[test]
    fn a_loan_is_charged_on_its_principal_at_each_boundary_and_never_on_its_interest() {
        let mut venue = margin_venue_short_btc();
        assert_eq!(venue.next_deadline(), Some(boundary(0)));

        let events = venue.advance_time(boundary(1) + TimeDelta::seconds(1));
        let charged = charges(&events);

        assert_eq!(charged.len(), 2);
        assert_eq!(
            charged[0].0.balance,
            Balance::new_margin(Decimal::ZERO, Decimal::ZERO, d("0.75"), d("0.00015"))
        );
        assert_eq!(charged[0].0.time_exchange, boundary(0));
        assert_eq!(
            *charged[0].1,
            interest_flow(
                base(),
                "0.75",
                "0.000075",
                boundary(0),
                InterestTiming::Periodic,
                "1"
            )
        );
        assert_eq!(
            charged[1].0.balance,
            Balance::new_margin(Decimal::ZERO, Decimal::ZERO, d("0.75"), d("0.000225"))
        );
        assert_eq!(
            *charged[1].1,
            interest_flow(
                base(),
                "0.75",
                "0.000075",
                boundary(1),
                InterestTiming::Periodic,
                "2"
            )
        );
        assert_eq!(venue.next_deadline(), Some(boundary(2)));
    }

    #[test]
    fn a_loan_repaid_before_a_boundary_is_not_charged_there() {
        let mut venue = margin_venue_short_btc();

        // 0.76 BTC repays the 0.000075 interest, then the 0.75 principal, leaving 0.009925 free.
        let outcome = venue.open_order(with_effect(
            buy_request("0.76", market_prices("50000")),
            MarginEffect::Repay,
        ));
        assert_eq!(
            filled_received(&outcome).balance,
            Balance::new_margin(d("0.009925"), d("0.009925"), Decimal::ZERO, Decimal::ZERO)
        );

        assert_eq!(venue.next_deadline(), None);
        assert!(venue.advance_time(boundary(1)).is_empty());
    }

    #[test]
    fn a_boundary_charges_the_principal_left_after_a_partial_repay() {
        let mut venue = margin_venue_short_btc();

        // 0.5 BTC repays the 0.000075 interest, then 0.499925 of the 0.75 principal.
        venue.open_order(with_effect(
            buy_request("0.5", market_prices("50000")),
            MarginEffect::Repay,
        ));

        let events = venue.advance_time(boundary(0));
        assert_eq!(
            *charges(&events)[0].1,
            interest_flow(
                base(),
                "0.250075",
                "0.00002501",
                boundary(0),
                InterestTiming::Periodic,
                "1"
            ),
            "0.250075 at 0.01% is 0.0000250075, rounded up to the satoshi"
        );
    }

    #[test]
    fn a_loan_taken_at_a_boundary_s_instant_is_charged_there_only_at_borrow() {
        let mut venue = margin_venue("0.25", "100000", "3")
            .with_margin_interest(Arc::new(hourly_interest(base())));
        advance(&mut venue, time(1));
        advance(&mut venue, boundary(0));

        let outcome = venue.open_order(sell_request("1", market_prices("50000")));
        assert_eq!(
            *cash_flow_of(&outcome.events[2]),
            interest_flow(
                base(),
                "0.75",
                "0.000075",
                boundary(0),
                InterestTiming::OnBorrow,
                "0"
            )
        );

        assert!(
            venue
                .advance_time(boundary(0) + TimeDelta::seconds(1))
                .is_empty()
        );
        assert_eq!(venue.next_deadline(), Some(boundary(1)));
    }

    #[test]
    fn a_resting_sell_is_charged_when_placed_and_its_cancel_repays_interest_first() {
        let mut venue = margin_market_venue("0", "100000")
            .with_margin_interest(Arc::new(hourly_interest(base())));

        let outcome = venue.open_order(limit_request("rest", Side::Sell, "1", "50000", gtc()));
        assert_eq!(
            balance_of(&outcome.events[0]).balance,
            Balance::new_margin(d("1"), Decimal::ZERO, d("1"), d("0.0001"))
        );
        assert_eq!(
            *cash_flow_of(&outcome.events[1]),
            interest_flow(
                base(),
                "1",
                "0.0001",
                time(1),
                InterestTiming::OnBorrow,
                "0"
            )
        );

        let cancelled = venue.cancel_order(OrderRequestCancel {
            key: limit_request("rest", Side::Sell, "1", "50000", gtc()).key,
            state: RequestCancel { id: None },
        });
        assert_eq!(
            balance_of(&cancelled.events[0]).balance,
            Balance::new_margin(Decimal::ZERO, Decimal::ZERO, d("0.0001"), Decimal::ZERO),
            "the released base repays the interest first, so as much principal stays owed"
        );
        assert_eq!(venue.next_deadline(), Some(boundary(0)));
    }

    #[test]
    fn a_held_buy_is_charged_when_accepted_and_again_on_what_its_bar_borrows_more() {
        let mut venue =
            margin_venue_holding().with_margin_interest(Arc::new(hourly_interest(quote())));

        // 150 at the close of 100: 50 borrowed, charged 0.005.
        let outcome = venue.open_order(market_order("held", Side::Buy, "1.5", gtc()));
        assert_eq!(
            balance_of(&outcome.events[0]).balance,
            Balance::new_margin(d("150"), Decimal::ZERO, d("50"), d("0.005"))
        );
        assert_eq!(
            *cash_flow_of(&outcome.events[1]),
            interest_flow(
                quote(),
                "50",
                "0.005",
                time(1),
                InterestTiming::OnBorrow,
                "0"
            )
        );

        // 180 at an open of 120: 30 more borrowed, charged 0.003.
        let events = feed_bar(&mut venue, 2, ohlc("120", "121", "119", "120"));
        assert_eq!(
            balance_of(&events[0]).balance,
            Balance::new_margin(Decimal::ZERO, Decimal::ZERO, d("80"), d("0.008"))
        );
        assert_eq!(
            cash_flow_of(&events[2]).amount,
            d("-0.003"),
            "after both balances"
        );
        assert_eq!(trade_of(&events[3]).price, d("120"));
    }

    #[test]
    fn a_held_buy_whose_bar_repays_its_whole_loan_owes_no_more_boundaries() {
        // A zero rate charges nothing at the borrow, so the loan is exactly what was lent.
        let free_loans = PeriodicMarginInterest::new(TimeDelta::hours(1), DayCount::Act365)
            .with_rates(quote(), RateSeries::constant(Decimal::ZERO));
        let mut venue = margin_venue_holding().with_margin_interest(Arc::new(free_loans));

        // 150 at the close of 100: 50 borrowed.
        venue.open_order(market_order("held", Side::Buy, "1.5", gtc()));
        assert_eq!(venue.next_deadline(), Some(boundary(0)));

        // 90 at an open of 60: the 100 the account had pays for all of it, so all 50 is repaid.
        let events = feed_bar(&mut venue, 2, ohlc("60", "61", "59", "60"));
        assert_eq!(
            balance_of(&events[0]).balance,
            Balance::new_margin(d("10"), d("10"), Decimal::ZERO, Decimal::ZERO)
        );
        assert_eq!(venue.next_deadline(), None);
    }

    #[test]
    fn a_seeded_loan_is_charged_at_boundaries_from_the_clock_s_first_move_only() {
        let config = MockExecutionConfig {
            spot_margin: Some(
                SpotMarginConfig::new(quote(), d("3"), MarginEffect::Borrow).unwrap(),
            ),
            ..config_from_balances(
                vec![
                    AssetBalance::new(
                        base(),
                        Balance::new_margin(d("0.5"), d("0.5"), d("0.5"), Decimal::ZERO),
                        Utc::now(),
                    ),
                    funded(quote(), d("100000")),
                ],
                FeeModelConfig::default(),
            )
        };
        let mut venue = SimulatedVenue::new(&config, spot_instruments())
            .with_margin_interest(Arc::new(hourly_interest(base())));
        assert_eq!(
            venue.next_deadline(),
            None,
            "charging starts when the clock moves"
        );

        advance(&mut venue, time(1));
        assert_eq!(venue.next_deadline(), Some(boundary(0)));

        let events = venue.advance_time(boundary(0));
        assert_eq!(
            *charges(&events)[0].1,
            interest_flow(
                base(),
                "0.5",
                "0.00005",
                boundary(0),
                InterestTiming::Periodic,
                "0"
            )
        );
    }

    #[test]
    fn at_borrow_only_charges_the_borrow_and_no_boundary() {
        let mut venue = margin_venue("0.25", "100000", "3").with_margin_interest(Arc::new(
            hourly_interest(base()).with_schedule(InterestSchedule::AtBorrowOnly),
        ));
        advance(&mut venue, time(1));

        let outcome = venue.open_order(sell_request("1", market_prices("50000")));

        assert_eq!(
            filled_balance(&outcome).balance.margin.unwrap().interest,
            d("0.000075")
        );
        assert_eq!(venue.next_deadline(), None);
        assert!(venue.advance_time(boundary(3)).is_empty());
    }

    #[test]
    #[should_panic(expected = "without MockExecutionConfig::spot_margin")]
    fn a_cash_venue_given_an_interest_model_panics() {
        let _ = make_venue("1", "100000").with_margin_interest(Arc::new(hourly_interest(base())));
    }

    /// A model that breaks its contract: `boundary` returns the instant it is asked from, and
    /// `charge` refunds a satoshi.
    #[derive(Debug)]
    struct Misbehaving;

    impl MarginInterestModel for Misbehaving {
        fn next_boundary(
            &self,
            _: &AssetNameExchange,
            after: DateTime<Utc>,
        ) -> Option<DateTime<Utc>> {
            Some(after)
        }

        fn charge(
            &self,
            _: &AssetNameExchange,
            _: Decimal,
            _: InterestDue,
        ) -> Option<InterestCharge> {
            Some(InterestCharge::new(d("-0.00000001"), None))
        }
    }

    /// A model charging a satoshi at every borrow, whatever was lent, and at no boundary.
    #[derive(Debug)]
    struct FlatAtBorrow;

    impl MarginInterestModel for FlatAtBorrow {
        fn next_boundary(&self, _: &AssetNameExchange, _: DateTime<Utc>) -> Option<DateTime<Utc>> {
            None
        }

        fn charge(
            &self,
            _: &AssetNameExchange,
            _: Decimal,
            due: InterestDue,
        ) -> Option<InterestCharge> {
            matches!(due, InterestDue::Borrow(_))
                .then(|| InterestCharge::new(d("0.00000001"), None))
        }
    }

    #[test]
    fn an_order_that_borrows_nothing_is_not_asked_about_interest() {
        let mut venue =
            margin_venue("0.25", "100000", "3").with_margin_interest(Arc::new(FlatAtBorrow));
        advance(&mut venue, time(1));

        let outcome = venue.open_order(sell_request("0.1", market_prices("50000")));

        assert_eq!(filled_trade(&outcome).quantity, d("0.1"));
        assert!(
            !outcome
                .events
                .iter()
                .any(|event| matches!(event.kind, AccountEventKind::CashFlow(_))),
            "0.1 of the 0.25 held lends nothing, so nothing is charged"
        );
    }

    #[test]
    #[should_panic(expected = "charged negative interest")]
    fn a_model_charging_negative_interest_panics() {
        let mut venue =
            margin_venue("0.25", "100000", "3").with_margin_interest(Arc::new(Misbehaving));
        advance(&mut venue, time(1));

        let _ = venue.open_order(sell_request("1", market_prices("50000")));
    }

    #[test]
    #[should_panic(expected = "which is not after")]
    fn a_model_whose_boundary_is_not_after_the_instant_asked_panics() {
        let config = MockExecutionConfig {
            spot_margin: Some(
                SpotMarginConfig::new(quote(), d("3"), MarginEffect::Borrow).unwrap(),
            ),
            ..config_from_balances(
                vec![
                    AssetBalance::new(
                        base(),
                        Balance::new_margin(d("0.5"), d("0.5"), d("0.5"), Decimal::ZERO),
                        Utc::now(),
                    ),
                    funded(quote(), d("100000")),
                ],
                FeeModelConfig::default(),
            )
        };
        let mut venue = SimulatedVenue::new(&config, spot_instruments())
            .with_margin_interest(Arc::new(Misbehaving));

        let _ = venue.advance_time(time(1));
    }

    // ---------------------------------------------------------------------------------------
    // Fees charged in a third asset (`FeeAssetConfig`).
    // ---------------------------------------------------------------------------------------

    fn bnb() -> AssetNameExchange {
        AssetNameExchange::new("BNB")
    }

    fn spot_instrument(
        name: &str,
        base: &str,
        quote: &str,
    ) -> Instrument<ExchangeId, AssetNameExchange> {
        Instrument {
            exchange: EXCHANGE,
            name_internal: InstrumentNameInternal::new(name.to_lowercase()),
            name_exchange: InstrumentNameExchange::new(name),
            underlying: Underlying {
                base: AssetNameExchange::new(base),
                quote: AssetNameExchange::new(quote),
            },
            quote: InstrumentQuoteAsset::UnderlyingQuote,
            kind: InstrumentKind::Spot,
            spec: None,
            data_venue: None,
        }
    }

    /// `BTCUSDT` as `spot_instruments` gives it, and `BNBUSDT`, which prices the fee asset.
    fn fee_asset_instruments()
    -> FnvHashMap<InstrumentNameExchange, Instrument<ExchangeId, AssetNameExchange>> {
        let mut instruments = spot_instruments();
        let bnb_usdt = spot_instrument("BNBUSDT", "BNB", "USDT");
        instruments.insert(bnb_usdt.name_exchange.clone(), bnb_usdt);
        instruments
    }

    /// 10 BTC, 100,000 USDT and `bnb` BNB, maker 2bp against taker 10bp, and fees in BNB at a
    /// quarter off.
    fn fee_asset_config(bnb: &str) -> MockExecutionConfig {
        MockExecutionConfig {
            fee_asset: Some(FeeAssetConfig::new(self::bnb(), d("0.25")).unwrap()),
            ..config_from_balances(
                vec![
                    funded(base(), d("10")),
                    funded(quote(), d("100000")),
                    funded(self::bnb(), d(bnb)),
                ],
                maker_taker_fee(),
            )
        }
    }

    /// A fed venue for `config`, `BTCUSDT` last traded at 50,000, and `BNBUSDT` at a 599 / 601
    /// book, a mid of 600, when `priced`.
    fn fee_asset_venue_from(config: &MockExecutionConfig, priced: bool) -> SimulatedVenue {
        let mut venue = SimulatedVenue::new_market_driven(config, fee_asset_instruments());
        advance(&mut venue, time(1));
        if priced {
            assert!(
                venue
                    .apply_market(
                        &InstrumentNameExchange::new("BNBUSDT"),
                        MarketObservation::new(book("599", "601")),
                        time(1)
                    )
                    .is_empty()
            );
        }
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(traded("50000")),
                    time(1)
                )
                .is_empty()
        );
        venue
    }

    fn fee_asset_venue(bnb: &str) -> SimulatedVenue {
        fee_asset_venue_from(&fee_asset_config(bnb), true)
    }

    /// The balance restatements an outcome's events carry, by asset.
    fn restated(events: &[UnindexedAccountEvent]) -> Vec<(AssetNameExchange, Balance)> {
        events
            .iter()
            .filter_map(|event| match &event.kind {
                AccountEventKind::BalanceSnapshot(balance) => {
                    Some((balance.0.asset.clone(), balance.0.balance))
                }
                _ => None,
            })
            .collect()
    }

    /// A taker buy of 1 BTC at 50,000 pays the 50 USDT fee as 37.50 at a quarter off, which is
    /// 0.0625 BNB at 600, out of the BNB balance, and exchanges its two assets free of fee.
    #[test]
    fn a_fill_pays_its_fee_in_the_fee_asset_at_a_discount() {
        let mut venue = fee_asset_venue("1");

        let outcome = venue.open_order(buy_request("1", None));

        assert_eq!(
            filled_trade(&outcome).fees,
            AssetFees::new(bnb(), d("0.0625"), Some(d("37.5")))
        );
        assert_eq!(
            restated(&outcome.events),
            vec![
                (quote(), Balance::new(d("50000"), d("50000"))),
                (base(), Balance::new(d("11"), d("11"))),
                (bnb(), Balance::new(d("0.9375"), d("0.9375"))),
            ]
        );
    }

    #[test]
    fn a_sell_receives_its_whole_proceeds_and_pays_its_fee_in_the_fee_asset() {
        let mut venue = fee_asset_venue("1");

        let outcome = venue.open_order(sell_request("1", None));

        assert_eq!(filled_trade(&outcome).fees.asset, bnb());
        assert_eq!(
            restated(&outcome.events),
            vec![
                (base(), Balance::new(d("9"), d("9"))),
                (quote(), Balance::new(d("150000"), d("150000"))),
                (bnb(), Balance::new(d("0.9375"), d("0.9375"))),
            ]
        );
    }

    /// With less of the fee asset than the fee, the whole fee is charged undiscounted in quote,
    /// none of it split, and the fee asset is untouched.
    #[test]
    fn a_fee_asset_balance_short_of_the_fee_falls_back_whole() {
        for bnb in ["0.0624", "0"] {
            let mut venue = fee_asset_venue(bnb);

            let outcome = venue.open_order(buy_request("1", None));

            assert_eq!(
                filled_trade(&outcome).fees,
                AssetFees::new(quote(), d("50"), Some(d("50"))),
                "{bnb} BNB"
            );
            assert_eq!(
                restated(&outcome.events),
                vec![
                    (quote(), Balance::new(d("49950"), d("49950"))),
                    (base(), Balance::new(d("11"), d("11"))),
                ],
                "{bnb} BNB"
            );
        }
    }

    /// Exactly the fee is enough.
    #[test]
    fn a_fee_asset_balance_of_exactly_the_fee_pays_it() {
        let mut venue = fee_asset_venue("0.0625");

        let outcome = venue.open_order(buy_request("1", None));

        assert_eq!(filled_trade(&outcome).fees.asset, bnb());
        assert_eq!(balance_now(&venue, bnb()), Balance::new(d("0"), d("0")));
    }

    #[test]
    fn a_fee_asset_the_venue_cannot_price_falls_back() {
        let mut venue = fee_asset_venue_from(&fee_asset_config("1"), false);

        let outcome = venue.open_order(buy_request("1", None));

        assert_eq!(
            filled_trade(&outcome).fees,
            AssetFees::new(quote(), d("50"), Some(d("50")))
        );
        assert_eq!(balance_now(&venue, bnb()), Balance::new(d("1"), d("1")));
    }

    /// On the fee asset's own instrument the venue charges as without the setting.
    #[test]
    fn a_fill_on_the_fee_assets_own_instrument_falls_back() {
        let mut venue = fee_asset_venue("1");
        assert!(
            venue
                .apply_market(
                    &InstrumentNameExchange::new("BNBUSDT"),
                    MarketObservation::new(traded("600")),
                    time(1)
                )
                .is_empty()
        );
        let mut request = buy_request("1", None);
        request.key.instrument = InstrumentNameExchange::new("BNBUSDT");

        let outcome = venue.open_order(request);

        // 600 × 10bp in quote, undiscounted.
        assert_eq!(
            filled_trade(&outcome).fees,
            AssetFees::new(quote(), d("0.6"), Some(d("0.6")))
        );
        assert_eq!(balance_now(&venue, bnb()), Balance::new(d("2"), d("2")));
    }

    /// A resting buy holds its fee as the fallback would charge it, in quote. When it fills with
    /// the fee paid in BNB, that part of the hold comes back.
    #[test]
    fn a_resting_fill_paid_in_the_fee_asset_releases_the_fee_it_held() {
        let mut venue = fee_asset_venue("1");
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(book("49000", "49100")),
                    time(1)
                )
                .is_empty()
        );
        let outcome = venue.open_order(limit_request("resting", Side::Buy, "1", "49000", gtc()));
        // 49,000 plus the maker fee of 9.80 is held.
        assert_eq!(
            filled_balance(&outcome).balance,
            Balance::new(d("100000"), d("50990.2"))
        );

        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("48900", "48950")),
            time(2),
        );

        // The maker fee of 9.80, a quarter off, at 600: 0.01225 BNB.
        let trade = events
            .iter()
            .find_map(|event| match &event.kind {
                AccountEventKind::Trade(trade) => Some(trade),
                _ => None,
            })
            .unwrap();
        assert_eq!(
            trade.fees,
            AssetFees::new(bnb(), d("0.01225"), Some(d("7.35")))
        );
        assert_eq!(
            restated(&events),
            vec![
                (quote(), Balance::new(d("51000"), d("51000"))),
                (base(), Balance::new(d("11"), d("11"))),
                (bnb(), Balance::new(d("0.98775"), d("0.98775"))),
            ]
        );
    }

    /// Under `Received`, a buy paying its fee in BNB receives its whole quantity.
    #[test]
    fn under_received_a_buy_paying_in_the_fee_asset_receives_its_whole_quantity() {
        let config = MockExecutionConfig {
            spot_fee_asset: SpotFeeAsset::Received,
            ..fee_asset_config("1")
        };
        let mut venue = fee_asset_venue_from(&config, true);

        let outcome = venue.open_order(buy_request("1", None));

        assert_eq!(filled_trade(&outcome).fees.asset, bnb());
        assert_eq!(balance_now(&venue, base()).total, d("11"));
        assert_eq!(balance_now(&venue, quote()).total, d("50000"));
    }

    #[test]
    fn a_zero_fee_is_charged_without_the_fee_asset() {
        let config = MockExecutionConfig {
            fee_model: FeeModelConfig::default(),
            ..fee_asset_config("1")
        };
        let mut venue = fee_asset_venue_from(&config, true);

        let outcome = venue.open_order(buy_request("1", None));

        assert_eq!(
            filled_trade(&outcome).fees,
            AssetFees::new(quote(), Decimal::ZERO, Some(Decimal::ZERO))
        );
        assert_eq!(balance_now(&venue, bnb()), Balance::new(d("1"), d("1")));
    }

    /// A discount of one charges nothing, even to an account that has never held the fee asset.
    #[test]
    fn a_full_discount_charges_nothing_and_needs_no_fee_asset_balance() {
        let config = MockExecutionConfig {
            fee_asset: Some(FeeAssetConfig::new(bnb(), Decimal::ONE).unwrap()),
            ..config_from_balances(
                vec![funded(base(), d("10")), funded(quote(), d("100000"))],
                maker_taker_fee(),
            )
        };
        let mut venue = fee_asset_venue_from(&config, true);

        let outcome = venue.open_order(buy_request("1", None));

        assert_eq!(
            filled_trade(&outcome).fees,
            AssetFees::new(bnb(), Decimal::ZERO, Some(Decimal::ZERO))
        );
        assert_eq!(
            restated(&outcome.events),
            vec![
                (quote(), Balance::new(d("50000"), d("50000"))),
                (base(), Balance::new(d("11"), d("11"))),
            ]
        );
    }

    /// A market order held for its next bar pays its fee in BNB when the bar fills it.
    #[test]
    fn a_held_market_order_pays_its_fee_in_the_fee_asset() {
        let config = MockExecutionConfig {
            market_order_timing: MarketOrderTiming::NextBar(NextBarPrice::Open),
            ..fee_asset_config("1")
        };
        let mut venue = SimulatedVenue::new_market_driven(&config, fee_asset_instruments());
        advance(&mut venue, time(1));
        assert!(
            venue
                .apply_market(
                    &InstrumentNameExchange::new("BNBUSDT"),
                    MarketObservation::new(book("599", "601")),
                    time(1)
                )
                .is_empty()
        );
        assert!(feed_bar(&mut venue, 1, ohlc("95", "105", "90", "100")).is_empty());
        let held = venue.open_order(ioc_buy("held", "1"));
        assert!(held.response.state.is_accepted());

        advance(&mut venue, time(2));
        let events = feed_bar(&mut venue, 2, ohlc("200", "210", "190", "205"));

        // 200 × 10bp, a quarter off, at 600: 0.00025 BNB.
        assert_eq!(
            restated(&events),
            vec![
                (quote(), Balance::new(d("99800"), d("99800"))),
                (base(), Balance::new(d("11"), d("11"))),
                (bnb(), Balance::new(d("0.99975"), d("0.99975"))),
            ]
        );
    }

    /// On an instrument quoting in the fee asset the venue charges as without the setting too:
    /// the fee is undiscounted, in quote, which is the fee asset, under the `SpotFeeAsset` rule.
    #[test]
    fn a_fill_on_an_instrument_quoted_in_the_fee_asset_falls_back() {
        let mut instruments = fee_asset_instruments();
        let eth_bnb = spot_instrument("ETHBNB", "ETH", "BNB");
        instruments.insert(eth_bnb.name_exchange.clone(), eth_bnb);
        let eth = || AssetNameExchange::new("ETH");
        let config = MockExecutionConfig {
            fee_asset: Some(FeeAssetConfig::new(bnb(), d("0.25")).unwrap()),
            ..config_from_balances(
                vec![
                    funded(base(), d("10")),
                    funded(quote(), d("100000")),
                    funded(bnb(), d("10")),
                    funded(eth(), d("1")),
                ],
                maker_taker_fee(),
            )
        };

        for (side, eth_after, bnb_after) in [
            // 0.5 BNB plus 0.0005 on top.
            (Side::Buy, "2", "9.4995"),
            // 0.5 BNB less 0.0005 out of it.
            (Side::Sell, "0", "10.4995"),
        ] {
            let mut venue = SimulatedVenue::new_market_driven(&config, instruments.clone());
            advance(&mut venue, time(1));
            assert!(
                venue
                    .apply_market(
                        &InstrumentNameExchange::new("ETHBNB"),
                        MarketObservation::new(traded("0.5")),
                        time(1)
                    )
                    .is_empty()
            );
            let mut request = match side {
                Side::Buy => buy_request("1", None),
                Side::Sell => sell_request("1", None),
            };
            request.key.instrument = InstrumentNameExchange::new("ETHBNB");

            let outcome = venue.open_order(request);

            // 0.5 × 10bp, undiscounted.
            assert_eq!(
                filled_trade(&outcome).fees,
                AssetFees::new(bnb(), d("0.0005"), Some(d("0.0005"))),
                "{side:?}"
            );
            assert_eq!(balance_now(&venue, eth()).total, d(eth_after), "{side:?}");
            assert_eq!(balance_now(&venue, bnb()).total, d(bnb_after), "{side:?}");
        }
    }

    /// A maker rebate is a negative fee, which stays in quote: the venue pays no rebate in the
    /// fee asset.
    #[test]
    fn a_negative_fee_is_paid_without_the_fee_asset() {
        let rebate =
            FeeModelConfig::Percentage(PercentageFeeModel::maker_taker(d("-0.0001"), d("-0.0001")));
        let config = MockExecutionConfig {
            fee_model: rebate,
            ..fee_asset_config("1")
        };
        let mut venue = fee_asset_venue_from(&config, true);

        let outcome = venue.open_order(buy_request("1", None));

        assert_eq!(
            filled_trade(&outcome).fees,
            AssetFees::new(quote(), d("-5"), Some(d("-5")))
        );
        assert_eq!(balance_now(&venue, quote()).total, d("50005"));
        assert_eq!(balance_now(&venue, bnb()), Balance::new(d("1"), d("1")));
    }

    /// `USDTBNB` at a last price of 0.0016 prices BNB at its reciprocal, 625, and of two pairs
    /// pricing it, the one first by name is used.
    #[test]
    fn the_fee_asset_is_priced_by_a_reciprocal_pair_or_the_pair_first_by_name() {
        let usdt_bnb = spot_instrument("USDTBNB", "USDT", "BNB");
        let feed = |venue: &mut SimulatedVenue, name: &str, price: &str| {
            assert!(
                venue
                    .apply_market(
                        &InstrumentNameExchange::new(name),
                        MarketObservation::new(traded(price)),
                        time(1)
                    )
                    .is_empty()
            );
        };

        // Only `USDTBNB`: 37.50 at 625 is 0.06 BNB.
        let mut instruments = spot_instruments();
        instruments.insert(usdt_bnb.name_exchange.clone(), usdt_bnb.clone());
        let mut venue = SimulatedVenue::new_market_driven(&fee_asset_config("1"), instruments);
        advance(&mut venue, time(1));
        feed(&mut venue, "USDTBNB", "0.0016");
        feed(&mut venue, "BTCUSDT", "50000");
        let outcome = venue.open_order(buy_request("1", None));
        assert_eq!(
            filled_trade(&outcome).fees,
            AssetFees::new(bnb(), d("0.06"), Some(d("37.5")))
        );

        // Both: `BNBUSDT`, at a last price of 600, is first by name though fed first. 0.0625 BNB.
        let mut instruments = fee_asset_instruments();
        instruments.insert(usdt_bnb.name_exchange.clone(), usdt_bnb);
        let mut venue = SimulatedVenue::new_market_driven(&fee_asset_config("1"), instruments);
        advance(&mut venue, time(1));
        feed(&mut venue, "BNBUSDT", "600");
        feed(&mut venue, "USDTBNB", "0.0016");
        feed(&mut venue, "BTCUSDT", "50000");
        let outcome = venue.open_order(buy_request("1", None));
        assert_eq!(
            filled_trade(&outcome).fees,
            AssetFees::new(bnb(), d("0.0625"), Some(d("37.5")))
        );
    }

    /// A marketable buy that fills half against the offer and rests the rest pays the filled
    /// half's fee in BNB, and holds the resting half's fee as the fallback would charge it.
    #[test]
    fn a_partly_filled_order_pays_its_fill_in_the_fee_asset_and_holds_the_rest_in_quote() {
        let mut venue = fee_asset_venue("1");
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(book("49000", "49100"))
                        .with_depth(MarketDepth::new(None, Some(d("0.5")))),
                    time(1),
                )
                .is_empty()
        );

        let outcome = venue.open_order(limit_request("part", Side::Buy, "1", "49100", gtc()));

        assert_eq!(rested_open(&outcome).filled_quantity, d("0.5"));
        // 24,550 × 10bp, a quarter off, at 600.
        assert_eq!(
            filled_trade(&outcome).fees,
            AssetFees::new(bnb(), d("0.0306875"), Some(d("18.4125")))
        );
        // 24,550 paid, and 24,550 plus the maker fee of 4.91 held for the resting half.
        assert_eq!(
            balance_now(&venue, quote()),
            Balance::new(d("75450"), d("50895.09"))
        );
        assert_eq!(
            balance_now(&venue, bnb()),
            Balance::new(d("0.9693125"), d("0.9693125"))
        );
    }

    /// 10,000 USDT on a 3× margin account, BTC flat, paying fees in BNB and charged hourly on
    /// USDT loans, `BTCUSDT` at 50,000 and BNB at 600.
    fn fee_asset_margin_venue(bnb: &str) -> SimulatedVenue {
        let config = MockExecutionConfig {
            spot_margin: Some(
                SpotMarginConfig::new(quote(), d("3"), MarginEffect::Borrow).unwrap(),
            ),
            fee_asset: Some(FeeAssetConfig::new(self::bnb(), d("0.25")).unwrap()),
            ..config_from_balances(
                vec![
                    funded(base(), Decimal::ZERO),
                    funded(quote(), d("10000")),
                    funded(self::bnb(), d(bnb)),
                ],
                maker_taker_fee(),
            )
        };
        fee_asset_venue_from(&config, true).with_margin_interest(Arc::new(hourly_interest(quote())))
    }

    /// A buy of 0.3 BTC borrows the 5,000 USDT it pays beyond the account's own, and no more,
    /// since its fee is paid in BNB. The BNB restates after the fill's own balances, and the
    /// interest on the loan is reported after all three.
    #[test]
    fn a_margin_buy_paying_in_the_fee_asset_borrows_only_its_notional() {
        let mut venue = fee_asset_margin_venue("1");

        let outcome = venue.open_order(buy_request("0.3", None));

        // 15,000 × 10bp, a quarter off, at 600.
        assert_eq!(
            filled_trade(&outcome).fees,
            AssetFees::new(bnb(), d("0.01875"), Some(d("11.25")))
        );
        let paid = balance_of(&outcome.events[0]);
        assert_eq!(paid.asset, quote());
        assert_eq!(
            paid.balance.margin.map(|margin| margin.borrowed),
            Some(d("5000"))
        );
        assert_eq!(balance_of(&outcome.events[1]).asset, base());
        assert_eq!(
            *balance_of(&outcome.events[2]),
            AssetBalance::new(
                bnb(),
                Balance::new_margin(d("0.98125"), d("0.98125"), d("0"), d("0")),
                time(1)
            )
        );
        // 5,000 at 0.01% for the hour.
        assert_eq!(
            *cash_flow_of(&outcome.events[3]),
            interest_flow(
                quote(),
                "5000",
                "0.5",
                time(1),
                InterestTiming::OnBorrow,
                "0"
            )
        );
    }

    /// With no BNB, the fee falls back to quote, which the venue lends with the notional; it
    /// never lends BNB for a fee.
    #[test]
    fn a_margin_account_short_of_the_fee_asset_borrows_the_fallback_fee_not_the_fee_asset() {
        let mut venue = fee_asset_margin_venue("0");

        let outcome = venue.open_order(buy_request("0.3", None));

        assert_eq!(
            filled_trade(&outcome).fees,
            AssetFees::new(quote(), d("15"), Some(d("15")))
        );
        assert_eq!(
            balance_now(&venue, quote())
                .margin
                .map(|margin| margin.borrowed),
            Some(d("5015"))
        );
        assert_eq!(
            balance_now(&venue, bnb()),
            Balance::new_margin(d("0"), d("0"), d("0"), d("0"))
        );
    }

    /// A resting buy borrows for its notional and its fallback fee. Filled with the fee paid in
    /// BNB, it repays the part of the loan the fee no longer needs, interest first.
    #[test]
    fn a_resting_margin_fill_paying_in_the_fee_asset_repays_the_fee_it_borrowed() {
        let mut venue = fee_asset_margin_venue("1");
        assert!(
            venue
                .apply_market(
                    &instrument_name(),
                    MarketObservation::new(book("49000", "49100")),
                    time(1)
                )
                .is_empty()
        );
        let outcome = venue.open_order(limit_request("resting", Side::Buy, "0.3", "49000", gtc()));
        // 14,700 plus the maker fee of 2.94, beyond the 10,000 held, and an hour's interest on it.
        assert_eq!(
            filled_balance(&outcome).balance,
            Balance::new_margin(d("14702.94"), d("0"), d("4702.94"), d("0.470294"))
        );

        let events = venue.apply_market(
            &instrument_name(),
            MarketObservation::new(book("48900", "48950")),
            time(2),
        );

        // 2.94, a quarter off, at 600.
        let trade = events
            .iter()
            .find_map(|event| match &event.kind {
                AccountEventKind::Trade(trade) => Some(trade),
                _ => None,
            })
            .unwrap();
        assert_eq!(
            trade.fees,
            AssetFees::new(bnb(), d("0.003675"), Some(d("2.205")))
        );
        // The 2.94 no longer needed repays the 0.470294 of interest, then 2.469706 of the loan.
        assert_eq!(
            balance_now(&venue, quote()),
            Balance::new_margin(d("0"), d("0"), d("4700.470294"), d("0"))
        );
        assert_eq!(balance_now(&venue, bnb()).total, d("0.996325"));
    }

    /// A CFD fill is cash-settled, so its fee stays in quote even with the fee asset priced.
    #[test]
    fn a_cfd_fill_is_charged_without_the_fee_asset() {
        let mut instruments = instruments_of(cfd_instrument());
        let bnb_usd = spot_instrument("BNBUSD", "BNB", "usd");
        instruments.insert(bnb_usd.name_exchange.clone(), bnb_usd);
        let config = MockExecutionConfig {
            fee_asset: Some(FeeAssetConfig::new(bnb(), d("0.25")).unwrap()),
            ..config_from_balances(
                vec![funded(usd(), d("1000000")), funded(bnb(), d("10"))],
                maker_taker_fee(),
            )
        };
        let mut venue = SimulatedVenue::new_market_driven(&config, instruments);
        advance(&mut venue, time(1));
        assert!(
            venue
                .apply_market(
                    &InstrumentNameExchange::new("BNBUSD"),
                    MarketObservation::new(traded("600")),
                    time(1)
                )
                .is_empty()
        );
        assert!(cfd_market(&mut venue, "4999", "5001", "5000").is_empty());

        let outcome = venue.open_order(cfd_request(Side::Buy, "1", None));

        assert_eq!(filled_trade(&outcome).fees.asset, usd());
        assert_eq!(balance_now(&venue, bnb()).total, d("10"));
    }
}