wickra-backtest-core 0.1.3

Streaming-native backtest engine core (strategy spec, rules, execution, portfolio) built on wickra-core.
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
//! The event-driven backtest loop.
//!
//! Look-ahead bias is structurally prevented by default: signal-driven orders
//! are decided on a bar's **close** and fill on the **next bar's open**. An
//! opt-in `fill_timing: "close"` instead fills market orders on the signalling
//! bar's own close (close-to-close, deliberately optimistic). Stop-loss and
//! take-profit are price levels checked **intrabar** against each bar's OHLC and
//! fill at the level (conservative: the stop is assumed hit before the target
//! when a bar's range brackets both). Equity is marked to market at every close.
//!
//! Supports long and short positions; market, limit and stop entry orders (a
//! limit/stop rests at a percent offset from the signal close and fills when a
//! later bar reaches it, otherwise it keeps working); maker/taker fees (resting
//! limit fills pay maker, market/stop fills pay taker) and fixed-bps, order-book-spread or
//! volume-impact slippage; and leverage / position sizing (fixed fraction / cash / quantity,
//! risk-per-trade and vol-target, capped by `max_leverage` and
//! `max_position_pct`; without `max_leverage` the cap is 1x equity — no leverage
//! by default). Execution latency (`latency_bars`) delays every fill, and
//! volume-participation partial fills (`partial_fills` + `max_participation`)
//! cap an entry to a fraction of the bar's volume. Perpetual funding
//! (`costs.funding`) is charged each bar to an open position from the
//! derivatives feed, and a leveraged position is liquidated intrabar at its
//! bankruptcy price when `risk.liquidation` is set.

use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;

use wickra_core::{
    CrossSection as CoreCrossSection, DerivativesTick as CoreDerivativesTick,
    OrderBook as CoreOrderBook, Trade as CoreTrade,
};

use crate::data::{Candle, CrossSection, DerivativesTick, OrderBook, TradePrint};
use crate::error::{BacktestError, Result};
use crate::metrics;
use crate::portfolio::Portfolio;
use crate::registry::{self, BarInput, EvalIndicator};
use crate::report::{BacktestReport, EquityPoint, REPORT_SCHEMA_VERSION};
use crate::rules::{condition_lookback, eval_condition, BarRow, RuleState};
use crate::spec::{Execution, FillTiming, OrderType, Risk, Sizing, Slippage, StrategySpec};

/// Default starting capital for the runner.
pub const DEFAULT_CAPITAL: f64 = 10_000.0;

#[derive(Debug, Clone, Copy)]
enum Side {
    Long,
    Short,
}

/// A resting limit or stop trigger.
#[derive(Debug, Clone, Copy)]
enum LevelKind {
    Limit,
    Stop,
    /// Stop-limit: the trigger is the stop, and touching it activates a limit
    /// order at `limit`. Carrying the limit here rather than beside the trigger
    /// keeps the resting order one value, the way the other two kinds are.
    StopLimit {
        limit: f64,
    },
}

/// What a working order does once it fills.
#[derive(Debug)]
enum Action {
    /// An entry. `trigger` is `None` for a market order (fills at the next
    /// open) or a resting limit/stop level (fills when the bar reaches it).
    Enter {
        side: Side,
        trigger: Option<(f64, LevelKind)>,
    },
    /// A market exit, fills at the next open.
    Exit(&'static str),
}

/// A working order, decided on a bar's close and filled on a later bar. `delay`
/// counts down the simulated execution latency before the order is eligible.
#[derive(Debug)]
struct Pending {
    action: Action,
    delay: u32,
}

/// Fill price for a resting level order against a bar, or `None` if not reached.
/// A buy fills at the open when it gaps through the level (open below a limit,
/// above a stop), otherwise at the level; a sell mirrors this.
fn level_fill(side: Side, trigger: f64, kind: LevelKind, c: &Candle) -> Option<f64> {
    let is_buy = matches!(side, Side::Long);
    match (is_buy, kind) {
        (true, LevelKind::Limit) => (c.low <= trigger).then(|| c.open.min(trigger)),
        (true, LevelKind::Stop) => (c.high >= trigger).then(|| c.open.max(trigger)),
        (false, LevelKind::Limit) => (c.high >= trigger).then(|| c.open.max(trigger)),
        (false, LevelKind::Stop) => (c.low <= trigger).then(|| c.open.min(trigger)),
        // A stop-limit needs both: the stop has to be touched, and the limit has
        // to be reachable within the same bar. The second condition is the whole
        // point of the order -- a stop that gaps far through its limit does not
        // fill, where a plain stop would have filled at the open. `activation` is
        // where the stop takes effect (the open when the bar gapped past it,
        // otherwise the stop itself), and the limit caps how far the fill may
        // travel from there.
        (true, LevelKind::StopLimit { limit }) => {
            (c.high >= trigger && c.low <= limit).then(|| limit.min(c.open.max(trigger)))
        }
        (false, LevelKind::StopLimit { limit }) => {
            (c.low <= trigger && c.high >= limit).then(|| limit.max(c.open.min(trigger)))
        }
    }
}

/// The resting trigger level for an entry, or `None` for a market order. The
/// level is the signal bar's close shifted by the configured limit/stop offset.
fn entry_trigger(exec: &Execution, signal_close: f64) -> Option<(f64, LevelKind)> {
    match exec.order_type {
        OrderType::Limit => Some((
            signal_close * (1.0 + exec.limit_offset_pct.unwrap_or(0.0) / 100.0),
            LevelKind::Limit,
        )),
        OrderType::Stop => Some((
            signal_close * (1.0 + exec.stop_offset_pct.unwrap_or(0.0) / 100.0),
            LevelKind::Stop,
        )),
        OrderType::StopLimit => Some((
            signal_close * (1.0 + exec.stop_offset_pct.unwrap_or(0.0) / 100.0),
            LevelKind::StopLimit {
                limit: signal_close * (1.0 + exec.limit_offset_pct.unwrap_or(0.0) / 100.0),
            },
        )),
        OrderType::Market => None,
    }
}

/// Realized per-bar return volatility (standard deviation of simple
/// close-to-close returns) over the last `lookback` bars, or `None` if there is
/// not enough history or the series is flat.
fn realized_vol(history: &[BarRow], lookback: usize) -> Option<f64> {
    if lookback < 2 || history.len() < lookback {
        return None;
    }
    let closes: Vec<f64> = history[history.len() - lookback..]
        .iter()
        .map(|row| row.candle.close)
        .collect();
    let rets: Vec<f64> = closes
        .windows(2)
        .filter(|w| w[0].abs() > f64::EPSILON)
        .map(|w| (w[1] - w[0]) / w[0])
        .collect();
    if rets.is_empty() {
        return None;
    }
    let mean = rets.iter().sum::<f64>() / rets.len() as f64;
    let var = rets.iter().map(|r| (r - mean).powi(2)).sum::<f64>() / rets.len() as f64;
    let sd = var.sqrt();
    (sd > 0.0).then_some(sd)
}

/// Slippage rate (a fraction of price): fixed basis points, the order book's
/// half-spread relative to the mid, or a linear function of the order's share of
/// the bar volume. Missing inputs (no book / zero volume) yield zero.
fn slippage_rate(
    slippage: Slippage,
    orderbook: Option<&CoreOrderBook>,
    qty: f64,
    volume: f64,
) -> f64 {
    match slippage {
        Slippage::FixedBps { bps } => bps / 10_000.0,
        Slippage::Spread => orderbook.map_or(0.0, |ob| match (ob.best_bid(), ob.best_ask()) {
            (Some(bid), Some(ask)) => {
                let mid = f64::midpoint(ask.price, bid.price);
                if mid > 0.0 {
                    (ask.price - bid.price) / 2.0 / mid
                } else {
                    0.0
                }
            }
            _ => 0.0,
        }),
        Slippage::VolumeImpact { coef } => {
            if volume > 0.0 {
                coef * qty.abs() / volume
            } else {
                0.0
            }
        }
    }
}

/// Context an entry/exit fill needs from the run loop.
struct FillCtx<'a> {
    spec: &'a StrategySpec,
    candle: &'a Candle,
    history: &'a [BarRow],
    orderbook: Option<&'a CoreOrderBook>,
    maker: f64,
    taker: f64,
    bar: usize,
}

/// Open a position at `raw_price` (before slippage), honouring the sizing model,
/// leverage caps and volume-participation partial fills. `maker_fill` charges
/// the maker fee (resting limit fills) instead of the taker fee.
fn execute_entry(
    side: Side,
    raw_price: f64,
    maker_fill: bool,
    ctx: &FillCtx,
    pf: &mut Portfolio,
    entry_bar: &mut Option<usize>,
    extreme: &mut f64,
) -> Result<()> {
    let dir = match side {
        Side::Long => 1.0,
        Side::Short => -1.0,
    };
    let rv = match ctx.spec.sizing {
        Sizing::VolTarget { lookback, .. } => realized_vol(ctx.history, lookback as usize),
        _ => None,
    };
    // Volume-impact slippage needs the order size; probe it at the raw price.
    let probe_qty = match ctx.spec.costs.slippage {
        Slippage::VolumeImpact { .. } => {
            size(ctx.spec.sizing, &ctx.spec.risk, pf.cash, raw_price, rv)?.unwrap_or(0.0)
        }
        _ => 0.0,
    };
    let slip = slippage_rate(
        ctx.spec.costs.slippage,
        ctx.orderbook,
        probe_qty,
        ctx.candle.volume,
    );
    let fill = raw_price * (1.0 + dir * slip);
    if let Some(base) = size(ctx.spec.sizing, &ctx.spec.risk, pf.cash, fill, rv)? {
        // Immediate-or-cancel partial fills: take at most a participation cap of
        // the bar's volume.
        let base = if ctx.spec.execution.partial_fills {
            let cap = ctx.spec.execution.max_participation.unwrap_or(0.0) * ctx.candle.volume;
            base.min(cap)
        } else {
            base
        };
        if base > 0.0 {
            let rate = if maker_fill { ctx.maker } else { ctx.taker };
            let fee = base * fill * rate;
            pf.enter(dir * base, fill, ctx.candle.time, fee);
            *entry_bar = Some(ctx.bar);
            *extreme = fill;
        }
    }
    Ok(())
}

/// Close the open position at `raw_price` (before slippage).
fn execute_exit(
    reason: &'static str,
    raw_price: f64,
    ctx: &FillCtx,
    pf: &mut Portfolio,
    entry_bar: &mut Option<usize>,
) {
    if !pf.in_position() {
        return;
    }
    // Long exit sells (fills lower), short exit buys (fills higher).
    let dir = if pf.is_long() { -1.0 } else { 1.0 };
    let slip = slippage_rate(
        ctx.spec.costs.slippage,
        ctx.orderbook,
        pf.qty,
        ctx.candle.volume,
    );
    let fill = raw_price * (1.0 + dir * slip);
    let fee = pf.qty.abs() * fill * ctx.taker;
    pf.exit(fill, ctx.candle.time, fee, reason);
    *entry_bar = None;
}

/// The optional non-OHLCV feeds for one bar: a reference-series close (pairwise),
/// a derivatives tick (derivatives) and an order-book snapshot (order-book).
/// Absent feeds are `None`; indicators that need a missing feed yield nothing.
#[derive(Debug, Default)]
pub struct Feeds<'a> {
    /// Reference-series close for pairwise indicators.
    pub reference: Option<f64>,
    /// Derivatives tick for derivatives indicators.
    pub deriv: Option<&'a DerivativesTick>,
    /// Order-book snapshot for order-book indicators.
    pub orderbook: Option<&'a OrderBook>,
    /// Trades that printed within this bar, for trade-flow indicators.
    pub trades: Option<&'a [TradePrint]>,
    /// Market cross-section for this bar, for breadth indicators.
    pub cross_section: Option<&'a CrossSection>,
}

/// One bar's inputs, converted from the wire types once and handed to each phase.
///
/// The conversions are not free and more than one phase needs them, so they
/// happen here rather than per phase. `index` is the bar's absolute position in
/// the run, which is not the same as its position in the retained window.
#[derive(Debug)]
struct Bar<'a> {
    candle: &'a Candle,
    reference: Option<f64>,
    deriv: Option<CoreDerivativesTick>,
    orderbook: Option<CoreOrderBook>,
    cross_section: Option<CoreCrossSection>,
    trades: Vec<CoreTrade>,
    index: usize,
}

/// One declared indicator, with the keys its values are recorded under.
///
/// The keys are built once and shared into every `BarRow`. Recording a value used
/// to clone the indicator's name into a fresh `String`, and a multi-output field
/// used to `format!` one per bar -- allocations proportional to the length of the
/// run, which for a live loop has no length.
struct Indicator {
    name: Arc<str>,
    /// `name.field` keys, filled the first time a field is reported: the field
    /// names come from the indicator, so they are not known before it runs.
    field_keys: Vec<(&'static str, Arc<str>)>,
    eval: Box<dyn EvalIndicator>,
}

/// How many bars the evaluator must be able to reach, including the current one.
///
/// Every backward-looking form declares its own depth in `rules`, so this is the
/// maximum over the spec's rules plus whatever the sizing model reads. Sized this
/// way the window answers exactly the questions an unbounded history would, and
/// no more.
fn history_depth(spec: &StrategySpec) -> usize {
    let mut back = condition_lookback(&spec.entry).max(condition_lookback(&spec.exit));
    if let Some(cond) = &spec.short_entry {
        back = back.max(condition_lookback(cond));
    }
    if let Some(cond) = &spec.short_exit {
        back = back.max(condition_lookback(cond));
    }
    // Vol targeting reads the last `lookback` closes off the tail.
    if let Sizing::VolTarget { lookback, .. } = spec.sizing {
        back = back.max(lookback as usize);
    }
    back + 1
}

/// Reject a spec that prices a run against a feed the run does not carry.
///
/// Both cases below produce a number rather than a failure when the feed is
/// missing: spread slippage costs zero, and funding is never charged. The report
/// then looks like a successful backtest of a cheaper strategy than the one that
/// was described, which is the expensive kind of wrong -- nothing about it says
/// the model was silently reduced.
///
/// The batch entry points know their feeds up front, so they check here.
/// [`StreamingBacktest`] cannot: its caller supplies feeds bar by bar, and
/// whether a book arrives is not knowable when the handle is built.
pub(crate) fn require_feeds(
    spec: &StrategySpec,
    has_orderbook: bool,
    has_deriv: bool,
) -> Result<()> {
    if matches!(spec.costs.slippage, Slippage::Spread) && !has_orderbook {
        return Err(BacktestError::InvalidSpec(
            "costs.slippage spread needs an order-book feed; without one every fill              would be priced at zero slippage"
                .into(),
        ));
    }
    if spec.costs.funding && !has_deriv {
        return Err(BacktestError::InvalidSpec(
            "costs.funding needs a derivatives feed; without one no funding would be              charged at all"
                .into(),
        ));
    }
    Ok(())
}

/// Run a backtest of `spec` over `candles` with the default capital.
///
/// ```
/// use wickra_backtest_core::{run, Candle, StrategySpec};
///
/// let spec = StrategySpec::parse(
///     r#"{"symbol":"x","timeframe":"1h","indicators":{},
///         "entry":{"gt":[{"price":"close"},100]},
///         "exit":{"lt":[{"price":"close"},100]},
///         "sizing":{"type":"fixed_qty","qty":1}}"#,
/// )?;
/// let bar = |time, open: f64, close: f64| Candle {
///     time,
///     open,
///     high: open.max(close),
///     low: open.min(close),
///     close,
///     volume: 0.0,
/// };
/// let report = run(&spec, &[bar(0, 100.0, 101.0), bar(1, 102.0, 103.0), bar(2, 104.0, 97.0)])?;
///
/// // The entry signal fires on bar 0 and fills at bar 1's open, look-ahead-free.
/// assert_eq!(report.trades.len(), report.metrics.num_trades as usize);
/// assert_eq!(report.symbol, "x");
/// # Ok::<(), wickra_backtest_core::BacktestError>(())
/// ```
///
/// # Errors
///
/// Returns an error if the spec is invalid, the candle series is empty, or the
/// spec prices against a feed this entry point cannot supply.
pub fn run(spec: &StrategySpec, candles: &[Candle]) -> Result<BacktestReport> {
    run_with_capital(spec, candles, DEFAULT_CAPITAL)
}

/// Run a backtest with explicit starting `capital`.
pub fn run_with_capital(
    spec: &StrategySpec,
    candles: &[Candle],
    capital: f64,
) -> Result<BacktestReport> {
    spec.validate()?;
    require_feeds(spec, false, false)?;
    if candles.is_empty() {
        return Err(BacktestError::InvalidData("no candles".into()));
    }
    let mut bt = StreamingBacktest::new(spec, capital)?;
    for candle in candles {
        bt.step(candle)?;
    }
    Ok(bt.finish())
}

/// Run a backtest over a candle stream, invoking `on_bar` with the streaming
/// state after each bar — the streaming entry point for a live tail or for
/// emitting the equity curve incrementally.
///
/// This is exactly the same step loop as [`run_with_capital`], so the returned
/// report is byte-identical; `on_bar` simply observes the state after each
/// [`StreamingBacktest::step`] (e.g. to read [`StreamingBacktest::latest_equity`]).
/// Pointing the same loop at a live feed turns the engine into the live bot.
pub fn run_stream<F>(
    spec: &StrategySpec,
    candles: &[Candle],
    capital: f64,
    mut on_bar: F,
) -> Result<BacktestReport>
where
    F: FnMut(usize, &StreamingBacktest),
{
    spec.validate()?;
    require_feeds(spec, false, false)?;
    if candles.is_empty() {
        return Err(BacktestError::InvalidData("no candles".into()));
    }
    let mut bt = StreamingBacktest::new(spec, capital)?;
    for (i, candle) in candles.iter().enumerate() {
        bt.step(candle)?;
        on_bar(i, &bt);
    }
    Ok(bt.finish())
}

/// Run a backtest with a reference price series for pairwise indicators. The
/// reference candle at each index supplies the second input (its close) to
/// pairwise indicators such as correlation, beta or spread. `reference` must be
/// the same length as `candles`.
pub fn run_with_ref(
    spec: &StrategySpec,
    candles: &[Candle],
    reference: &[Candle],
    capital: f64,
) -> Result<BacktestReport> {
    spec.validate()?;
    require_feeds(spec, false, false)?;
    if candles.is_empty() {
        return Err(BacktestError::InvalidData("no candles".into()));
    }
    if reference.len() != candles.len() {
        return Err(BacktestError::InvalidData(
            "reference series must have the same length as the candles".into(),
        ));
    }
    let mut bt = StreamingBacktest::new(spec, capital)?;
    for (candle, ref_candle) in candles.iter().zip(reference) {
        bt.step_with_ref(candle, Some(ref_candle.close))?;
    }
    Ok(bt.finish())
}

/// Run a backtest with a per-bar derivatives feed for derivatives indicators
/// (funding, open interest, long/short ratio, …). `derivs` must be the same
/// length as `candles`.
pub fn run_with_deriv(
    spec: &StrategySpec,
    candles: &[Candle],
    derivs: &[DerivativesTick],
    capital: f64,
) -> Result<BacktestReport> {
    spec.validate()?;
    require_feeds(spec, false, true)?;
    if candles.is_empty() {
        return Err(BacktestError::InvalidData("no candles".into()));
    }
    if derivs.len() != candles.len() {
        return Err(BacktestError::InvalidData(
            "derivatives feed must have the same length as the candles".into(),
        ));
    }
    let mut bt = StreamingBacktest::new(spec, capital)?;
    for (candle, d) in candles.iter().zip(derivs) {
        bt.step_with_feeds(
            candle,
            &Feeds {
                deriv: Some(d),
                ..Default::default()
            },
        )?;
    }
    Ok(bt.finish())
}

/// Run a backtest with a per-bar order-book feed for order-book indicators
/// (imbalance, microprice, quoted spread, …). `books` must be the same length
/// as `candles`.
pub fn run_with_orderbook(
    spec: &StrategySpec,
    candles: &[Candle],
    books: &[OrderBook],
    capital: f64,
) -> Result<BacktestReport> {
    spec.validate()?;
    require_feeds(spec, true, false)?;
    if candles.is_empty() {
        return Err(BacktestError::InvalidData("no candles".into()));
    }
    if books.len() != candles.len() {
        return Err(BacktestError::InvalidData(
            "order-book feed must have the same length as the candles".into(),
        ));
    }
    let mut bt = StreamingBacktest::new(spec, capital)?;
    for (candle, ob) in candles.iter().zip(books) {
        bt.step_with_feeds(
            candle,
            &Feeds {
                orderbook: Some(ob),
                ..Default::default()
            },
        )?;
    }
    Ok(bt.finish())
}

/// Run a backtest with a per-bar trade feed for trade-flow indicators (CVD,
/// trade imbalance, VPIN, signed volume, …). `trades[i]` is the list of trades
/// that printed within bar `i`; the outer length must match `candles`.
pub fn run_with_trades(
    spec: &StrategySpec,
    candles: &[Candle],
    trades: &[Vec<TradePrint>],
    capital: f64,
) -> Result<BacktestReport> {
    spec.validate()?;
    require_feeds(spec, false, false)?;
    if candles.is_empty() {
        return Err(BacktestError::InvalidData("no candles".into()));
    }
    if trades.len() != candles.len() {
        return Err(BacktestError::InvalidData(
            "trade feed must have one trade list per candle".into(),
        ));
    }
    let mut bt = StreamingBacktest::new(spec, capital)?;
    for (candle, bar_trades) in candles.iter().zip(trades) {
        bt.step_with_feeds(
            candle,
            &Feeds {
                trades: Some(bar_trades.as_slice()),
                ..Default::default()
            },
        )?;
    }
    Ok(bt.finish())
}

/// Run a backtest with a per-bar market cross-section for breadth indicators
/// (advance/decline, `McClellan`, TRIN, …). `sections` must be the same length as
/// `candles`.
pub fn run_with_cross_section(
    spec: &StrategySpec,
    candles: &[Candle],
    sections: &[CrossSection],
    capital: f64,
) -> Result<BacktestReport> {
    spec.validate()?;
    require_feeds(spec, false, false)?;
    if candles.is_empty() {
        return Err(BacktestError::InvalidData("no candles".into()));
    }
    if sections.len() != candles.len() {
        return Err(BacktestError::InvalidData(
            "cross-section feed must have one panel per candle".into(),
        ));
    }
    let mut bt = StreamingBacktest::new(spec, capital)?;
    for (candle, cs) in candles.iter().zip(sections) {
        bt.step_with_feeds(
            candle,
            &Feeds {
                cross_section: Some(cs),
                ..Default::default()
            },
        )?;
    }
    Ok(bt.finish())
}

/// A streaming backtest: feed bars one at a time with [`StreamingBacktest::step`],
/// then [`StreamingBacktest::finish`]. The historical runner is exactly this fed
/// from a slice, so **backtest and live share one code path** — point `step` at
/// a live feed and the same engine becomes the live bot.
///
/// # Memory over a long run
///
/// Bar history is bounded: only as many rows are retained as the spec's rules can
/// reach back, so feeding it forever does not grow it.
///
/// The equity curve and closed trades are not bounded, and deliberately so —
/// [`StreamingBacktest::finish`] computes every metric over the whole series, so
/// discarding points would quietly narrow the report rather than shrink it. An
/// equity point is 16 bytes, so a year of 1-minute bars costs roughly 8 MB. A live
/// consumer that reads [`StreamingBacktest::latest_equity`] each bar and persists
/// it elsewhere never needs the accumulated copy; `finish` is what releases it,
/// and starting a fresh run costs the indicators their warmup again.
pub struct StreamingBacktest<'a> {
    spec: Cow<'a, StrategySpec>,
    capital: f64,
    maker: f64,
    taker: f64,
    warmup: usize,
    indicators: Vec<Indicator>,
    pf: Portfolio,
    // The most recent `history_depth` bars, not the whole run: the evaluator only
    // ever indexes backwards by a bounded amount, and retaining everything made
    // memory grow with the length of the feed. A live loop is a run that never
    // ends, so "the whole history" is not a size at all.
    history: Vec<BarRow>,
    history_depth: usize,
    // Bars fed so far. `history.len()` used to serve as this; once the window is
    // bounded the two part company, and entry bookkeeping needs the absolute one.
    bars_seen: usize,
    equity: Vec<EquityPoint>,
    pending: Option<Pending>,
    entry_bar: Option<usize>,
    // Most favourable price reached since entry (peak for a long, trough for a
    // short) — the reference for the trailing stop.
    extreme: f64,
    // (time, close) of the most recent bar, for the final mark-out.
    last: Option<(i64, f64)>,
}

/// Hand-written because the indicator map holds `Box<dyn EvalIndicator>`, which no
/// derive can reach. The evaluators are shown by name: their internal state is the
/// indicator's business, and printing it would make this unreadable at any real
/// bar count.
impl fmt::Debug for StreamingBacktest<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StreamingBacktest")
            .field("capital", &self.capital)
            .field("warmup", &self.warmup)
            .field(
                "indicators",
                &self.indicators.iter().map(|i| &*i.name).collect::<Vec<_>>(),
            )
            .field("bars", &self.bars_seen)
            .field("equity_points", &self.equity.len())
            .field("trades", &self.pf.trades.len())
            .field("pending", &self.pending)
            .field("entry_bar", &self.entry_bar)
            .finish_non_exhaustive()
    }
}

impl<'a> StreamingBacktest<'a> {
    /// Build a streaming backtest from a validated spec and starting capital.
    ///
    /// ```
    /// use wickra_backtest_core::{run_with_capital, Candle, StreamingBacktest, StrategySpec};
    ///
    /// let spec = StrategySpec::parse(
    ///     r#"{"symbol":"x","timeframe":"1h","indicators":{},
    ///         "entry":{"gt":[{"price":"close"},100]},
    ///         "exit":{"lt":[{"price":"close"},100]},
    ///         "sizing":{"type":"fixed_qty","qty":1}}"#,
    /// )?;
    /// let bar = |time, open: f64, close: f64| Candle {
    ///     time,
    ///     open,
    ///     high: open.max(close),
    ///     low: open.min(close),
    ///     close,
    ///     volume: 0.0,
    /// };
    /// let candles = [bar(0, 100.0, 101.0), bar(1, 102.0, 103.0), bar(2, 104.0, 97.0)];
    ///
    /// let mut live = StreamingBacktest::new(&spec, 1_000.0)?;
    /// for candle in &candles {
    ///     live.step(candle)?;
    ///     // Everything a live loop wants is readable between bars.
    ///     let _ = (live.num_trades(), live.latest_equity());
    /// }
    /// let streamed = live.finish();
    ///
    /// // Feeding the same bars from a slice is the historical runner, and with
    /// // the same capital it produces the same report -- the whole claim of this
    /// // crate. (`run` would use the default capital and disagree, which is a
    /// // difference in inputs, not in engines.)
    /// let batch = run_with_capital(&spec, &candles, 1_000.0)?;
    /// assert_eq!(streamed.equity, batch.equity);
    /// assert_eq!(streamed.metrics.pnl, batch.metrics.pnl);
    /// # Ok::<(), wickra_backtest_core::BacktestError>(())
    /// ```
    pub fn new(spec: &'a StrategySpec, capital: f64) -> Result<Self> {
        Self::from_spec(Cow::Borrowed(spec), capital)
    }

    /// Build from an owned-or-borrowed spec — the shared constructor behind
    /// [`StreamingBacktest::new`] and [`StreamingBacktest::new_owned`].
    fn from_spec(spec: Cow<'a, StrategySpec>, capital: f64) -> Result<Self> {
        spec.validate()?;
        // `spec.indicators` is a sorted map, so the order here is deterministic.
        let mut indicators: Vec<Indicator> = Vec::with_capacity(spec.indicators.len());
        let mut max_warmup = 0usize;
        for (name, ind) in &spec.indicators {
            let built = registry::build(&ind.kind, &ind.params)?;
            max_warmup = max_warmup.max(built.warmup());
            indicators.push(Indicator {
                name: Arc::from(name.as_str()),
                field_keys: Vec::new(),
                eval: built,
            });
        }
        let warmup = spec.warmup.map_or(max_warmup, |w| w as usize);
        let history_depth = history_depth(&spec);
        let maker = spec.costs.maker_bps / 10_000.0;
        let taker = spec.costs.taker_bps / 10_000.0;
        Ok(Self {
            spec,
            capital,
            maker,
            taker,
            warmup,
            indicators,
            pf: Portfolio::new(capital),
            history: Vec::with_capacity(history_depth),
            history_depth,
            bars_seen: 0,
            equity: Vec::new(),
            pending: None,
            entry_bar: None,
            extreme: 0.0,
            last: None,
        })
    }

    /// Process one bar: fill the working order, update indicators, check intrabar
    /// stops, mark equity and decide the next action. Look-ahead-free.
    pub fn step(&mut self, candle: &Candle) -> Result<()> {
        self.step_with_feeds(candle, &Feeds::default())
    }

    /// The equity points produced so far, oldest first. Readable after each
    /// `step` for a live tail of the equity curve.
    pub fn equity(&self) -> &[EquityPoint] {
        &self.equity
    }

    /// The most recent equity point, or `None` before the first bar is marked.
    /// This is the value to emit per bar in a streaming / live run.
    pub fn latest_equity(&self) -> Option<EquityPoint> {
        self.equity.last().copied()
    }

    /// The number of completed trades so far.
    pub fn num_trades(&self) -> usize {
        self.pf.trades.len()
    }

    /// Like [`StreamingBacktest::step`], but also supplies the reference series'
    /// close for this bar, which pairwise indicators consume as their second
    /// input. Single-instrument indicators ignore it.
    pub fn step_with_ref(&mut self, candle: &Candle, reference: Option<f64>) -> Result<()> {
        self.step_with_feeds(
            candle,
            &Feeds {
                reference,
                ..Default::default()
            },
        )
    }

    /// Process one bar with its optional non-OHLCV [`Feeds`]. Pairwise indicators
    /// consume the reference; derivatives / order-book indicators consume the
    /// tick / snapshot; other indicators ignore them.
    /// Advance the simulation by one bar.
    ///
    /// # Errors
    ///
    /// Returns an error if the bar cannot be priced the way the spec asks.
    pub fn step_with_feeds(&mut self, candle: &Candle, feeds: &Feeds) -> Result<()> {
        // Checked per bar, because that is the only place a streaming caller can
        // be checked: the batch entry points know the whole run's feeds up front
        // and reject a mismatched spec once, but here they arrive one bar at a
        // time. The standard is the same either way -- the batch path requires a
        // book for every candle, not merely for some -- so a bar that cannot be
        // priced the way the spec asks is rejected rather than priced as if it
        // could be.
        require_feeds(&self.spec, feeds.orderbook.is_some(), feeds.deriv.is_some())?;
        let bar = Bar {
            candle,
            reference: feeds.reference,
            deriv: feeds.deriv.and_then(|d| d.to_core().ok()),
            orderbook: feeds.orderbook.and_then(|ob| ob.to_core().ok()),
            cross_section: feeds.cross_section.and_then(|cs| cs.to_core().ok()),
            trades: feeds
                .trades
                .unwrap_or(&[])
                .iter()
                .filter_map(|tp| tp.to_core().ok())
                .collect(),
            index: self.bars_seen,
        };
        self.last = Some((candle.time, candle.close));

        // The order below is the correctness argument, not a matter of taste. A
        // fill is priced against this bar before the bar is recorded, so a rule
        // cannot see the close it is about to be filled at; indicators update
        // before intrabar stops read them; equity is marked after every cost has
        // been charged; and only then does the next signal get to look at the
        // completed bar. Reordering any two of these is a change in what the
        // engine means, which is why they are named here rather than left as
        // comment headings inside one long body.
        self.fill_working_order(&bar)?;
        let idx = self.record_bar(&bar);
        self.apply_intrabar_exits(&bar);
        self.charge_funding(&bar);
        self.mark_equity(&bar);
        self.decide_next_action(&bar, idx)
    }

    /// 1. Fill the working order against this bar, look-ahead-free.
    fn fill_working_order(&mut self, bar: &Bar) -> Result<()> {
        let candle = bar.candle;
        let orderbook = &bar.orderbook;
        let t = bar.index;
        // 1. Fill the working order against this bar (look-ahead-free). Execution
        //    latency counts down first; then a market order fills at the open and
        //    a resting limit/stop fills only when the bar reaches its level —
        //    otherwise the order keeps working into the next bar.
        if let Some(mut order) = self.pending.take() {
            if order.delay > 0 {
                order.delay -= 1;
                self.pending = Some(order); // still waiting on latency
            } else {
                let ctx = FillCtx {
                    spec: &self.spec,
                    candle,
                    history: &self.history,
                    maker: self.maker,
                    taker: self.taker,
                    orderbook: orderbook.as_ref(),
                    bar: t,
                };
                let keep_working = match &order.action {
                    Action::Enter { side, trigger } => {
                        let side = *side;
                        // A resting limit fill provides liquidity → maker fee.
                        let maker_fill = matches!(trigger, Some((_, LevelKind::Limit)));
                        let level = match trigger {
                            None => Some(candle.open),
                            Some((trig, kind)) => level_fill(side, *trig, *kind, candle),
                        };
                        match level {
                            Some(px) => {
                                execute_entry(
                                    side,
                                    px,
                                    maker_fill,
                                    &ctx,
                                    &mut self.pf,
                                    &mut self.entry_bar,
                                    &mut self.extreme,
                                )?;
                                false
                            }
                            None => true, // level not reached; the order keeps working
                        }
                    }
                    Action::Exit(reason) => {
                        execute_exit(reason, candle.open, &ctx, &mut self.pf, &mut self.entry_bar);
                        false
                    }
                };
                if keep_working {
                    self.pending = Some(order);
                }
            }
        }

        Ok(())
    }

    /// 2. Update every indicator and record the bar.
    ///
    /// Returns the bar's index in the retained window, which is not its index in
    /// the run: the window is bounded and the run is not.
    fn record_bar(&mut self, bar: &Bar) -> usize {
        let candle = bar.candle;
        let reference = bar.reference;
        let deriv = bar.deriv;
        let orderbook = &bar.orderbook;
        let cross_section = &bar.cross_section;
        let trades: &[CoreTrade] = &bar.trades;
        // 2. Update indicators and record the bar.
        let mut values = BTreeMap::new();
        for ind in &mut self.indicators {
            let input = BarInput {
                candle,
                reference,
                deriv,
                orderbook: orderbook.as_ref(),
                trades,
                cross_section: cross_section.as_ref(),
            };
            if let Some(v) = ind.eval.update(&input) {
                values.insert(Arc::clone(&ind.name), v);
                let fields = ind.eval.fields();
                for (field, fv) in fields {
                    // Built once per field, then shared: a linear scan over a
                    // handful of names costs less than formatting one per bar.
                    let key =
                        if let Some((_, key)) = ind.field_keys.iter().find(|(f, _)| *f == field) {
                            Arc::clone(key)
                        } else {
                            let key: Arc<str> = Arc::from(format!("{}.{field}", ind.name).as_str());
                            ind.field_keys.push((field, Arc::clone(&key)));
                            key
                        };
                    values.insert(key, fv);
                }
            }
        }
        let row = BarRow {
            candle: *candle,
            values,
        };
        if self.history.len() == self.history_depth {
            // Full: drop the oldest and keep the slice contiguous, since the
            // evaluator indexes into it directly.
            self.history.rotate_left(1);
            self.history[self.history_depth - 1] = row;
        } else {
            self.history.push(row);
        }
        self.bars_seen += 1;
        // Window-relative: the current bar is always the last retained one.
        self.history.len() - 1
    }

    /// 3. Intrabar stop-loss / take-profit / trailing-stop against this bar.
    fn apply_intrabar_exits(&mut self, bar: &Bar) {
        let candle = bar.candle;
        // 3. Intrabar stop-loss / take-profit / trailing-stop against this bar's OHLC.
        if self.pf.in_position() {
            // Extend the favourable extreme with this bar before checking the trail.
            self.extreme = if self.pf.is_long() {
                self.extreme.max(candle.high)
            } else {
                self.extreme.min(candle.low)
            };
            if let Some((price, reason)) = intrabar_exit(
                candle,
                &self.spec.risk,
                self.pf.entry_price,
                self.extreme,
                self.pf.is_long(),
            ) {
                let fee = self.pf.qty.abs() * price * self.taker;
                self.pf.exit(price, candle.time, fee, reason);
                self.entry_bar = None;
            } else if self.spec.risk.liquidation {
                // Bankruptcy price: account equity (cash + qty * price) reaches 0.
                let p_liq = -self.pf.cash / self.pf.qty;
                let breached = if self.pf.is_long() {
                    candle.low <= p_liq
                } else {
                    candle.high >= p_liq
                };
                if p_liq > 0.0 && breached {
                    let fee = self.pf.qty.abs() * p_liq * self.taker;
                    self.pf.exit(p_liq, candle.time, fee, "liquidation");
                    self.entry_bar = None;
                }
            }
        }
    }

    /// 3b. Charge perpetual funding to an open position from the feed.
    fn charge_funding(&mut self, bar: &Bar) {
        let deriv = bar.deriv;
        // 3b. Charge perpetual funding to the open position from the feed.
        if self.spec.costs.funding && self.pf.in_position() {
            if let Some(d) = deriv {
                // Longs (qty > 0) pay when the rate is positive; shorts receive.
                let payment = self.pf.qty * d.mark_price * d.funding_rate;
                self.pf.apply_funding(payment);
            }
        }
    }

    /// 4. Mark equity at the close.
    fn mark_equity(&mut self, bar: &Bar) {
        let candle = bar.candle;
        // 4. Mark equity at the close.
        self.equity.push(EquityPoint {
            time: candle.time,
            equity: self.pf.equity(candle.close),
        });
    }

    /// 5. Decide the next signal action.
    fn decide_next_action(&mut self, bar: &Bar, idx: usize) -> Result<()> {
        let candle = bar.candle;
        let orderbook = &bar.orderbook;
        let t = bar.index;
        // 5. Decide the next signal action. Skip warmup.
        //
        // Counted in bars fed, not in retained rows: warmup is about indicators
        // having seen enough input, which is their own state, not this window's
        // depth. Reading it off the window would stall the gate forever once the
        // window filled.
        if t < self.warmup {
            return Ok(());
        }
        let bars_since_entry = self.entry_bar.map(|e| (t - e) as u32);
        let state = RuleState {
            in_position: self.pf.in_position(),
            bars_since_entry,
        };
        // Close-to-close mode fills on this very bar's close; otherwise the order
        // rests and fills on a later bar (the look-ahead-free default).
        let close_fill = matches!(self.spec.execution.fill_timing, FillTiming::Close);

        if self.pf.in_position() {
            let cond = if self.pf.is_long() {
                &self.spec.exit
            } else {
                self.spec.short_exit.as_ref().unwrap_or(&self.spec.exit)
            };
            if eval_condition(cond, &self.history, idx, state) {
                if close_fill {
                    let ctx = FillCtx {
                        spec: &self.spec,
                        candle,
                        history: &self.history,
                        maker: self.maker,
                        taker: self.taker,
                        orderbook: orderbook.as_ref(),
                        bar: t,
                    };
                    execute_exit(
                        "signal",
                        candle.close,
                        &ctx,
                        &mut self.pf,
                        &mut self.entry_bar,
                    );
                } else {
                    self.pending = Some(Pending {
                        action: Action::Exit("signal"),
                        delay: self.spec.execution.latency_bars,
                    });
                }
            }
        } else if self.pending.is_none() {
            // No order working: a new entry signal places one. Its trigger is the
            // signal bar's close shifted by the configured limit/stop offset.
            let entry_fires = eval_condition(&self.spec.entry, &self.history, idx, state);
            let short_fires = !entry_fires
                && self
                    .spec
                    .short_entry
                    .as_ref()
                    .is_some_and(|c| eval_condition(c, &self.history, idx, state));
            let side = if entry_fires {
                Some(Side::Long)
            } else if short_fires {
                Some(Side::Short)
            } else {
                None
            };
            if let Some(side) = side {
                if close_fill {
                    let ctx = FillCtx {
                        spec: &self.spec,
                        candle,
                        history: &self.history,
                        maker: self.maker,
                        taker: self.taker,
                        orderbook: orderbook.as_ref(),
                        bar: t,
                    };
                    execute_entry(
                        side,
                        candle.close,
                        false, // close-to-close fills are market (taker)
                        &ctx,
                        &mut self.pf,
                        &mut self.entry_bar,
                        &mut self.extreme,
                    )?;
                } else {
                    let trigger = entry_trigger(&self.spec.execution, candle.close);
                    self.pending = Some(Pending {
                        action: Action::Enter { side, trigger },
                        delay: self.spec.execution.latency_bars,
                    });
                }
            }
        }
        Ok(())
    }

    /// Close any open position at the last bar's close and produce the report.
    pub fn finish(mut self) -> BacktestReport {
        if self.pf.in_position() {
            if let Some((time, close)) = self.last {
                let fee = self.pf.qty.abs() * close * self.taker;
                self.pf.exit(close, time, fee, "end");
            }
        }
        let series: Vec<f64> = self.equity.iter().map(|e| e.equity).collect();
        let metrics = metrics::compute(self.capital, &series, &self.pf.trades);
        BacktestReport {
            schema_version: REPORT_SCHEMA_VERSION,
            symbol: self.spec.symbol.clone(),
            timeframe: self.spec.timeframe.clone(),
            metrics,
            trades: self.pf.trades,
            equity: self.equity,
            fees_paid: self.pf.fees_paid,
            initial_capital: self.capital,
        }
    }
}

impl StreamingBacktest<'static> {
    /// Build a streaming backtest that **owns** its spec, so the handle carries
    /// no borrow and can be held across `step`s indefinitely — for embedders
    /// that cannot thread a borrow through their own lifetime, such as a
    /// `#[wasm_bindgen]` handle driving the engine bar-by-bar in the browser.
    /// Otherwise identical to [`StreamingBacktest::new`].
    ///
    /// # Errors
    ///
    /// Returns an error if the spec fails validation.
    pub fn new_owned(spec: StrategySpec, capital: f64) -> Result<Self> {
        Self::from_spec(Cow::Owned(spec), capital)
    }
}

/// Base (unsigned) quantity for the sizing model.
///
/// `equity` is the account equity at entry (the position is opened from flat, so
/// equity equals cash). The resulting notional is capped by the leverage and
/// position limits: without `risk.max_leverage` the cap is 1x equity — no
/// leverage by default — so an order can never exceed what the account can fund.
fn size(
    sizing: Sizing,
    risk: &Risk,
    equity: f64,
    price: f64,
    realized_vol: Option<f64>,
) -> Result<Option<f64>> {
    if price <= 0.0 || equity <= 0.0 {
        return Ok(None);
    }
    let qty = match sizing {
        Sizing::FixedFraction { fraction } => (equity * fraction) / price,
        Sizing::FixedCash { cash: notional } => notional / price,
        Sizing::FixedQty { qty } => qty,
        Sizing::RiskPerTrade { risk_pct } => {
            // Size so a stop-loss hit loses `risk_pct` of equity: the per-unit
            // loss is `price * stop_loss_pct`, so qty = risk_cash / per-unit loss.
            let stop = risk.stop_loss_pct.ok_or_else(|| {
                BacktestError::InvalidSpec(
                    "risk_per_trade sizing requires risk.stop_loss_pct".into(),
                )
            })?;
            if stop <= 0.0 {
                return Ok(None);
            }
            (equity * risk_pct / 100.0) / (price * stop / 100.0)
        }
        Sizing::VolTarget { target_vol, .. } => {
            // Scale notional so the position's per-bar return vol ~= target_vol.
            // No realized vol yet (warming up) => no position this bar.
            let Some(rv) = realized_vol else {
                return Ok(None);
            };
            (equity * target_vol / rv) / price
        }
    };
    if qty <= 0.0 {
        return Ok(None);
    }
    // Cap the notional by the leverage and position limits.
    let max_leverage = risk.max_leverage.unwrap_or(1.0);
    let mut max_notional = equity * max_leverage;
    if let Some(max_pct) = risk.max_position_pct {
        max_notional = max_notional.min(equity * max_pct / 100.0);
    }
    let capped = (qty * price).min(max_notional) / price;
    Ok(Some(capped))
}

/// Intrabar stop-loss / trailing-stop / take-profit fill against the bar's OHLC.
///
/// `extreme` is the most favourable price reached since entry (peak for a long,
/// trough for a short), the trailing-stop reference. Conservative: when a bar's
/// range brackets several levels, the stop (then the trailing stop) is assumed
/// to fill before the target. Levels are side-aware (a short's stop is above
/// entry, its target below).
///
/// Fills are **gap-aware**: a stop fills at its level when price trades through
/// it intrabar, but if the bar *opens* beyond the level (a gap), the fill is the
/// open — the worse price for a stop, the better price for a take-profit — never
/// an unreachable level. A long stop fills at `min(level, open)`, a long target
/// at `max(level, open)`; a short is the mirror.
fn intrabar_exit(
    candle: &Candle,
    risk: &Risk,
    entry: f64,
    extreme: f64,
    is_long: bool,
) -> Option<(f64, &'static str)> {
    if entry <= 0.0 {
        return None;
    }
    if is_long {
        if let Some(p) = risk.stop_loss_pct {
            let level = entry * (1.0 - p / 100.0);
            if candle.low <= level {
                return Some((level.min(candle.open), "stop_loss"));
            }
        }
        if let Some(p) = risk.trailing_stop_pct {
            let level = extreme * (1.0 - p / 100.0);
            if candle.low <= level {
                return Some((level.min(candle.open), "trailing_stop"));
            }
        }
        if let Some(p) = risk.take_profit_pct {
            let level = entry * (1.0 + p / 100.0);
            if candle.high >= level {
                return Some((level.max(candle.open), "take_profit"));
            }
        }
    } else {
        if let Some(p) = risk.stop_loss_pct {
            let level = entry * (1.0 + p / 100.0);
            if candle.high >= level {
                return Some((level.max(candle.open), "stop_loss"));
            }
        }
        if let Some(p) = risk.trailing_stop_pct {
            let level = extreme * (1.0 + p / 100.0);
            if candle.high >= level {
                return Some((level.max(candle.open), "trailing_stop"));
            }
        }
        if let Some(p) = risk.take_profit_pct {
            let level = entry * (1.0 - p / 100.0);
            if candle.low <= level {
                return Some((level.min(candle.open), "take_profit"));
            }
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::data::Level;
    use crate::spec::StrategySpec;

    fn bar(time: i64, open: f64, high: f64, low: f64, close: f64) -> Candle {
        Candle {
            time,
            open,
            high,
            low,
            close,
            volume: 0.0,
        }
    }

    // --- stop-limit ---------------------------------------------------------
    //
    // A stop-limit is a stop that arms a limit. What distinguishes it from a
    // plain stop is the case where the market gaps past the limit: the stop
    // triggers, the limit is never reachable, and the order does not fill. A
    // plain stop would have filled at the open. These tests pin that difference,
    // because an implementation that ignored it would pass every other check.

    #[test]
    fn buy_stop_limit_fills_at_the_stop_when_the_limit_is_above_it() {
        // Stop 100, limit 101. The bar trades up through 100, so the stop arms
        // and the limit buy at 101 is immediately marketable: it fills at 100,
        // better than the limit, never worse.
        let c = bar(0, 99.0, 100.5, 98.5, 100.2);
        let fill = level_fill(Side::Long, 100.0, LevelKind::StopLimit { limit: 101.0 }, &c);
        assert_eq!(fill, Some(100.0));
    }

    #[test]
    fn buy_stop_limit_does_not_fill_when_the_bar_gaps_past_the_limit() {
        // Opens at 105, far above both stop and limit, and never trades back to
        // 101. The stop is touched; the limit is not. No fill.
        let c = bar(0, 105.0, 106.0, 102.0, 105.5);
        let fill = level_fill(Side::Long, 100.0, LevelKind::StopLimit { limit: 101.0 }, &c);
        assert_eq!(fill, None);
        // The same bar and the same stop, as a plain stop order, does fill --
        // at the open. That is exactly the protection a stop-limit buys.
        assert_eq!(
            level_fill(Side::Long, 100.0, LevelKind::Stop, &c),
            Some(105.0)
        );
    }

    #[test]
    fn buy_stop_limit_fills_at_the_limit_when_price_comes_back() {
        // Gaps to 105, so the stop arms at the open, then trades back through
        // 101. It fills at the limit, not at the open.
        let c = bar(0, 105.0, 106.0, 100.5, 104.0);
        let fill = level_fill(Side::Long, 100.0, LevelKind::StopLimit { limit: 101.0 }, &c);
        assert_eq!(fill, Some(101.0));
    }

    #[test]
    fn sell_stop_limit_mirrors_the_buy_side() {
        // Stop 100 below the market, limit 99. Trades down through 100 and
        // reaches 99: fills at 100, better than the limit.
        let touched = bar(0, 101.0, 101.5, 99.0, 99.5);
        assert_eq!(
            level_fill(
                Side::Short,
                100.0,
                LevelKind::StopLimit { limit: 99.0 },
                &touched
            ),
            Some(100.0)
        );
        // Gaps down to 95 and never trades back up to 99: no fill, where a plain
        // stop would have filled at the open.
        let gapped = bar(0, 95.0, 98.0, 94.0, 96.0);
        assert_eq!(
            level_fill(
                Side::Short,
                100.0,
                LevelKind::StopLimit { limit: 99.0 },
                &gapped
            ),
            None
        );
        assert_eq!(
            level_fill(Side::Short, 100.0, LevelKind::Stop, &gapped),
            Some(95.0)
        );
    }

    #[test]
    fn stop_limit_never_fills_worse_than_its_limit() {
        // Whatever the bar does, a buy never pays more than the limit and a sell
        // never receives less.
        for (o, h, l, c) in [
            (99.0, 100.5, 98.5, 100.2),
            (105.0, 106.0, 100.5, 104.0),
            (100.2, 103.0, 100.1, 102.0),
        ] {
            let candle = bar(0, o, h, l, c);
            if let Some(px) = level_fill(
                Side::Long,
                100.0,
                LevelKind::StopLimit { limit: 101.0 },
                &candle,
            ) {
                assert!(px <= 101.0, "buy filled above its limit: {px}");
            }
        }
    }

    // --- a run must carry the feeds its spec prices against ------------------
    //
    // Both of these used to produce a report. Spread slippage without a book cost
    // nothing, and funding without a derivatives feed was never charged, so the
    // run answered for a cheaper strategy than the one described and said nothing
    // about it.

    fn oscillating(n: i64) -> Vec<Candle> {
        (0..n)
            .map(|i| {
                let px = 100.0 + ((i as f64) * 0.4).sin() * 6.0;
                bar(i, px, px + 0.5, px - 0.5, px)
            })
            .collect()
    }

    fn spec_with(costs: &str) -> StrategySpec {
        StrategySpec::parse(&format!(
            r#"{{"symbol":"x","timeframe":"1h",
                "indicators":{{"a":{{"type":"Sma","params":[5]}}}},
                "entry":{{"cross_above":[{{"price":"close"}},"a"]}},
                "exit":{{"cross_below":[{{"price":"close"}},"a"]}},
                "sizing":{{"type":"fixed_qty","qty":1}},
                "costs":{costs}}}"#
        ))
        .unwrap()
    }

    #[test]
    fn the_report_says_what_it_is_a_report_of() {
        // Distinctive values on purpose: the golden corpus uses "x" and "1h"
        // throughout, so it would pass just as well against a hardcoded string.
        let spec = StrategySpec::parse(
            r#"{"symbol":"BTCUSDT","timeframe":"4h","indicators":{},
                "entry":{"gt":[{"price":"close"},100]},
                "exit":{"lt":[{"price":"close"},100]},
                "sizing":{"type":"fixed_qty","qty":1}}"#,
        )
        .unwrap();
        let candles = oscillating(20);

        let batch = run(&spec, &candles).unwrap();
        assert_eq!(batch.symbol, "BTCUSDT");
        assert_eq!(batch.timeframe, "4h");

        // The streaming path builds its report separately, so it is asserted
        // separately.
        let mut bt = StreamingBacktest::new(&spec, DEFAULT_CAPITAL).unwrap();
        for candle in &candles {
            bt.step(candle).unwrap();
        }
        let streamed = bt.finish();
        assert_eq!(streamed.symbol, "BTCUSDT");
        assert_eq!(streamed.timeframe, "4h");
    }

    #[test]
    fn a_streaming_bar_without_its_required_feed_is_rejected() {
        // The batch entry points check the whole run's feeds once, up front. A
        // streaming caller has no "up front", so the same standard has to be
        // applied per bar -- otherwise `step()` would price a spread-slippage
        // spec at zero slippage, reporting a cheaper strategy than the one asked
        // for, which is exactly what the batch check exists to prevent.
        let spec = spec_with(r#"{"slippage":{"type":"spread"}}"#);
        let candles = oscillating(10);

        let mut blind = StreamingBacktest::new(&spec, 10_000.0).unwrap();
        let err = blind.step(&candles[0]).unwrap_err();
        let BacktestError::InvalidSpec(msg) = err else {
            panic!("expected InvalidSpec, got {err:?}");
        };
        assert!(
            msg.contains("order-book"),
            "message should say what is missing: {msg}"
        );

        // The same spec, fed a book each bar, runs -- so the rejection is about
        // the feed, not about the spec.
        let mut fed = StreamingBacktest::new(&spec, 10_000.0).unwrap();
        for candle in &candles {
            let book = OrderBook {
                bids: vec![Level {
                    price: candle.close - 0.01,
                    size: 1.0,
                }],
                asks: vec![Level {
                    price: candle.close + 0.01,
                    size: 1.0,
                }],
            };
            let feeds = Feeds {
                orderbook: Some(&book),
                ..Feeds::default()
            };
            fed.step_with_feeds(candle, &feeds).unwrap();
        }
        assert_eq!(fed.equity().len(), candles.len());
    }

    #[test]
    fn spread_slippage_without_an_order_book_is_rejected() {
        let spec = spec_with(r#"{"slippage":{"type":"spread"}}"#);
        let candles = oscillating(60);
        let err = run(&spec, &candles).unwrap_err();
        let BacktestError::InvalidSpec(msg) = err else {
            panic!("expected InvalidSpec, got {err:?}");
        };
        assert!(
            msg.contains("order-book"),
            "message should say what is missing: {msg}"
        );

        // The same spec with a book runs, which is what makes the rejection a
        // statement about the feed rather than about the spec.
        let books: Vec<OrderBook> = candles
            .iter()
            .map(|c| OrderBook {
                bids: vec![Level {
                    price: c.close - 0.01,
                    size: 1.0,
                }],
                asks: vec![Level {
                    price: c.close + 0.01,
                    size: 1.0,
                }],
            })
            .collect();
        assert!(run_with_orderbook(&spec, &candles, &books, DEFAULT_CAPITAL).is_ok());
    }

    #[test]
    fn funding_without_a_derivatives_feed_is_rejected() {
        let spec = spec_with(r#"{"funding":true}"#);
        let candles = oscillating(60);
        let err = run(&spec, &candles).unwrap_err();
        let BacktestError::InvalidSpec(msg) = err else {
            panic!("expected InvalidSpec, got {err:?}");
        };
        assert!(
            msg.contains("derivatives"),
            "message should say what is missing: {msg}"
        );
    }

    #[test]
    fn a_spec_that_prices_nothing_special_needs_no_extra_feed() {
        // The guard must not reject the ordinary case: fixed-bps slippage and no
        // funding run over plain candles.
        let spec = spec_with(r#"{"slippage":{"type":"fixed_bps","bps":1.0}}"#);
        assert!(run(&spec, &oscillating(60)).is_ok());
    }

    /// A generated indicator — one that was never in the original hand-written
    /// registry — drives a full backtest, proving the expanded registry
    /// integrates end to end through the engine.
    #[test]
    fn generated_indicator_drives_backtest() {
        // `Alma` is one of the generated scalar (`Input = f64`) indicators.
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h",
                "indicators":{"a":{"type":"Alma","params":[9,0.85,6.0]}},
                "entry":{"cross_above":[{"price":"close"},"a"]},
                "exit":{"cross_below":[{"price":"close"},"a"]},
                "sizing":{"type":"fixed_qty","qty":1}}"#,
        )
        .unwrap();
        let candles: Vec<Candle> = (0..60)
            .map(|i| {
                let px = 100.0 + ((i as f64) * 0.4).sin() * 6.0;
                bar(i, px, px + 0.5, px - 0.5, px)
            })
            .collect();
        let r = run(&spec, &candles).unwrap();
        // It ran over every bar and produced a full equity curve.
        assert_eq!(r.equity.len(), candles.len());
        // The oscillating series crosses the moving average, so it trades.
        assert!(r.metrics.num_trades >= 1);
    }

    /// A price-threshold long strategy with no costs, hand-computed end to end.
    #[test]
    fn hand_computed_round_trip() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},100]},
                "exit":{"lt":[{"price":"close"},100]},
                "sizing":{"type":"fixed_qty","qty":1}}"#,
        )
        .unwrap();
        let candles = [
            bar(0, 100.0, 101.0, 100.0, 101.0),
            bar(1, 102.0, 103.0, 102.0, 103.0), // fill enter @ open 102
            bar(2, 104.0, 104.0, 99.0, 99.0),
            bar(3, 98.0, 98.0, 97.0, 97.0), // fill exit @ open 98
        ];
        let r = run_with_capital(&spec, &candles, 1000.0).unwrap();
        assert_eq!(r.trades.len(), 1);
        let t = &r.trades[0];
        assert!((t.entry_price - 102.0).abs() < 1e-9);
        assert!((t.exit_price - 98.0).abs() < 1e-9);
        assert!((t.pnl - (-4.0)).abs() < 1e-9);
        assert!((r.equity.last().unwrap().equity - 996.0).abs() < 1e-9);
    }

    /// Short entry profits when price falls; exit fills at next open.
    #[test]
    fn short_round_trip() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"lt":[{"price":"close"},0]},
                "exit":{"in_position":true},
                "short_entry":{"lt":[{"price":"close"},100]},
                "short_exit":{"gt":[{"price":"close"},100]},
                "sizing":{"type":"fixed_qty","qty":1}}"#,
        )
        .unwrap();
        let candles = [
            bar(0, 100.0, 100.0, 99.0, 99.0),   // close 99 < 100 -> short signal
            bar(1, 98.0, 98.0, 98.0, 98.0),     // fill short @ open 98
            bar(2, 101.0, 101.0, 101.0, 101.0), // close 101 > 100 -> cover signal
            bar(3, 102.0, 102.0, 102.0, 102.0), // fill cover @ open 102
        ];
        let r = run_with_capital(&spec, &candles, 1000.0).unwrap();
        assert_eq!(r.trades.len(), 1);
        let t = &r.trades[0];
        assert!((t.entry_price - 98.0).abs() < 1e-9);
        assert!((t.exit_price - 102.0).abs() < 1e-9);
        // short pnl = -1 * (102 - 98) = -4
        assert!((t.pnl - (-4.0)).abs() < 1e-9);
        assert_eq!(t.reason, "signal");
    }

    /// A long position whose stop is hit intrabar fills at the stop level.
    #[test]
    fn intrabar_stop_loss() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},
                "exit":{"lt":[{"price":"close"},0]},
                "sizing":{"type":"fixed_qty","qty":1},
                "risk":{"stop_loss_pct":5.0}}"#,
        )
        .unwrap();
        let candles = [
            bar(0, 100.0, 100.0, 100.0, 100.0), // enter signal
            bar(1, 100.0, 101.0, 100.0, 100.0), // fill enter @ 100; stop at 95
            bar(2, 99.0, 99.0, 90.0, 92.0),     // low 90 <= 95 -> stop fills @ 95
        ];
        let r = run_with_capital(&spec, &candles, 1000.0).unwrap();
        assert_eq!(r.trades.len(), 1);
        let t = &r.trades[0];
        assert!((t.exit_price - 95.0).abs() < 1e-9);
        assert_eq!(t.reason, "stop_loss");
        assert!((t.pnl - (-5.0)).abs() < 1e-9); // 1 * (95 - 100)
    }

    /// A long position whose target is hit intrabar fills at the target level.
    #[test]
    fn intrabar_take_profit() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},
                "exit":{"lt":[{"price":"close"},0]},
                "sizing":{"type":"fixed_qty","qty":1},
                "risk":{"take_profit_pct":10.0}}"#,
        )
        .unwrap();
        let candles = [
            bar(0, 100.0, 100.0, 100.0, 100.0), // enter signal
            bar(1, 100.0, 100.0, 100.0, 100.0), // fill enter @ 100; target 110
            bar(2, 105.0, 115.0, 105.0, 112.0), // high 115 >= 110 -> target fills @ 110
        ];
        let r = run_with_capital(&spec, &candles, 1000.0).unwrap();
        assert_eq!(r.trades.len(), 1);
        let t = &r.trades[0];
        assert!((t.exit_price - 110.0).abs() < 1e-9);
        assert_eq!(t.reason, "take_profit");
        assert!((t.pnl - 10.0).abs() < 1e-9);
    }

    /// When a single bar's range spans both the stop and the target, the stop
    /// is assumed hit first (the conservative O→H→L→C path): the exit is the
    /// stop, not the target.
    #[test]
    fn simultaneous_stop_and_target_prefers_stop() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},
                "exit":{"lt":[{"price":"close"},0]},
                "sizing":{"type":"fixed_qty","qty":1},
                "risk":{"stop_loss_pct":5.0,"take_profit_pct":10.0}}"#,
        )
        .unwrap();
        let candles = [
            bar(0, 100.0, 100.0, 100.0, 100.0), // enter signal
            bar(1, 100.0, 100.0, 100.0, 100.0), // fill enter @ 100; stop 95, target 110
            bar(2, 100.0, 115.0, 90.0, 100.0),  // range hits BOTH 90<=95 and 115>=110
        ];
        let r = run_with_capital(&spec, &candles, 1000.0).unwrap();
        assert_eq!(r.trades.len(), 1);
        let t = &r.trades[0];
        assert_eq!(t.reason, "stop_loss");
        assert!((t.exit_price - 95.0).abs() < 1e-9);
        assert!((t.pnl - (-5.0)).abs() < 1e-9);
    }

    /// A bar that gaps entirely below the stop still triggers it, and fills at
    /// the gapped-down open (the realistic, conservative price) — not the
    /// unreachable stop level, which the bar never traded at.
    #[test]
    fn gap_down_through_stop_fills_at_open() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},
                "exit":{"lt":[{"price":"close"},0]},
                "sizing":{"type":"fixed_qty","qty":1},
                "risk":{"stop_loss_pct":5.0}}"#,
        )
        .unwrap();
        let candles = [
            bar(0, 100.0, 100.0, 100.0, 100.0), // enter signal
            bar(1, 100.0, 100.0, 100.0, 100.0), // fill enter @ 100; stop at 95
            bar(2, 90.0, 92.0, 88.0, 89.0),     // gaps open 90, below the 95 stop
        ];
        let r = run_with_capital(&spec, &candles, 1000.0).unwrap();
        assert_eq!(r.trades.len(), 1);
        let t = &r.trades[0];
        assert_eq!(t.reason, "stop_loss");
        assert!((t.exit_price - 90.0).abs() < 1e-9); // the gapped open, not 95
        assert!((t.pnl - (-10.0)).abs() < 1e-9); // 1 * (90 - 100)
    }

    /// A short whose stop gaps up: fills at the gapped-up open (worse for the
    /// short), not the lower stop level.
    #[test]
    fn gap_up_through_short_stop_fills_at_open() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"lt":[{"price":"close"},0]},"exit":{"in_position":false},
                "short_entry":{"gt":[{"price":"close"},0]},
                "short_exit":{"lt":[{"price":"close"},0]},
                "sizing":{"type":"fixed_qty","qty":1},
                "risk":{"stop_loss_pct":5.0}}"#,
        )
        .unwrap();
        let candles = [
            bar(0, 100.0, 100.0, 100.0, 100.0), // short signal
            bar(1, 100.0, 100.0, 100.0, 100.0), // fill short @ 100; stop at 105
            bar(2, 110.0, 112.0, 108.0, 111.0), // gaps open 110, above the 105 stop
        ];
        let r = run_with_capital(&spec, &candles, 1000.0).unwrap();
        assert_eq!(r.trades.len(), 1);
        let t = &r.trades[0];
        assert_eq!(t.reason, "stop_loss");
        assert!((t.exit_price - 110.0).abs() < 1e-9); // the gapped open, not 105
    }

    /// A long trailing stop exits when price retraces past the trailed peak.
    #[test]
    fn trailing_stop() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},
                "exit":{"lt":[{"price":"close"},0]},
                "sizing":{"type":"fixed_qty","qty":1},
                "risk":{"trailing_stop_pct":10.0}}"#,
        )
        .unwrap();
        let candles = [
            bar(0, 100.0, 100.0, 100.0, 100.0), // enter signal
            bar(1, 100.0, 100.0, 100.0, 100.0), // fill enter @ 100
            bar(2, 100.0, 120.0, 119.0, 120.0), // peak 120 (trail 108, low 119 -> no exit)
            bar(3, 118.0, 118.0, 105.0, 106.0), // low 105 <= 108 -> trailing fills @ 108
        ];
        let r = run_with_capital(&spec, &candles, 1000.0).unwrap();
        assert_eq!(r.trades.len(), 1);
        let t = &r.trades[0];
        assert_eq!(t.reason, "trailing_stop");
        assert!((t.exit_price - 108.0).abs() < 1e-9);
        assert!((t.pnl - 8.0).abs() < 1e-9);
    }

    #[test]
    fn no_signals_no_trades() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},1000000]},
                "exit":{"in_position":true},
                "sizing":{"type":"fixed_qty","qty":1}}"#,
        )
        .unwrap();
        let candles = [
            bar(0, 10.0, 10.0, 10.0, 10.0),
            bar(1, 11.0, 11.0, 11.0, 11.0),
        ];
        let r = run(&spec, &candles).unwrap();
        assert!(r.trades.is_empty());
    }

    #[test]
    fn open_position_closed_at_end() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},
                "exit":{"lt":[{"price":"close"},0]},
                "sizing":{"type":"fixed_qty","qty":1}}"#,
        )
        .unwrap();
        let candles = [
            bar(0, 10.0, 10.0, 10.0, 10.0),
            bar(1, 11.0, 11.0, 11.0, 11.0),
        ];
        let r = run_with_capital(&spec, &candles, 1000.0).unwrap();
        assert_eq!(r.trades.len(), 1);
        assert_eq!(r.trades[0].reason, "end");
    }

    #[test]
    fn sma_crossover_runs() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h",
                "indicators":{"fast":{"type":"Sma","params":[2]},"slow":{"type":"Sma","params":[3]}},
                "entry":{"cross_above":["fast","slow"]},
                "exit":{"cross_below":["fast","slow"]},
                "sizing":{"type":"fixed_fraction","fraction":0.5}}"#,
        )
        .unwrap();
        let candles: Vec<Candle> = (0..20)
            .map(|i| {
                bar(
                    i,
                    100.0 + i as f64,
                    100.0 + i as f64,
                    100.0,
                    100.0 + i as f64,
                )
            })
            .collect();
        let r = run(&spec, &candles).unwrap();
        assert_eq!(r.equity.len(), 20);
        assert_eq!(r.schema_version, REPORT_SCHEMA_VERSION);
    }

    /// A multi-output indicator referenced by field (`bb.upper` / `bb.lower`)
    /// resolves end to end through the engine.
    #[test]
    fn multi_output_field_ref_runs() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h",
                "indicators":{"bb":{"type":"Bollinger","params":[5,2]}},
                "entry":{"gt":[{"price":"close"},"bb.upper"]},
                "exit":{"lt":[{"price":"close"},"bb.lower"]},
                "sizing":{"type":"fixed_fraction","fraction":0.5}}"#,
        )
        .unwrap();
        let candles: Vec<Candle> = (0..30)
            .map(|i| {
                let p = 100.0 + (i as f64 * 0.5).sin() * 5.0;
                bar(i, p, p + 1.0, p - 1.0, p)
            })
            .collect();
        let r = run(&spec, &candles).unwrap();
        assert_eq!(r.equity.len(), 30);
    }

    #[test]
    fn vol_target_sizes_inversely_to_vol() {
        // target 1% per bar, realized 2% => notional 0.5x equity => 50 units.
        let q = size(
            Sizing::VolTarget {
                target_vol: 0.01,
                lookback: 5,
            },
            &Risk::default(),
            10_000.0,
            100.0,
            Some(0.02),
        )
        .unwrap()
        .unwrap();
        assert!((q - 50.0).abs() < 1e-9);
    }

    #[test]
    fn vol_target_takes_no_position_without_history() {
        let none = size(
            Sizing::VolTarget {
                target_vol: 0.01,
                lookback: 5,
            },
            &Risk::default(),
            10_000.0,
            100.0,
            None,
        )
        .unwrap();
        assert!(none.is_none());
    }

    #[test]
    fn vol_target_trades_after_warmup() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},
                "exit":{"in_position":false},
                "sizing":{"type":"vol_target","target_vol":0.02,"lookback":3}}"#,
        )
        .unwrap();
        let closes = [100.0, 101.0, 102.0, 101.0, 103.0, 102.0];
        let candles: Vec<Candle> = closes
            .iter()
            .enumerate()
            .map(|(i, &c)| bar(i64::try_from(i).unwrap(), c, c + 0.5, c - 0.5, c))
            .collect();
        let r = run(&spec, &candles).unwrap();
        // Once `lookback` bars of history exist, a vol-targeted position is taken.
        assert!(!r.trades.is_empty());
        assert!(r.trades[0].qty > 0.0);
    }

    #[test]
    fn risk_per_trade_sizes_from_stop() {
        // equity 10_000, risk 1% = 100 cash; stop 2% of price 100 = 2 per unit
        // => 50 units (notional 5_000, under the 1x cap).
        let risk = Risk {
            stop_loss_pct: Some(2.0),
            ..Default::default()
        };
        let q = size(
            Sizing::RiskPerTrade { risk_pct: 1.0 },
            &risk,
            10_000.0,
            100.0,
            None,
        )
        .unwrap()
        .unwrap();
        assert!((q - 50.0).abs() < 1e-9);
    }

    #[test]
    fn risk_per_trade_requires_stop() {
        assert!(size(
            Sizing::RiskPerTrade { risk_pct: 1.0 },
            &Risk::default(),
            10_000.0,
            100.0,
            None
        )
        .is_err());
    }

    #[test]
    fn default_leverage_caps_at_equity() {
        // fixed_cash 50_000 but equity 10_000 and no max_leverage => capped to 1x.
        let q = size(
            Sizing::FixedCash { cash: 50_000.0 },
            &Risk::default(),
            10_000.0,
            100.0,
            None,
        )
        .unwrap()
        .unwrap();
        assert!((q - 100.0).abs() < 1e-9);
    }

    #[test]
    fn max_leverage_allows_more_than_equity() {
        let risk = Risk {
            max_leverage: Some(3.0),
            ..Default::default()
        };
        let q = size(
            Sizing::FixedCash { cash: 50_000.0 },
            &risk,
            10_000.0,
            100.0,
            None,
        )
        .unwrap()
        .unwrap();
        assert!((q - 300.0).abs() < 1e-9); // 3x equity / price
    }

    #[test]
    fn max_position_pct_caps_notional() {
        let risk = Risk {
            max_leverage: Some(5.0),
            max_position_pct: Some(20.0),
            ..Default::default()
        };
        // 5x would allow 50_000, but 20% of equity = 2_000 notional => 20 units.
        let q = size(
            Sizing::FixedCash { cash: 50_000.0 },
            &risk,
            10_000.0,
            100.0,
            None,
        )
        .unwrap()
        .unwrap();
        assert!((q - 20.0).abs() < 1e-9);
    }

    #[test]
    fn leverage_flows_through_run() {
        let candles = [
            bar(0, 100.0, 100.0, 100.0, 100.0),
            bar(1, 100.0, 100.0, 100.0, 100.0), // enter @ open 100
            bar(2, 100.0, 100.0, 100.0, 100.0),
        ];
        let no_lev = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},
                "exit":{"in_position":false},
                "sizing":{"type":"fixed_cash","cash":50000}}"#,
        )
        .unwrap();
        let r0 = run_with_capital(&no_lev, &candles, 10_000.0).unwrap();
        assert!((r0.trades[0].qty - 100.0).abs() < 1e-9); // capped to 1x equity

        let levered = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},
                "exit":{"in_position":false},
                "sizing":{"type":"fixed_cash","cash":50000},
                "risk":{"max_leverage":3}}"#,
        )
        .unwrap();
        let r1 = run_with_capital(&levered, &candles, 10_000.0).unwrap();
        assert!((r1.trades[0].qty - 300.0).abs() < 1e-9); // 3x equity
    }

    #[test]
    fn limit_entry_fills_on_dip() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},
                "exit":{"in_position":false},
                "sizing":{"type":"fixed_qty","qty":1},
                "execution":{"order_type":"limit","limit_offset_pct":-1.0}}"#,
        )
        .unwrap();
        let candles = [
            bar(0, 100.0, 100.0, 100.0, 100.0), // signal -> limit works @ 99
            bar(1, 100.0, 101.0, 100.0, 100.0), // low 100 > 99: no fill, keeps working
            bar(2, 100.0, 100.0, 98.0, 99.0),   // low 98 <= 99: fills @ 99
        ];
        let r = run_with_capital(&spec, &candles, 10_000.0).unwrap();
        assert_eq!(r.trades.len(), 1);
        assert!((r.trades[0].entry_price - 99.0).abs() < 1e-9);
    }

    #[test]
    fn limit_entry_never_fills_without_a_dip() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},
                "exit":{"in_position":false},
                "sizing":{"type":"fixed_qty","qty":1},
                "execution":{"order_type":"limit","limit_offset_pct":-1.0}}"#,
        )
        .unwrap();
        let candles = [
            bar(0, 100.0, 100.0, 100.0, 100.0),
            bar(1, 100.0, 101.0, 100.0, 100.0),
            bar(2, 100.0, 102.0, 100.0, 101.0), // low never reaches 99
        ];
        let r = run_with_capital(&spec, &candles, 10_000.0).unwrap();
        assert!(r.trades.is_empty());
    }

    #[test]
    fn stop_entry_fills_on_breakout() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},
                "exit":{"in_position":false},
                "sizing":{"type":"fixed_qty","qty":1},
                "execution":{"order_type":"stop","stop_offset_pct":1.0}}"#,
        )
        .unwrap();
        let candles = [
            bar(0, 100.0, 100.0, 100.0, 100.0), // signal -> stop works @ 101
            bar(1, 100.0, 100.5, 100.0, 100.0), // high 100.5 < 101: no fill
            bar(2, 100.0, 102.0, 100.0, 101.0), // high 102 >= 101: fills @ 101
        ];
        let r = run_with_capital(&spec, &candles, 10_000.0).unwrap();
        assert_eq!(r.trades.len(), 1);
        assert!((r.trades[0].entry_price - 101.0).abs() < 1e-9);
    }

    #[test]
    fn limit_order_requires_offset() {
        // `parse` validates, so an order_type without its offset is rejected up front.
        assert!(StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},"exit":{"in_position":true},
                "sizing":{"type":"fixed_qty","qty":1},
                "execution":{"order_type":"limit"}}"#,
        )
        .is_err());
    }

    #[test]
    fn stop_limit_is_unsupported() {
        assert!(StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},"exit":{"in_position":true},
                "sizing":{"type":"fixed_qty","qty":1},
                "execution":{"order_type":"stop_limit"}}"#,
        )
        .is_err());
    }

    #[test]
    fn latency_delays_the_fill() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},
                "exit":{"in_position":false},
                "sizing":{"type":"fixed_qty","qty":1},
                "execution":{"latency_bars":1}}"#,
        )
        .unwrap();
        let candles = [
            bar(0, 100.0, 100.0, 100.0, 100.0), // signal at close
            bar(1, 110.0, 110.0, 110.0, 110.0), // would fill here without latency
            bar(2, 120.0, 120.0, 120.0, 120.0), // fills here after 1 bar of latency
        ];
        let r = run_with_capital(&spec, &candles, 10_000.0).unwrap();
        assert_eq!(r.trades.len(), 1);
        assert!((r.trades[0].entry_price - 120.0).abs() < 1e-9);
    }

    #[test]
    fn partial_fills_cap_entry_to_participation() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},
                "exit":{"in_position":false},
                "sizing":{"type":"fixed_qty","qty":100},
                "execution":{"partial_fills":true,"max_participation":0.05}}"#,
        )
        .unwrap();
        // The fill bar's volume is 1000, so the cap is 0.05 * 1000 = 50 units,
        // below the desired 100.
        let vbar = |time, volume| Candle {
            time,
            open: 100.0,
            high: 100.0,
            low: 100.0,
            close: 100.0,
            volume,
        };
        let candles = [vbar(0, 0.0), vbar(1, 1000.0), vbar(2, 1000.0)];
        let r = run_with_capital(&spec, &candles, 1_000_000.0).unwrap();
        assert_eq!(r.trades.len(), 1);
        assert!((r.trades[0].qty - 50.0).abs() < 1e-9);
    }

    #[test]
    fn partial_fills_requires_participation() {
        assert!(StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},"exit":{"in_position":true},
                "sizing":{"type":"fixed_qty","qty":1},
                "execution":{"partial_fills":true}}"#,
        )
        .is_err());
    }

    #[test]
    fn fill_timing_close_fills_same_bar() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},100]},
                "exit":{"lt":[{"price":"close"},100]},
                "sizing":{"type":"fixed_qty","qty":1},
                "execution":{"fill_timing":"close"}}"#,
        )
        .unwrap();
        let candles = [
            bar(0, 90.0, 90.0, 90.0, 90.0),   // close 90: no entry
            bar(1, 95.0, 105.0, 95.0, 101.0), // close 101 > 100: entry @ close 101
            bar(2, 100.0, 100.0, 90.0, 99.0), // close 99 < 100: exit @ close 99
        ];
        let r = run_with_capital(&spec, &candles, 10_000.0).unwrap();
        assert_eq!(r.trades.len(), 1);
        assert!((r.trades[0].entry_price - 101.0).abs() < 1e-9); // same-bar close
        assert!((r.trades[0].exit_price - 99.0).abs() < 1e-9);
    }

    #[test]
    fn fill_timing_close_rejects_limit_and_latency() {
        // Close fills can't express the next-bar limit/stop or latency models.
        assert!(StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},"exit":{"in_position":true},
                "sizing":{"type":"fixed_qty","qty":1},
                "execution":{"fill_timing":"close","order_type":"limit","limit_offset_pct":-1.0}}"#,
        )
        .is_err());
        assert!(StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},"exit":{"in_position":true},
                "sizing":{"type":"fixed_qty","qty":1},
                "execution":{"fill_timing":"close","latency_bars":1}}"#,
        )
        .is_err());
    }

    #[test]
    fn history_depth_covers_every_backward_looking_form() {
        // A cross reaches one bar back; `prev` compounds; `rising`/`falling` take
        // their own count. The window has to be the maximum of all of them, plus
        // the current bar.
        let depth = |rules: &str| {
            let spec = StrategySpec::parse(&format!(
                r#"{{"symbol":"x","timeframe":"1h","indicators":{{}},{rules},
                    "sizing":{{"type":"fixed_qty","qty":1}}}}"#
            ))
            .unwrap();
            history_depth(&spec)
        };

        // Plain comparisons read only the current bar.
        assert_eq!(
            depth(r#""entry":{"gt":[{"price":"close"},1]},"exit":{"lt":[{"price":"close"},1]}"#),
            1
        );
        // A cross compares this bar with the previous one.
        assert_eq!(
            depth(
                r#""entry":{"cross_above":[{"price":"close"},{"price":"open"}]},
                   "exit":{"lt":[{"price":"close"},1]}"#
            ),
            2
        );
        // `rising` by n reaches n bars back.
        assert_eq!(
            depth(
                r#""entry":{"rising":[{"price":"close"},9]},"exit":{"lt":[{"price":"close"},1]}"#
            ),
            10
        );
        // Nested `prev` compounds, and the deepest rule wins.
        assert_eq!(
            depth(
                r#""entry":{"gt":[{"prev":[{"prev":[{"price":"close"},2]},3]},1]},
                   "exit":{"lt":[{"price":"close"},1]}"#
            ),
            6
        );
        // Vol targeting reads the last `lookback` closes off the tail.
        let vol = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},1]},
                "exit":{"lt":[{"price":"close"},1]},
                "sizing":{"type":"vol_target","target_vol":0.02,"lookback":20}}"#,
        )
        .unwrap();
        assert_eq!(history_depth(&vol), 21);
    }

    #[test]
    fn history_stays_bounded_over_a_long_run() {
        // The claim this guards: a run that never ends must not grow without end.
        // Before the window, a year of minute bars retained a year of rows.
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{"f":{"type":"Ema","params":[3]}},
                "entry":{"cross_above":[{"price":"close"},"f"]},
                "exit":{"cross_below":[{"price":"close"},"f"]},
                "sizing":{"type":"fixed_qty","qty":1}}"#,
        )
        .unwrap();
        let mut bt = StreamingBacktest::new(&spec, 10_000.0).unwrap();
        for i in 0..20_000i64 {
            let px = 100.0 + ((i as f64) * 0.05).sin() * 5.0;
            bt.step(&bar(i, px, px + 0.5, px - 0.5, px)).unwrap();
        }
        assert_eq!(bt.bars_seen, 20_000);
        assert_eq!(bt.history_depth, 2);
        assert_eq!(bt.history.len(), 2);
        // It still traded, so the bounded window did not blind the rules.
        assert!(bt.num_trades() > 0);
    }

    #[test]
    fn a_deep_lookback_still_sees_far_enough() {
        // `rising` by 40 must keep working after the window has filled and started
        // evicting: the retained depth is what the rule reaches, not less.
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"rising":[{"price":"close"},40]},
                "exit":{"falling":[{"price":"close"},40]},
                "sizing":{"type":"fixed_qty","qty":1}}"#,
        )
        .unwrap();
        assert_eq!(history_depth(&spec), 41);

        let candles: Vec<Candle> = (0..400i64)
            .map(|i| {
                let px = 100.0 + ((i as f64) * 0.03).sin() * 10.0;
                bar(i, px, px + 0.5, px - 0.5, px)
            })
            .collect();
        let batch = run_with_capital(&spec, &candles, 10_000.0).unwrap();
        assert!(batch.metrics.num_trades >= 1, "the fixture must trade");

        let mut bt = StreamingBacktest::new(&spec, 10_000.0).unwrap();
        for candle in &candles {
            bt.step(candle).unwrap();
        }
        assert_eq!(bt.history.len(), 41);
        let streamed = bt.finish();
        assert_eq!(streamed.metrics.num_trades, batch.metrics.num_trades);
        assert!((streamed.metrics.pnl - batch.metrics.pnl).abs() < 1e-9);
    }

    #[test]
    fn streaming_matches_batch() {
        // Feeding bars one at a time through the public streaming API produces
        // the same report as the batch runner — backtest and live are one path.
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h",
                "indicators":{"f":{"type":"Ema","params":[3]}},
                "entry":{"cross_above":[{"price":"close"},"f"]},
                "exit":{"cross_below":[{"price":"close"},"f"]},
                "sizing":{"type":"fixed_qty","qty":1}}"#,
        )
        .unwrap();
        let candles: Vec<Candle> = (0..30i64)
            .map(|i| {
                let px = 100.0 + ((i as f64) * 0.5).sin() * 5.0;
                bar(i, px, px + 0.5, px - 0.5, px)
            })
            .collect();

        let batch = run_with_capital(&spec, &candles, 10_000.0).unwrap();

        let mut bt = StreamingBacktest::new(&spec, 10_000.0).unwrap();
        for c in &candles {
            bt.step(c).unwrap();
        }
        let streamed = bt.finish();

        assert!(batch.metrics.num_trades >= 1);
        assert_eq!(batch.metrics.num_trades, streamed.metrics.num_trades);
        assert_eq!(batch.trades.len(), streamed.trades.len());
        assert_eq!(batch.equity.len(), streamed.equity.len());
        assert!(
            (batch.equity.last().unwrap().equity - streamed.equity.last().unwrap().equity).abs()
                < 1e-12
        );
    }

    #[test]
    fn run_stream_matches_batch_and_tails_equity() {
        // The streaming entry point yields a byte-identical report to the batch
        // runner, and the per-bar hook sees the equity curve grow one point at a
        // time — the live-tail path.
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h",
                "indicators":{"f":{"type":"Ema","params":[3]}},
                "entry":{"cross_above":[{"price":"close"},"f"]},
                "exit":{"cross_below":[{"price":"close"},"f"]},
                "sizing":{"type":"fixed_qty","qty":1}}"#,
        )
        .unwrap();
        let candles: Vec<Candle> = (0..30i64)
            .map(|i| {
                let px = 100.0 + ((i as f64) * 0.5).sin() * 5.0;
                bar(i, px, px + 0.5, px - 0.5, px)
            })
            .collect();

        let batch = run_with_capital(&spec, &candles, 10_000.0).unwrap();

        let mut tail: Vec<EquityPoint> = Vec::new();
        let streamed = run_stream(&spec, &candles, 10_000.0, |i, bt| {
            // The equity curve has exactly one point per processed bar.
            assert_eq!(bt.equity().len(), i + 1);
            tail.push(bt.latest_equity().expect("a bar was marked"));
        })
        .unwrap();

        assert_eq!(tail.len(), candles.len());
        assert_eq!(streamed.equity.len(), batch.equity.len());
        // The tailed points equal the report's equity series exactly.
        for (got, want) in tail.iter().zip(&streamed.equity) {
            assert_eq!(got.time, want.time);
            assert!((got.equity - want.equity).abs() < 1e-12);
        }
        assert_eq!(streamed.metrics.num_trades, batch.metrics.num_trades);
    }

    #[test]
    fn pairwise_indicator_uses_reference_series() {
        // A pairwise indicator (Pearson correlation) is fed the reference
        // series' close as its second input via run_with_ref.
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h",
                "indicators":{"c":{"type":"PearsonCorrelation","params":[3]}},
                "entry":{"gt":["c",0.5]},
                "exit":{"lt":["c",-2.0]},
                "sizing":{"type":"fixed_qty","qty":1}}"#,
        )
        .unwrap();
        let primary: Vec<Candle> = [100.0, 101.0, 102.0, 101.0, 103.0, 102.0, 104.0, 103.0]
            .iter()
            .zip(0i64..)
            .map(|(&c, i)| bar(i, c, c + 0.5, c - 0.5, c))
            .collect();
        // A perfectly correlated reference series → correlation ~1 > 0.5 → entry.
        let reference: Vec<Candle> = [50.0, 50.5, 51.0, 50.5, 51.5, 51.0, 52.0, 51.5]
            .iter()
            .zip(0i64..)
            .map(|(&c, i)| bar(i, c, c + 0.2, c - 0.2, c))
            .collect();

        let with_ref = run_with_ref(&spec, &primary, &reference, 10_000.0).unwrap();
        assert!(with_ref.metrics.num_trades >= 1);

        // Without a reference series the pairwise indicator yields nothing, so
        // the entry condition never fires.
        let without_ref = run_with_capital(&spec, &primary, 10_000.0).unwrap();
        assert_eq!(without_ref.metrics.num_trades, 0);
    }

    #[test]
    fn pairwise_multi_output_exposes_fields() {
        // A pairwise multi-output indicator exposes its named fields when fed a
        // reference value.
        let mut ind = registry::build("RelativeStrengthAB", &[3.0, 3.0]).unwrap();
        let mut names: Vec<&str> = Vec::new();
        let prices = [
            100.0, 102.0, 104.0, 103.0, 105.0, 106.0, 107.0, 108.0, 109.0, 110.0,
        ];
        for (i, &px) in prices.iter().enumerate() {
            let c = Candle {
                time: i64::try_from(i).unwrap(),
                open: px,
                high: px,
                low: px,
                close: px,
                volume: 0.0,
            };
            let input = BarInput {
                candle: &c,
                reference: Some(px * 0.9),
                deriv: None,
                orderbook: None,
                trades: &[],
                cross_section: None,
            };
            if ind.update(&input).is_some() {
                names = ind.fields().iter().map(|(n, _)| *n).collect();
            }
        }
        assert!(names.contains(&"ratio"), "fields: {names:?}");
    }

    #[test]
    fn run_with_ref_rejects_length_mismatch() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},"exit":{"in_position":true},
                "sizing":{"type":"fixed_qty","qty":1}}"#,
        )
        .unwrap();
        let a = [bar(0, 1.0, 1.0, 1.0, 1.0), bar(1, 1.0, 1.0, 1.0, 1.0)];
        let b = [bar(0, 1.0, 1.0, 1.0, 1.0)];
        assert!(run_with_ref(&spec, &a, &b, 10_000.0).is_err());
    }

    fn sample_tick(funding_rate: f64) -> DerivativesTick {
        DerivativesTick {
            funding_rate,
            mark_price: 100.0,
            index_price: 100.0,
            futures_price: 100.0,
            open_interest: 1000.0,
            long_size: 600.0,
            short_size: 400.0,
            taker_buy_volume: 50.0,
            taker_sell_volume: 40.0,
            long_liquidation: 0.0,
            short_liquidation: 0.0,
            timestamp: 0,
        }
    }

    #[test]
    fn derivatives_indicator_uses_feed() {
        // FundingRate passes the tick's funding rate through; the feed drives it.
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h",
                "indicators":{"f":{"type":"FundingRate","params":[]}},
                "entry":{"gt":["f",0.0]},
                "exit":{"lt":["f",-1.0]},
                "sizing":{"type":"fixed_qty","qty":1}}"#,
        )
        .unwrap();
        let candles: Vec<Candle> = (0i64..5)
            .map(|i| bar(i, 100.0, 100.0, 100.0, 100.0))
            .collect();
        let derivs = vec![sample_tick(0.01); 5];

        let with_feed = run_with_deriv(&spec, &candles, &derivs, 10_000.0).unwrap();
        assert!(with_feed.metrics.num_trades >= 1);

        // Without a derivatives feed the indicator yields nothing → no entry.
        let without_feed = run_with_capital(&spec, &candles, 10_000.0).unwrap();
        assert_eq!(without_feed.metrics.num_trades, 0);
    }

    #[test]
    fn order_book_indicator_uses_feed() {
        use crate::data::Level;
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h",
                "indicators":{"i":{"type":"OrderBookImbalanceTop1","params":[]}},
                "entry":{"gt":["i",0.0]},
                "exit":{"lt":["i",-2.0]},
                "sizing":{"type":"fixed_qty","qty":1}}"#,
        )
        .unwrap();
        let candles: Vec<Candle> = (0i64..5)
            .map(|t| bar(t, 100.0, 100.0, 100.0, 100.0))
            .collect();
        // A bid-heavy book → positive top-of-book imbalance → entry.
        let book = OrderBook {
            bids: vec![Level {
                price: 100.0,
                size: 9.0,
            }],
            asks: vec![Level {
                price: 101.0,
                size: 1.0,
            }],
        };
        let books = vec![book; 5];

        let with_feed = run_with_orderbook(&spec, &candles, &books, 10_000.0).unwrap();
        assert!(with_feed.metrics.num_trades >= 1);

        let without_feed = run_with_capital(&spec, &candles, 10_000.0).unwrap();
        assert_eq!(without_feed.metrics.num_trades, 0);
    }

    #[test]
    fn trade_indicator_replays_bar_trades() {
        use crate::data::{TradePrint, TradeSide};
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h",
                "indicators":{"cvd":{"type":"CumulativeVolumeDelta","params":[]}},
                "entry":{"gt":["cvd",0.0]},
                "exit":{"lt":["cvd",-1.0]},
                "sizing":{"type":"fixed_qty","qty":1}}"#,
        )
        .unwrap();
        let candles: Vec<Candle> = (0i64..5)
            .map(|t| bar(t, 100.0, 100.0, 100.0, 100.0))
            .collect();
        let buy = TradePrint {
            price: 100.0,
            size: 5.0,
            side: TradeSide::Buy,
            timestamp: 0,
        };
        // Two buy trades per bar → cumulative volume delta grows positive.
        let trades: Vec<Vec<TradePrint>> = (0..5).map(|_| vec![buy, buy]).collect();

        let with_feed = run_with_trades(&spec, &candles, &trades, 10_000.0).unwrap();
        assert!(with_feed.metrics.num_trades >= 1);

        let without_feed = run_with_capital(&spec, &candles, 10_000.0).unwrap();
        assert_eq!(without_feed.metrics.num_trades, 0);
    }

    #[test]
    fn funding_charges_an_open_long() {
        let with_funding = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},
                "exit":{"in_position":false},
                "sizing":{"type":"fixed_qty","qty":1},
                "costs":{"funding":true}}"#,
        )
        .unwrap();
        let candles = [
            bar(0, 100.0, 100.0, 100.0, 100.0),
            bar(1, 100.0, 100.0, 100.0, 100.0),
            bar(2, 100.0, 100.0, 100.0, 100.0),
        ];
        let derivs = vec![sample_tick(0.01); 3]; // funding 1% of mark 100 = 1.0/bar

        let funded = run_with_deriv(&with_funding, &candles, &derivs, 10_000.0).unwrap();
        assert!(funded.fees_paid > 0.0); // a long paid funding

        let no_funding = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},
                "exit":{"in_position":false},
                "sizing":{"type":"fixed_qty","qty":1}}"#,
        )
        .unwrap();
        let unfunded = run_with_deriv(&no_funding, &candles, &derivs, 10_000.0).unwrap();
        assert!(funded.equity.last().unwrap().equity < unfunded.equity.last().unwrap().equity);
    }

    #[test]
    fn leverage_liquidation_closes_at_bankruptcy() {
        // 5x long: capital 1000, notional 5000 → qty 50, cash -4000, bankruptcy
        // price -(-4000)/50 = 80.
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},
                "exit":{"in_position":false},
                "sizing":{"type":"fixed_cash","cash":5000},
                "risk":{"max_leverage":5,"liquidation":true}}"#,
        )
        .unwrap();
        let candles = [
            bar(0, 100.0, 100.0, 100.0, 100.0), // signal
            bar(1, 100.0, 100.0, 95.0, 98.0),   // enter @ open 100; low 95 > 80: safe
            bar(2, 90.0, 90.0, 70.0, 75.0),     // low 70 <= 80: liquidate @ 80
        ];
        let r = run_with_capital(&spec, &candles, 1000.0).unwrap();
        assert_eq!(r.trades.len(), 1);
        assert_eq!(r.trades[0].reason, "liquidation");
        assert!((r.trades[0].exit_price - 80.0).abs() < 1e-9);
        assert!(r.equity.last().unwrap().equity.abs() < 1e-6); // account wiped out
    }

    #[test]
    fn limit_entry_pays_maker_fee() {
        let candles = [
            bar(0, 100.0, 100.0, 100.0, 100.0),
            bar(1, 100.0, 100.0, 100.0, 100.0),
            bar(2, 100.0, 100.0, 100.0, 100.0),
        ];
        // A market entry pays the taker fee; a resting limit entry pays maker.
        let market = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},"exit":{"in_position":false},
                "sizing":{"type":"fixed_qty","qty":1},
                "costs":{"maker_bps":0,"taker_bps":200}}"#,
        )
        .unwrap();
        let limit = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},"exit":{"in_position":false},
                "sizing":{"type":"fixed_qty","qty":1},
                "costs":{"maker_bps":0,"taker_bps":200},
                "execution":{"order_type":"limit","limit_offset_pct":0.0}}"#,
        )
        .unwrap();
        let market_fees = run_with_capital(&market, &candles, 10_000.0)
            .unwrap()
            .fees_paid;
        let limit_fees = run_with_capital(&limit, &candles, 10_000.0)
            .unwrap()
            .fees_paid;
        assert!(limit_fees < market_fees); // maker (0) saved versus taker on entry
    }

    #[test]
    fn volume_impact_slippage_worsens_the_fill() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},"exit":{"in_position":false},
                "sizing":{"type":"fixed_qty","qty":10},
                "costs":{"slippage":{"type":"volume_impact","coef":0.5}}}"#,
        )
        .unwrap();
        let vbar = |t, vol| Candle {
            time: t,
            open: 100.0,
            high: 100.0,
            low: 100.0,
            close: 100.0,
            volume: vol,
        };
        let candles = [vbar(0, 1000.0), vbar(1, 1000.0), vbar(2, 1000.0)];
        let r = run_with_capital(&spec, &candles, 1_000_000.0).unwrap();
        // slip = coef * qty / volume = 0.5 * 10 / 1000 = 0.005 -> fill 100 * 1.005
        assert!((r.trades[0].entry_price - 100.5).abs() < 1e-9);
    }

    #[test]
    fn spread_slippage_uses_the_order_book() {
        use crate::data::Level;
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},"exit":{"in_position":false},
                "sizing":{"type":"fixed_qty","qty":1},
                "costs":{"slippage":{"type":"spread"}}}"#,
        )
        .unwrap();
        let candles = [
            bar(0, 100.0, 100.0, 100.0, 100.0),
            bar(1, 100.0, 100.0, 100.0, 100.0),
            bar(2, 100.0, 100.0, 100.0, 100.0),
        ];
        let book = OrderBook {
            bids: vec![Level {
                price: 99.0,
                size: 1.0,
            }],
            asks: vec![Level {
                price: 101.0,
                size: 1.0,
            }],
        };
        let books = vec![book; 3];
        let r = run_with_orderbook(&spec, &candles, &books, 10_000.0).unwrap();
        // half-spread / mid = 1 / 100 = 0.01 -> long entry fill 100 * 1.01 = 101
        assert!((r.trades[0].entry_price - 101.0).abs() < 1e-9);
    }

    #[test]
    fn trade_quote_indicator_uses_trades_and_mid() {
        use crate::data::{TradePrint, TradeSide};
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h",
                "indicators":{"es":{"type":"EffectiveSpread","params":[]}},
                "entry":{"gt":["es",0.0]},
                "exit":{"lt":["es",-1.0]},
                "sizing":{"type":"fixed_qty","qty":1}}"#,
        )
        .unwrap();
        let candles: Vec<Candle> = (0i64..5)
            .map(|t| bar(t, 100.0, 100.0, 100.0, 100.0))
            .collect();
        // Trades print away from the mid (close 100) -> positive effective spread.
        let trade = TradePrint {
            price: 102.0,
            size: 1.0,
            side: TradeSide::Buy,
            timestamp: 0,
        };
        let trades: Vec<Vec<TradePrint>> = (0..5).map(|_| vec![trade]).collect();

        let with_feed = run_with_trades(&spec, &candles, &trades, 10_000.0).unwrap();
        assert!(with_feed.metrics.num_trades >= 1);

        let without_feed = run_with_capital(&spec, &candles, 10_000.0).unwrap();
        assert_eq!(without_feed.metrics.num_trades, 0);
    }

    #[test]
    fn cross_section_breadth_indicator_uses_feed() {
        use crate::data::{CrossSection, CrossSectionMember};
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h",
                "indicators":{"ad":{"type":"AdvanceDecline","params":[]}},
                "entry":{"gt":["ad",0.0]},
                "exit":{"lt":["ad",-100.0]},
                "sizing":{"type":"fixed_qty","qty":1}}"#,
        )
        .unwrap();
        let candles: Vec<Candle> = (0i64..4)
            .map(|t| bar(t, 100.0, 100.0, 100.0, 100.0))
            .collect();
        let advancer = CrossSectionMember {
            change: 1.0,
            volume: 100.0,
            new_high: false,
            new_low: false,
        };
        let decliner = CrossSectionMember {
            change: -1.0,
            volume: 100.0,
            new_high: false,
            new_low: false,
        };
        // Three advancing vs one declining -> positive advance-decline.
        let section = CrossSection {
            members: vec![advancer, advancer, advancer, decliner],
            timestamp: 0,
        };
        let sections = vec![section; 4];

        let with_feed = run_with_cross_section(&spec, &candles, &sections, 10_000.0).unwrap();
        assert!(with_feed.metrics.num_trades >= 1);

        let without_feed = run_with_capital(&spec, &candles, 10_000.0).unwrap();
        assert_eq!(without_feed.metrics.num_trades, 0);
    }

    #[test]
    fn run_with_deriv_rejects_length_mismatch() {
        let spec = StrategySpec::parse(
            r#"{"symbol":"x","timeframe":"1h","indicators":{},
                "entry":{"gt":[{"price":"close"},0]},"exit":{"in_position":true},
                "sizing":{"type":"fixed_qty","qty":1}}"#,
        )
        .unwrap();
        let candles = [bar(0, 1.0, 1.0, 1.0, 1.0), bar(1, 1.0, 1.0, 1.0, 1.0)];
        let derivs = [sample_tick(0.0)];
        assert!(run_with_deriv(&spec, &candles, &derivs, 10_000.0).is_err());
    }

    #[test]
    fn new_owned_matches_the_borrowing_constructor() {
        let json = r#"{"symbol":"x","timeframe":"1h","indicators":{},
            "entry":{"gt":[{"price":"close"},0]},"exit":{"in_position":true},
            "sizing":{"type":"fixed_qty","qty":1}}"#;
        let spec = StrategySpec::parse(json).unwrap();
        let candles = [
            bar(0, 1.0, 1.0, 1.0, 1.0),
            bar(1, 1.0, 2.0, 1.0, 2.0),
            bar(2, 2.0, 3.0, 2.0, 3.0),
        ];

        // Borrowing constructor.
        let mut borrowed = StreamingBacktest::new(&spec, 10_000.0).unwrap();
        for candle in &candles {
            borrowed.step(candle).unwrap();
        }
        let borrowed_report = borrowed.finish();

        // Owned constructor: move the spec in; the handle carries no borrow.
        let mut owned = StreamingBacktest::new_owned(spec, 10_000.0).unwrap();
        for candle in &candles {
            owned.step(candle).unwrap();
        }
        let owned_report = owned.finish();

        // The two paths must produce byte-identical reports.
        assert_eq!(
            serde_json::to_string(&owned_report).unwrap(),
            serde_json::to_string(&borrowed_report).unwrap()
        );
    }
}