digdigdig3-station 0.3.30

Consumer-facing builder over digdigdig3 ExchangeHub. Persistence, cache, replay, cure, orderbook tracker, multiplex, reconnect.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
//! Derived-stream layer for `digdigdig3-station`.
//!
//! A *derived stream* is a Station-internal computation that subscribes to one
//! or more upstream WS-backed streams and emits events of its own type. It runs
//! as a standalone `tokio::spawn` task per `SeriesKey`, sharing the same
//! `DiskStore<T>` / `Series<T>` / `broadcast::channel<Event>` plumbing as
//! regular WS forwarders. Consumers see no difference.
//!
//! Concrete impls shipped in this module:
//!
//! - [`BasisDerived`] — joins `MarkPrice` + `IndexPrice`, emits
//!   `BasisPoint { value = mark − index }`. Rejects pairs skewed > 2 seconds.
//! - [`FundingSettlementDerived`] — monitors `FundingRate`, emits
//!   `FundingSettlementPoint` each time `next_funding_time` advances past the
//!   current wall clock (crossing-detector pattern).
//! - [`TradeToBarDerived`] — subscribes to `Trade` and aggregates individual
//!   trades into OHLCV bars of a fixed interval. Used as a fallback when the
//!   venue's WS does not natively offer the requested `Kind::Kline(interval)`.
//! - [`TradeToTickBarDerived`] — closes a bar every `n` trades.
//! - [`TradeToFootprintDerived`] — time-bucketed OHLCV with per-price buy/sell breakdown.
//! - [`TradeToTickImbalanceDerived`] — López de Prado Tick Imbalance Bar.
//! - [`TradeToVolumeImbalanceDerived`] — López de Prado Volume Imbalance Bar.
//! - [`TradeToRunBarDerived`] — López de Prado Run Bar.
//!
//! ## Kline-sufficient kinds (PURE kline converters — no `Trade` dependency)
//!
//! [`TradeToRangeBarDerived`], [`TradeToVolumeBarDerived`],
//! [`TradeToDollarBarDerived`], [`TradeToRenkoBarDerived`],
//! [`TradeToPnfBarDerived`], [`TradeToKagiBarDerived`],
//! [`TradeToThreeLineBreakDerived`] subscribe ONLY to
//! `Stream::Kline(KlineInterval::new("1m"))` — never `Stream::Trade`. Their
//! price-path/volume math is fully recoverable from 1m klines: cold-start
//! history folds each closed kline into up to 4 synthetic O→H→L→C /
//! O→L→H→C trade legs via [`kline_to_synthetic_trades`]; the live WS kline
//! stream folds into incremental Δ-volume synthetic ticks via
//! [`KlineDeltaState`] (shared by all seven). See
//! [`DerivedStream::seed_kline_baseline`] for how the cold-seed hands its
//! last folded kline's baseline to the live adapter to avoid a
//! double-counted seam.

use crate::data::{
    BarPoint, BasisPoint, FootprintPoint, FundingRatePoint, FundingSettlementPoint,
    KagiSegmentPoint, MarkPricePoint, IndexPricePoint, PnfColumnPoint,
    RenkoBrickPoint, ScalarBarPoint, ThreeLineBreakLinePoint, TpoSessionPoint, TradePoint,
};
use std::collections::VecDeque;
use crate::series::{DataPoint, Kind, TpoSource};
use crate::series::SeriesKey;
use crate::subscription::{Event, Stream};
use digdigdig3::core::websocket::KlineInterval;

// ---------------------------------------------------------------------------
// Trait
// ---------------------------------------------------------------------------

/// Stateful, pure-computation stream that subscribes to one or more upstream
/// broadcast channels and emits its own `Output` type.
///
/// Implementations are spawned once per `SeriesKey` and run for the lifetime
/// of the derived multiplexer. All state is local to `self` — no shared
/// mutation, no locks.
pub(crate) trait DerivedStream: Send + 'static {
    /// Output data point type. Must already implement `DataPoint` and have a
    /// corresponding `EventFrom<Self::Output>` impl in station.rs.
    type Output: DataPoint;

    /// Upstream `Stream` variants this derived stream needs (static set).
    /// Most derived streams have a fixed dep set independent of the
    /// `SeriesKey` and override only this. Order is significant —
    /// `on_upstream_event` receives `dep_idx` matching the index of the
    /// stream in this slice.
    ///
    /// Derived streams whose deps carry a runtime parameter (e.g. a
    /// `Stream::Kline(KlineInterval)` where the interval is read from
    /// `key.kind`) implement [`deps_for_key`] instead and return `&[]`
    /// here.
    fn deps() -> &'static [Stream];

    /// Per-key dependency set, called once at spawn time. The default
    /// returns the static `deps()` cloned into a Vec — implementations
    /// whose deps need a runtime parameter (TPO subscribes to a specific
    /// `Stream::Kline(interval)`) override this.
    fn deps_for_key(_key: &SeriesKey) -> Vec<Stream> {
        Self::deps().to_vec()
    }

    /// Construct initial (empty) state for the given key. Called once before
    /// the forwarder loop begins.
    fn new_for_key(key: &SeriesKey) -> Self;

    /// Process one upstream `Event`. Returns `Some(point)` if a derived output
    /// should be emitted, `None` to silently absorb the event.
    ///
    /// `dep_idx` is the index into `Self::deps()` that produced this event,
    /// allowing implementations to branch without repeated pattern-matching.
    fn on_upstream_event(&mut self, ev: &Event, dep_idx: usize) -> Option<Self::Output>;

    /// Seed internal state from a batch of upstream events at spawn time, before
    /// the live event loop begins. Returns all derived outputs emitted during the
    /// seed pass so callers can broadcast them (cold-start window visible to
    /// consumers immediately).
    ///
    /// `dep_idx` matches the index in `Self::deps()`. Default implementation
    /// feeds each event through `on_upstream_event` and collects results — works
    /// for all trade-derived impls without any additional code.
    fn seed_from_events(&mut self, events: &[Event], dep_idx: usize) -> Vec<Self::Output> {
        events.iter().filter_map(|e| self.on_upstream_event(e, dep_idx)).collect()
    }

    /// Hand the cold-seed's last-folded-kline baseline to the live
    /// delta-tick adapter, so the first live WS kline update for the SAME
    /// `open_time` computes a correct `Δvolume` against the seed's already-
    /// folded volume instead of double-counting or under-counting.
    ///
    /// Called once, immediately after [`DerivedStream::new_for_key`] and
    /// before any live event is fed, ONLY when the cold-seed produced at
    /// least one kline bar. Kline-sufficient kinds
    /// (Renko/PnF/Kagi/3LB/Range/Volume/Dollar) override this to forward
    /// into their embedded [`KlineDeltaState::seed_baseline`]. Every other
    /// derived kind keeps the no-op default.
    fn seed_kline_baseline(&mut self, _open_time: i64, _volume: f64, _close: f64) {}
}

// ---------------------------------------------------------------------------
// KlineDeltaState — shared live Δ-tick adapter for the kline-sufficient
// kinds (Renko / PnF / Kagi / Three-Line-Break / Range / Volume / Dollar)
// ---------------------------------------------------------------------------

/// Live-folding adapter shared by every kline-sufficient derived kind.
///
/// The WS `Stream::Kline("1m")` upstream delivers repeated `Event::Bar`
/// updates for the SAME in-progress bar (same `open_time`, growing
/// `volume`, moving `close`), then a new `open_time` once that bar closes.
/// This adapter folds that stream into synthetic `Event::Trade` ticks with
/// NO rollback, per the doctrine:
///
/// - Same `open_time` as the last seen bar → emit ONE synthetic trade:
///   `price = point.close`, `quantity = max(point.volume - last_seen_volume, 0)`,
///   `side` inferred from `point.close` vs the last close. A zero/negative
///   delta (duplicate frame, or a corrective re-send with lower volume)
///   emits nothing.
/// - New `open_time` (bar rolled) → the previous bar is final and is NEVER
///   re-folded (its path was already folded tick-by-tick as it happened).
///   The new bar starts its own Δ-accounting from a zero volume baseline,
///   so the first observed update on the new bar contributes its own
///   already-accrued volume as one synthetic trade — never the delta
///   against the old bar's volume.
/// - `last_close` carries across a rollover (price-continuity for side
///   inference); `last_seen_volume` does not.
///
/// ## Cold-seed seam
///
/// [`KlineDeltaState::seed_baseline`] primes `last_open_time` /
/// `last_seen_volume` / `last_close` from the cold-seed's last folded
/// kline (see [`DerivedStream::seed_kline_baseline`]) BEFORE any live event
/// arrives, so a live update sharing that same `open_time` computes a
/// correct incremental delta instead of re-folding the whole bar.
///
/// ## Timestamps
///
/// No wall-clock read (wasm-safe, deterministic). Each synthetic tick's
/// `ts_ms` is `point.open_time + offset`, where `offset` is a per-bar
/// monotonically increasing counter clamped to `[0, interval_ms)` — same
/// spacing family as [`kline_to_synthetic_trades`], generalized to an
/// unbounded number of live ticks per bar instead of a fixed 4 legs.
pub(crate) struct KlineDeltaState {
    /// `open_time` of the last observed bar. `i64::MIN` = unseeded.
    last_open_time: i64,
    /// Cumulative volume already accounted for within `last_open_time`.
    last_seen_volume: f64,
    /// Last observed close price (carried across rollovers for side inference).
    last_close: f64,
    /// Per-bar monotonic tick offset, reset to 0 on every rollover.
    tick_offset: i64,
}

impl KlineDeltaState {
    pub(crate) fn new() -> Self {
        Self {
            last_open_time: i64::MIN,
            last_seen_volume: 0.0,
            last_close: 0.0,
            tick_offset: 0,
        }
    }

    /// Prime the baseline from the cold-seed's last folded kline bar. Must
    /// be called before the first live event — see
    /// [`DerivedStream::seed_kline_baseline`].
    pub(crate) fn seed_baseline(&mut self, open_time: i64, volume: f64, close: f64) {
        self.last_open_time = open_time;
        self.last_seen_volume = volume;
        self.last_close = close;
        self.tick_offset = 0;
    }

    /// Fold one `Event::Bar` update into at most one synthetic
    /// `Event::Trade`. Returns `None` when there is nothing new to report
    /// (duplicate frame / non-positive delta) or when `interval_ms` cannot
    /// be resolved from `timeframe`.
    fn to_delta_trade(
        &mut self,
        bar: &BarPoint,
        timeframe: &KlineInterval,
        exchange: digdigdig3::core::types::ExchangeId,
        symbol: &str,
    ) -> Option<Event> {
        let interval_ms = interval_to_ms(timeframe.as_str()).unwrap_or(60_000).max(1);

        if self.last_open_time == i64::MIN {
            // First event ever seen with no cold-seed baseline handed over —
            // establish the baseline without emitting (nothing to delta
            // against yet; avoids treating the entire in-progress bar's
            // volume-to-date as a single synthetic trade on cold start).
            self.last_open_time = bar.open_time;
            self.last_seen_volume = bar.volume;
            self.last_close = bar.close;
            self.tick_offset = 0;
            return None;
        }

        let delta_volume = if bar.open_time == self.last_open_time {
            (bar.volume - self.last_seen_volume).max(0.0)
        } else if bar.open_time > self.last_open_time {
            // Bar rolled — previous bar is final, never re-folded. Baseline
            // for the new bar starts at zero volume.
            self.last_open_time = bar.open_time;
            self.tick_offset = 0;
            bar.volume.max(0.0)
        } else {
            // Stale/out-of-order bar (older open_time) — ignore.
            return None;
        };

        if delta_volume <= 0.0 {
            self.last_seen_volume = bar.volume;
            self.last_close = bar.close;
            return None;
        }

        let side = u8::from(bar.close < self.last_close);
        let offset = self.tick_offset.clamp(0, interval_ms - 1);
        self.tick_offset += 1;

        self.last_seen_volume = bar.volume;
        self.last_close = bar.close;

        Some(Event::Trade {
            exchange,
            symbol: symbol.to_string(),
            point: TradePoint {
                ts_ms: bar.open_time + offset,
                price: bar.close,
                quantity: delta_volume,
                side,
                trade_id_hash: 0,
            },
        })
    }
}

// ---------------------------------------------------------------------------
// BasisDerived
// ---------------------------------------------------------------------------

/// Joins `MarkPrice` (dep index 0) and `IndexPrice` (dep index 1), emitting
/// `BasisPoint { value = mark − index }` on every qualifying update.
///
/// Pairs with timestamps more than `max_skew_ms` apart are rejected. Default
/// skew threshold is 2 000 ms — 10× the typical 200 ms inter-channel lag on
/// Binance `markPrice@1s` / `indexPrice@1s`.
pub(crate) struct BasisDerived {
    /// Most recent (ts_ms, mark_price) from the MarkPrice upstream.
    last_mark: Option<(i64, f64)>,
    /// Most recent (ts_ms, index_price) from the IndexPrice upstream.
    last_index: Option<(i64, f64)>,
    /// Maximum allowed age difference between the two sides (milliseconds).
    max_skew_ms: i64,
}

impl DerivedStream for BasisDerived {
    type Output = BasisPoint;

    fn deps() -> &'static [Stream] {
        &[Stream::MarkPrice, Stream::IndexPrice]
    }

    fn new_for_key(_key: &SeriesKey) -> Self {
        Self {
            last_mark: None,
            last_index: None,
            max_skew_ms: 2_000,
        }
    }

    fn on_upstream_event(&mut self, ev: &Event, dep_idx: usize) -> Option<BasisPoint> {
        match dep_idx {
            0 => {
                if let Event::MarkPrice { point, .. } = ev {
                    self.last_mark = Some((point.ts_ms, point.mark));
                }
            }
            1 => {
                if let Event::IndexPrice { point, .. } = ev {
                    self.last_index = Some((point.ts_ms, point.price));
                }
            }
            _ => return None,
        }

        let (mark_ts, mark) = self.last_mark?;
        let (idx_ts,  idx)  = self.last_index?;

        if (mark_ts - idx_ts).abs() > self.max_skew_ms {
            return None;
        }

        let now_ms = mark_ts.max(idx_ts);
        Some(BasisPoint {
            ts_ms: now_ms,
            value: mark - idx,
            mark,
            index: idx,
        })
    }
}

// ---------------------------------------------------------------------------
// interval_to_ms
// ---------------------------------------------------------------------------

/// Convert a [`KlineInterval`] string (e.g. `"1s"`, `"3m"`, `"2h"`, `"1d"`,
/// `"1w"`) to its duration in milliseconds.
///
/// Returns `None` for any unrecognised string — the caller must handle that
/// case (typically by refusing to spawn the aggregator and returning a
/// `StationError::StreamNotSupported`).
///
/// Handled intervals (Binance / common exchange convention):
/// `1s 3s 5s 10s 15s 30s 1m 3m 5m 15m 30m 1h 2h 4h 6h 8h 12h 1d 3d 1w`
pub(crate) fn interval_to_ms(interval: &str) -> Option<i64> {
    // Fast path for the common case: one-or-two digit number + single letter.
    let bytes = interval.as_bytes();
    if bytes.is_empty() {
        return None;
    }
    let unit = *bytes.last()?;
    // Parse the numeric prefix.
    let n_str = std::str::from_utf8(&bytes[..bytes.len().saturating_sub(1)]).ok()?;
    let n: i64 = n_str.parse().ok()?;
    if n <= 0 {
        return None;
    }
    const SEC: i64 = 1_000;
    const MIN: i64 = 60 * SEC;
    const HOUR: i64 = 60 * MIN;
    const DAY: i64 = 24 * HOUR;
    match unit {
        b's' => Some(n * SEC),
        b'm' => Some(n * MIN),
        b'h' | b'H' => Some(n * HOUR),
        b'd' | b'D' => Some(n * DAY),
        b'w' | b'W' => Some(n * 7 * DAY),
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// TradeToBarDerived
// ---------------------------------------------------------------------------

/// Aggregates individual `Trade` events into OHLCV [`BarPoint`] bars for a
/// fixed `interval` (e.g. `"1m"`, `"5m"`, `"1h"`).
///
/// Used as a **fallback** when the venue's WS does not natively offer the
/// requested `Kind::Kline(interval)`. Station spawns this derived stream
/// instead of a WS forwarder, and consumers receive the same `Event::Bar`
/// events as they would from a native kline channel.
///
/// ## Bar semantics
///
/// Bars are aligned to UTC epoch boundaries: `bucket_start = (ts_ms /
/// interval_ms) * interval_ms`. Each trade either starts a new bar or
/// updates the current one in-place. The bar is emitted (as a partial /
/// open bar) on **every trade**, so consumers see live intra-bar updates.
/// When a trade from the next bucket arrives the previous bar is implicitly
/// closed (its last emitted state is the final OHLCV). Empty intervals
/// produce no bar — identical to HyperLiquid's native kline behaviour.
///
/// ## Construction via `new_for_key`
///
/// If `key.kind` is not `Kind::Kline(iv)`, or if `interval_to_ms` returns
/// `None` for the interval string, `interval_ms` is set to `0`. With
/// `interval_ms == 0` no buckets can ever form and `on_upstream_event`
/// always returns `None` — safe and panic-free.
pub(crate) struct TradeToBarDerived {
    /// Bucket width in milliseconds. `0` means "disabled" (unknown interval).
    interval_ms: i64,
    /// The currently-open (partial) bar, if any.
    current: Option<BarPoint>,
    /// Bucket start of `current` (ms). `0` when `current` is `None`.
    current_bucket_start: i64,
}

impl DerivedStream for TradeToBarDerived {
    type Output = BarPoint;

    fn deps() -> &'static [Stream] {
        &[Stream::Trade]
    }

    fn new_for_key(key: &SeriesKey) -> Self {
        let interval_ms = match &key.kind {
            Kind::Kline(iv) => interval_to_ms(iv.as_str()).unwrap_or(0),
            _ => 0,
        };
        Self { interval_ms, current: None, current_bucket_start: 0 }
    }

    fn on_upstream_event(&mut self, ev: &Event, _dep_idx: usize) -> Option<BarPoint> {
        // Disabled aggregator (unknown interval) or non-Trade event.
        if self.interval_ms == 0 {
            return None;
        }
        let Event::Trade { point, .. } = ev else { return None };

        let bucket_start = (point.ts_ms / self.interval_ms) * self.interval_ms;

        if self.current.is_none() || bucket_start > self.current_bucket_start {
            // Open a new bar.
            let bar = BarPoint {
                open_time: bucket_start,
                open:  point.price,
                high:  point.price,
                low:   point.price,
                close: point.price,
                volume:       point.quantity,
                quote_volume: point.price * point.quantity,
                trades_count: 1,
            };
            self.current = Some(bar.clone());
            self.current_bucket_start = bucket_start;
            Some(bar)
        } else {
            // Update current bar in-place.
            let bar = self.current.as_mut()?;
            if point.price > bar.high  { bar.high  = point.price; }
            if point.price < bar.low   { bar.low   = point.price; }
            bar.close        = point.price;
            bar.volume       += point.quantity;
            bar.quote_volume += point.price * point.quantity;
            bar.trades_count += 1;
            Some(bar.clone())
        }
    }
}

// ---------------------------------------------------------------------------
// TradeToRangeBarDerived
// ---------------------------------------------------------------------------

/// Aggregates `Trade` events into OHLCV [`BarPoint`] bars triggered by price movement.
///
/// ## Bar semantics
///
/// `range` (from `Kind::RangeBar(r)`) is stored as `r / 1e8` internally.
/// A new bar opens when `|trade.price − bar_open| >= range`. The crossing trade
/// belongs to the **new** bar (not the closing one).
///
/// ## Monotonic `open_time`
///
/// Range/tick/volume bars can close in the same millisecond. `Series::upsert_by_ts`
/// keys on `open_time`, so two distinct bars with equal ms would collapse.
/// To prevent this, `open_time` is `max(first_trade_ts, last_emitted_open_time + 1)`.
/// This guarantees strict monotonicity across all emitted bars without altering
/// the semantic meaning of `open_time` (it remains the timestamp of the first
/// trade in the bar, or 1 ms later if that timestamp collides).
///
/// ## Emit semantics
///
/// The current open bar is emitted on **every trade** (same as `TradeToBarDerived`),
/// so consumers see live intra-bar updates via upsert.
///
/// ## Disabled guard
///
/// If `range == 0` (key kind is not `RangeBar` or param is zero), `on_upstream_event`
/// always returns `None` — safe and panic-free.
pub(crate) struct TradeToRangeBarDerived {
    /// Minimum price movement to close bar, in native price units (`param / 1e8`).
    /// `0.0` means disabled.
    range: f64,
    /// Currently-open bar, if any.
    current: Option<BarPoint>,
    /// The `open_time` of the last bar that was finalized (emitted as a closed bar).
    /// Used for monotonic open_time collision avoidance.
    last_emitted_open_time: i64,
    /// Live Δ-tick adapter over the `Stream::Kline("1m")` upstream — see
    /// [`KlineDeltaState`]. Kline-sufficient kind: no `Stream::Trade` dependency.
    kline_state: KlineDeltaState,
}

impl DerivedStream for TradeToRangeBarDerived {
    type Output = BarPoint;

    fn deps() -> &'static [Stream] { &[] }

    fn deps_for_key(_key: &SeriesKey) -> Vec<Stream> {
        vec![Stream::Kline(KlineInterval::new("1m"))]
    }

    fn new_for_key(key: &SeriesKey) -> Self {
        let range = match &key.kind {
            Kind::RangeBar(r) if *r > 0 => *r as f64 / 1e8,
            _ => 0.0,
        };
        Self { range, current: None, last_emitted_open_time: 0, kline_state: KlineDeltaState::new() }
    }

    fn seed_kline_baseline(&mut self, open_time: i64, volume: f64, close: f64) {
        self.kline_state.seed_baseline(open_time, volume, close);
    }

    fn on_upstream_event(&mut self, ev: &Event, _dep_idx: usize) -> Option<BarPoint> {
        if self.range == 0.0 { return None; }
        match ev {
            // Cold-seed / rewarm: 4-leg synthetic trades from
            // `kline_to_synthetic_trades` — fed directly.
            Event::Trade { point, .. } => self.fold_trade(point),
            // Live WS path: fold the kline update into a Δ-volume synthetic
            // tick via the shared adapter, then feed it the same way.
            Event::Bar { point: bar, timeframe, exchange, symbol } => {
                let synth = self.kline_state.to_delta_trade(bar, timeframe, *exchange, symbol)?;
                let Event::Trade { point, .. } = &synth else { unreachable!("to_delta_trade always returns Event::Trade") };
                self.fold_trade(point)
            }
            _ => None,
        }
    }
}

impl TradeToRangeBarDerived {
    fn fold_trade(&mut self, point: &TradePoint) -> Option<BarPoint> {
        if let Some(ref mut bar) = self.current {
            // Check close condition BEFORE updating.
            if (point.price - bar.open).abs() >= self.range {
                // Finalize current bar (no update with crossing trade — it starts the new bar).
                let closed = bar.clone();
                // Emit the closed bar. open_time is already set.

                // Open new bar at crossing trade.
                let new_open_time = point.ts_ms.max(self.last_emitted_open_time + 1);
                self.last_emitted_open_time = new_open_time;
                self.current = Some(BarPoint {
                    open_time:   new_open_time,
                    open:        point.price,
                    high:        point.price,
                    low:         point.price,
                    close:       point.price,
                    volume:      point.quantity,
                    quote_volume: point.price * point.quantity,
                    trades_count: 1,
                });
                // Emit the new (open) bar rather than the closed one so callers
                // receive the in-progress state immediately (same contract as
                // TradeToBarDerived). The closed bar was already emitted on the
                // previous trade call that reached bar.close == crossing trade.
                // Returning the new bar gives the consumer one event per trade.
                let _ = closed; // closed bar state committed
                return Some(self.current.clone().unwrap());
            }
            // Update in-place.
            if point.price > bar.high  { bar.high  = point.price; }
            if point.price < bar.low   { bar.low   = point.price; }
            bar.close        = point.price;
            bar.volume       += point.quantity;
            bar.quote_volume += point.price * point.quantity;
            bar.trades_count += 1;
            Some(bar.clone())
        } else {
            // First trade — open a new bar.
            let open_time = point.ts_ms.max(self.last_emitted_open_time + 1);
            self.last_emitted_open_time = open_time;
            let bar = BarPoint {
                open_time,
                open:        point.price,
                high:        point.price,
                low:         point.price,
                close:       point.price,
                volume:      point.quantity,
                quote_volume: point.price * point.quantity,
                trades_count: 1,
            };
            self.current = Some(bar.clone());
            Some(bar)
        }
    }
}

// ---------------------------------------------------------------------------
// TradeToTickBarDerived
// ---------------------------------------------------------------------------

/// Aggregates `Trade` events into OHLCV [`BarPoint`] bars triggered by trade count.
///
/// ## Bar semantics
///
/// Closes a bar every `n` trades (from `Kind::TickBar(n)`). The `n`-th trade
/// belongs to the **closing** bar.
///
/// See [`TradeToRangeBarDerived`] for the monotonic `open_time` scheme and
/// intra-bar emit semantics — both apply here.
pub(crate) struct TradeToTickBarDerived {
    /// Trades per bar. `0` means disabled.
    n: u32,
    /// Currently-open bar, if any.
    current: Option<BarPoint>,
    /// Trades accumulated in the current bar.
    count: u32,
    /// See [`TradeToRangeBarDerived`] doc.
    last_emitted_open_time: i64,
}

impl DerivedStream for TradeToTickBarDerived {
    type Output = BarPoint;

    fn deps() -> &'static [Stream] { &[Stream::Trade] }

    fn new_for_key(key: &SeriesKey) -> Self {
        let n = match &key.kind {
            Kind::TickBar(n) if *n > 0 => *n,
            _ => 0,
        };
        Self { n, current: None, count: 0, last_emitted_open_time: 0 }
    }

    fn on_upstream_event(&mut self, ev: &Event, _dep_idx: usize) -> Option<BarPoint> {
        if self.n == 0 { return None; }
        let Event::Trade { point, .. } = ev else { return None };

        if self.current.is_none() {
            let open_time = point.ts_ms.max(self.last_emitted_open_time + 1);
            self.last_emitted_open_time = open_time;
            self.current = Some(BarPoint {
                open_time,
                open:        point.price,
                high:        point.price,
                low:         point.price,
                close:       point.price,
                volume:      point.quantity,
                quote_volume: point.price * point.quantity,
                trades_count: 1,
            });
            self.count = 1;
        } else {
            let bar = self.current.as_mut()?;
            if point.price > bar.high  { bar.high  = point.price; }
            if point.price < bar.low   { bar.low   = point.price; }
            bar.close        = point.price;
            bar.volume       += point.quantity;
            bar.quote_volume += point.price * point.quantity;
            bar.trades_count += 1;
            self.count += 1;
        }

        let bar = self.current.clone()?;

        // Roll if we hit n trades.
        if self.count >= self.n {
            // Next bar will be opened on the next trade.
            self.current = None;
            self.count = 0;
        }

        Some(bar)
    }
}

// ---------------------------------------------------------------------------
// TradeToVolumeBarDerived
// ---------------------------------------------------------------------------

/// Aggregates `Trade` events into OHLCV [`BarPoint`] bars triggered by cumulative volume.
///
/// ## Bar semantics
///
/// `threshold` (from `Kind::VolumeBar(v)`) is stored as `v / 1e8` internally.
/// The bar closes when `cumulative_volume >= threshold`. The trade that crosses
/// the threshold belongs to the **closing** bar (no volume carry-over to the
/// next bar — document: partial fills that split across bars are not tracked).
///
/// See [`TradeToRangeBarDerived`] for monotonic `open_time` and emit semantics.
pub(crate) struct TradeToVolumeBarDerived {
    /// Volume threshold in native units (`param / 1e8`). `0.0` means disabled.
    threshold: f64,
    /// Currently-open bar, if any.
    current: Option<BarPoint>,
    /// See [`TradeToRangeBarDerived`] doc.
    last_emitted_open_time: i64,
    /// Live Δ-tick adapter over the `Stream::Kline("1m")` upstream — see
    /// [`KlineDeltaState`]. Kline-sufficient kind: no `Stream::Trade` dependency.
    kline_state: KlineDeltaState,
}

impl DerivedStream for TradeToVolumeBarDerived {
    type Output = BarPoint;

    fn deps() -> &'static [Stream] { &[] }

    fn deps_for_key(_key: &SeriesKey) -> Vec<Stream> {
        vec![Stream::Kline(KlineInterval::new("1m"))]
    }

    fn new_for_key(key: &SeriesKey) -> Self {
        let threshold = match &key.kind {
            Kind::VolumeBar(v) if *v > 0 => *v as f64 / 1e8,
            _ => 0.0,
        };
        Self { threshold, current: None, last_emitted_open_time: 0, kline_state: KlineDeltaState::new() }
    }

    fn seed_kline_baseline(&mut self, open_time: i64, volume: f64, close: f64) {
        self.kline_state.seed_baseline(open_time, volume, close);
    }

    fn on_upstream_event(&mut self, ev: &Event, _dep_idx: usize) -> Option<BarPoint> {
        if self.threshold == 0.0 { return None; }
        match ev {
            Event::Trade { point, .. } => self.fold_trade(point),
            Event::Bar { point: bar, timeframe, exchange, symbol } => {
                let synth = self.kline_state.to_delta_trade(bar, timeframe, *exchange, symbol)?;
                let Event::Trade { point, .. } = &synth else { unreachable!("to_delta_trade always returns Event::Trade") };
                self.fold_trade(point)
            }
            _ => None,
        }
    }
}

impl TradeToVolumeBarDerived {
    fn fold_trade(&mut self, point: &TradePoint) -> Option<BarPoint> {
        if self.current.is_none() {
            let open_time = point.ts_ms.max(self.last_emitted_open_time + 1);
            self.last_emitted_open_time = open_time;
            self.current = Some(BarPoint {
                open_time,
                open:        point.price,
                high:        point.price,
                low:         point.price,
                close:       point.price,
                volume:      point.quantity,
                quote_volume: point.price * point.quantity,
                trades_count: 1,
            });
        } else {
            let bar = self.current.as_mut()?;
            if point.price > bar.high  { bar.high  = point.price; }
            if point.price < bar.low   { bar.low   = point.price; }
            bar.close        = point.price;
            bar.volume       += point.quantity;
            bar.quote_volume += point.price * point.quantity;
            bar.trades_count += 1;
        }

        let bar = self.current.clone()?;

        // Roll if volume crossed threshold (crossing trade is in the closing bar).
        if bar.volume >= self.threshold {
            self.current = None;
        }

        Some(bar)
    }
}

// ---------------------------------------------------------------------------
// TradeToFootprintDerived
// ---------------------------------------------------------------------------

/// Aggregates `Trade` events into time-bucketed [`FootprintPoint`] bars with
/// per-price buy/sell volume breakdown.
///
/// ## Time bucketing
///
/// Uses `KlineInterval` (from `Kind::Footprint(iv)`) aligned to UTC epoch:
/// `bucket_start = (ts_ms / interval_ms) * interval_ms`. Same as `TradeToBarDerived`.
///
/// ## Per-price levels
///
/// Each trade's price maps to a `(buy_vol, sell_vol)` entry in a `BTreeMap`
/// (ordered by price). Side `0` = Buy, `1` = Sell (matches `TradePoint::side`).
/// Price key is the raw `f64` bit-pattern (`u64::from_le_bytes(price.to_le_bytes())`),
/// which gives exact equality on repeated same-price trades without float precision loss.
///
/// ## Emit semantics
///
/// The current open footprint is emitted on **every trade** via `upsert_by_ts`
/// (same contract as `TradeToBarDerived`). On bucket roll, the new bar is emitted.
///
/// ## Disabled guard
///
/// `interval_ms == 0` → always returns `None`.
pub(crate) struct TradeToFootprintDerived {
    /// Bucket width in milliseconds. `0` = disabled.
    interval_ms: i64,
    /// Current bucket start.
    current_bucket_start: i64,
    /// OHLCV of the current bucket.
    current_ohlcv: Option<(f64, f64, f64, f64, f64)>, // open, high, low, close, volume
    /// Per-price accumulator: price_bits → (buy_vol, sell_vol).
    levels: std::collections::BTreeMap<u64, (f64, f64)>,
}

impl TradeToFootprintDerived {
    fn price_bits(price: f64) -> u64 {
        u64::from_le_bytes(price.to_le_bytes())
    }

    fn build_point(&self, open_time: i64) -> FootprintPoint {
        let (open, high, low, close, volume) = self.current_ohlcv.unwrap_or((0.0, 0.0, 0.0, 0.0, 0.0));
        // Convert BTreeMap (ordered by price bits, which for positive f64 matches
        // ascending numeric order) to sorted-by-price Vec.
        let levels: Vec<(f64, f64, f64)> = self.levels.iter().map(|(bits, (buy, sell))| {
            let price = f64::from_le_bytes(bits.to_le_bytes());
            (price, *buy, *sell)
        }).collect();
        FootprintPoint { open_time, open, high, low, close, volume, levels }
    }
}

impl DerivedStream for TradeToFootprintDerived {
    type Output = FootprintPoint;

    fn deps() -> &'static [Stream] { &[Stream::Trade] }

    fn new_for_key(key: &SeriesKey) -> Self {
        let interval_ms = match &key.kind {
            Kind::Footprint(iv) => interval_to_ms(iv.as_str()).unwrap_or(0),
            _ => 0,
        };
        Self {
            interval_ms,
            current_bucket_start: 0,
            current_ohlcv: None,
            levels: std::collections::BTreeMap::new(),
        }
    }

    fn on_upstream_event(&mut self, ev: &Event, _dep_idx: usize) -> Option<FootprintPoint> {
        if self.interval_ms == 0 {
            eprintln!("[dig3-fp-derived] interval_ms=0 → return None (disabled guard)");
            return None;
        }
        let Event::Trade { point, .. } = ev else {
            // Not a Trade event — log first 3 only so logs don't explode.
            return None
        };

        let bucket_start = (point.ts_ms / self.interval_ms) * self.interval_ms;
        let rolled = self.current_ohlcv.is_none() || bucket_start > self.current_bucket_start;

        if rolled {
            // Roll to new bucket.
            self.current_bucket_start = bucket_start;
            self.current_ohlcv = Some((point.price, point.price, point.price, point.price, point.quantity));
            self.levels.clear();
            // First level entry.
            let bits = Self::price_bits(point.price);
            let entry = self.levels.entry(bits).or_insert((0.0, 0.0));
            if point.side == 0 { entry.0 += point.quantity; } else { entry.1 += point.quantity; }
            eprintln!(
                "[dig3-fp-derived] BUCKET ROLL ts_ms={} bucket_start={} price={:.2} side={} qty={:.6}",
                point.ts_ms, bucket_start, point.price, point.side, point.quantity,
            );
        } else {
            // Update current bucket.
            let ohlcv = self.current_ohlcv.as_mut()?;
            if point.price > ohlcv.1 { ohlcv.1 = point.price; } // high
            if point.price < ohlcv.2 { ohlcv.2 = point.price; } // low
            ohlcv.3 = point.price; // close
            ohlcv.4 += point.quantity; // volume
            let bits = Self::price_bits(point.price);
            let entry = self.levels.entry(bits).or_insert((0.0, 0.0));
            if point.side == 0 { entry.0 += point.quantity; } else { entry.1 += point.quantity; }
        }

        let pt = self.build_point(self.current_bucket_start);
        // Log every 100th tick + every bucket roll so we see live cluster growth.
        if rolled || self.levels.len() % 100 == 0 {
            eprintln!(
                "[dig3-fp-derived] emit FootprintPoint open_time={} levels.len()={} vol={:.4} ohlc=[o={:.2} h={:.2} l={:.2} c={:.2}]",
                pt.open_time, pt.levels.len(), pt.volume, pt.open, pt.high, pt.low, pt.close,
            );
        }
        Some(pt)
    }
}

// ---------------------------------------------------------------------------
// TradeToRenkoBarDerived
// ---------------------------------------------------------------------------

/// Aggregates `Trade` events into fixed-height Renko bricks.
///
/// ## Brick semantics
///
/// `box_size` (from `Kind::RenkoBar(b, _)`) is stored as `b / 1e8`. A new
/// brick is emitted whenever the trade price moves at least one full
/// `box_size` in the current direction. Reversal requires
/// `reversal_count × box_size` of opposing movement; when it fires, ONE
/// brick is consumed (mplfinance gap-fill rule) and the remainder emit.
///
/// ## Output shape (`BarPoint`)
///
/// Up bricks: `open = brick_bottom, close = brick_top`. Down bricks:
/// `open = brick_top, close = brick_bottom`. `high = max`, `low = min`
/// of the brick's price span. `volume` accumulates trade volume across
/// the bar but is reset to 0 between bricks (we cannot legitimately
/// split a single trade's volume across two bricks).
///
/// ## Monotonic open_time
///
/// Same scheme as [`TradeToRangeBarDerived`].
///
/// ## Disabled guard
///
/// `box_size == 0.0` ⇒ always `None`.
pub(crate) struct TradeToRenkoBarDerived {
    /// Brick price height in native units. `0.0` ⇒ disabled.
    box_size: f64,
    /// Bricks required to flip direction (default 2 = TradeStation classic).
    reversal_count: u8,
    /// Anchor price — the price level the current direction was last at.
    /// New bricks emit when `|trade.price − anchor| ≥ box_size`.
    anchor: f64,
    /// Direction of the last emitted brick: `Some(true)` = up, `Some(false)`
    /// = down, `None` = no brick yet (seed phase).
    last_dir: Option<bool>,
    /// Volume accumulator for the in-progress brick.
    vol_acc: f64,
    /// Trade-count accumulator.
    tcount_acc: u64,
    /// Monotonic open_time guard — same as range/tick/volume bars.
    last_emitted_open_time: i64,
    /// True once the grid anchor has been established (either by the
    /// first-trade floor-snap or by [`Self::preset_grid_anchor`]). Blocks
    /// the floor-snap from re-firing when a rewarm-fold preset the anchor
    /// explicitly (a preset anchor may legitimately be `0.0`).
    seeded: bool,
    /// Live Δ-tick adapter over the `Stream::Kline("1m")` upstream — see
    /// [`KlineDeltaState`]. Kline-sufficient kind: no `Stream::Trade` dependency.
    kline_state: KlineDeltaState,
}

impl TradeToRenkoBarDerived {
    /// Preset the grid anchor from an already-emitted brick's lower
    /// boundary (`bottom`), so a throwaway fold over an OLDER trade window
    /// continues on the SAME grid as the live series instead of floor-
    /// snapping to whatever price the older window happens to start at.
    ///
    /// Must be called immediately after [`DerivedStream::new_for_key`],
    /// before feeding any events — it suppresses the first-trade
    /// floor-snap in [`Self::on_upstream_event`] by marking the state
    /// already-seeded.
    pub(crate) fn preset_grid_anchor(&mut self, grid_floor: f64) {
        self.anchor = grid_floor;
        self.seeded = true;
    }
}

impl DerivedStream for TradeToRenkoBarDerived {
    type Output = RenkoBrickPoint;

    fn deps() -> &'static [Stream] { &[] }

    fn deps_for_key(_key: &SeriesKey) -> Vec<Stream> {
        vec![Stream::Kline(KlineInterval::new("1m"))]
    }

    fn new_for_key(key: &SeriesKey) -> Self {
        let (box_size, reversal_count) = match &key.kind {
            Kind::RenkoBar(b, r) if *b > 0 => (*b as f64 / 1e8, (*r).max(1)),
            _ => (0.0, 1),
        };
        Self {
            box_size,
            reversal_count,
            anchor: 0.0,
            last_dir: None,
            vol_acc: 0.0,
            tcount_acc: 0,
            last_emitted_open_time: 0,
            seeded: false,
            kline_state: KlineDeltaState::new(),
        }
    }

    fn seed_kline_baseline(&mut self, open_time: i64, volume: f64, close: f64) {
        self.kline_state.seed_baseline(open_time, volume, close);
    }

    fn on_upstream_event(&mut self, ev: &Event, _dep_idx: usize) -> Option<RenkoBrickPoint> {
        if self.box_size == 0.0 { return None; }
        match ev {
            Event::Trade { point, .. } => self.fold_trade(point),
            Event::Bar { point: bar, timeframe, exchange, symbol } => {
                let synth = self.kline_state.to_delta_trade(bar, timeframe, *exchange, symbol)?;
                let Event::Trade { point, .. } = &synth else { unreachable!("to_delta_trade always returns Event::Trade") };
                self.fold_trade(point)
            }
            _ => None,
        }
    }
}

impl TradeToRenkoBarDerived {
    fn fold_trade(&mut self, point: &TradePoint) -> Option<RenkoBrickPoint> {
        // Seed anchor on the very first trade — skipped when the anchor
        // was already preset via `preset_grid_anchor` (rewarm-fold path).
        if !self.seeded {
            self.anchor = (point.price / self.box_size).floor() * self.box_size;
            self.seeded = true;
        }

        self.vol_acc += point.quantity;
        self.tcount_acc += 1;

        let mut last_emitted: Option<RenkoBrickPoint> = None;

        loop {
            let up_target = self.anchor + self.box_size;
            let down_target = self.anchor - self.box_size;

            if point.price >= up_target {
                if matches!(self.last_dir, Some(false)) {
                    let needed = self.anchor + self.box_size * self.reversal_count as f64;
                    if point.price < needed { break; }
                    self.anchor += self.box_size;
                }
                let open_time = point.ts_ms.max(self.last_emitted_open_time + 1);
                self.last_emitted_open_time = open_time;
                let brick = RenkoBrickPoint {
                    open_time,
                    bottom: self.anchor,
                    top: self.anchor + self.box_size,
                    up: true,
                    volume: self.vol_acc,
                    trades_count: self.tcount_acc,
                };
                self.vol_acc = 0.0;
                self.tcount_acc = 0;
                self.anchor += self.box_size;
                self.last_dir = Some(true);
                last_emitted = Some(brick);
                continue;
            }

            if point.price <= down_target {
                if matches!(self.last_dir, Some(true)) {
                    let needed = self.anchor - self.box_size * self.reversal_count as f64;
                    if point.price > needed { break; }
                    self.anchor -= self.box_size;
                }
                let open_time = point.ts_ms.max(self.last_emitted_open_time + 1);
                self.last_emitted_open_time = open_time;
                let brick = RenkoBrickPoint {
                    open_time,
                    bottom: self.anchor - self.box_size,
                    top: self.anchor,
                    up: false,
                    volume: self.vol_acc,
                    trades_count: self.tcount_acc,
                };
                self.vol_acc = 0.0;
                self.tcount_acc = 0;
                self.anchor -= self.box_size;
                self.last_dir = Some(false);
                last_emitted = Some(brick);
                continue;
            }

            break;
        }

        last_emitted
    }
}

// ---------------------------------------------------------------------------
// TradeToPnfBarDerived
// ---------------------------------------------------------------------------

/// Aggregates `Trade` events into Point-and-Figure (X/O) columns.
///
/// ## Column semantics
///
/// `box_size` from `Kind::PnfBar(b, _)` stored as `b / 1e8`.
/// `reversal_count` = boxes required to start a new opposite-direction
/// column (industry default = 3, TradeStation classic).
///
/// ## Output (`PnfColumnPoint`)
///
/// Emits one column point per trade — the **current** column, updated
/// in-place. The column rolls (direction flips) when reversal_count ×
/// box_size of opposing movement is hit; the new column's first box is
/// placed one box away from the prior column's terminal box (mplfinance
/// convention).
///
/// `column_id` strictly monotonic per-Derived-instance — caller groups
/// trades into columns via column_id, doesn't need to diff `(top, bot)`.
///
/// ## Disabled guard: `box_size == 0.0`.
pub(crate) struct TradeToPnfBarDerived {
    box_size: f64,
    reversal_count: u8,
    /// Currently-open column, if any.
    cur: Option<PnfColumnPoint>,
    /// Monotonic column id counter; first column = 1.
    next_column_id: u64,
    /// Monotonic open_time guard.
    last_emitted_open_time: i64,
    /// Live Δ-tick adapter over the `Stream::Kline("1m")` upstream — see
    /// [`KlineDeltaState`]. Kline-sufficient kind: no `Stream::Trade` dependency.
    kline_state: KlineDeltaState,
}

impl TradeToPnfBarDerived {
    /// Preset the box grid from an already-emitted column's `(bottom, top)`
    /// span, so a throwaway fold over an OLDER trade window continues on
    /// the SAME grid as the live series instead of floor-snapping fresh
    /// off whichever price the older window happens to start at.
    ///
    /// Seeds a zero-volume, zero-trade placeholder "current column" with
    /// `open_time = 0` (never emitted on its own — the first real trade in
    /// the fold extends/reverses it in place, same as the live path's
    /// first-trade seed, just grid-anchored instead of floor-snapped).
    /// Must be called immediately after [`DerivedStream::new_for_key`],
    /// before feeding any events.
    pub(crate) fn preset_grid(&mut self, bottom: f64, top: f64, is_x: bool) {
        self.cur = Some(PnfColumnPoint {
            open_time: 0,
            column_id: 0,
            is_x,
            bottom,
            top,
            volume: 0.0,
            trades_count: 0,
        });
    }
}

impl DerivedStream for TradeToPnfBarDerived {
    type Output = PnfColumnPoint;

    fn deps() -> &'static [Stream] { &[] }

    fn deps_for_key(_key: &SeriesKey) -> Vec<Stream> {
        vec![Stream::Kline(KlineInterval::new("1m"))]
    }

    fn new_for_key(key: &SeriesKey) -> Self {
        let (box_size, reversal_count) = match &key.kind {
            Kind::PnfBar(b, r) if *b > 0 => (*b as f64 / 1e8, (*r).max(1)),
            _ => (0.0, 3),
        };
        Self {
            box_size,
            reversal_count,
            cur: None,
            next_column_id: 1,
            last_emitted_open_time: 0,
            kline_state: KlineDeltaState::new(),
        }
    }

    fn seed_kline_baseline(&mut self, open_time: i64, volume: f64, close: f64) {
        self.kline_state.seed_baseline(open_time, volume, close);
    }

    fn on_upstream_event(&mut self, ev: &Event, _dep_idx: usize) -> Option<PnfColumnPoint> {
        if self.box_size == 0.0 { return None; }
        match ev {
            Event::Trade { point, .. } => self.fold_trade(point),
            Event::Bar { point: bar, timeframe, exchange, symbol } => {
                let synth = self.kline_state.to_delta_trade(bar, timeframe, *exchange, symbol)?;
                let Event::Trade { point, .. } = &synth else { unreachable!("to_delta_trade always returns Event::Trade") };
                self.fold_trade(point)
            }
            _ => None,
        }
    }
}

impl TradeToPnfBarDerived {
    fn fold_trade(&mut self, point: &TradePoint) -> Option<PnfColumnPoint> {
        // Seed the first column from the first trade as an X column,
        // floor-snapped to the box grid.
        if self.cur.is_none() {
            let bottom = (point.price / self.box_size).floor() * self.box_size;
            let top = bottom + self.box_size;
            let open_time = point.ts_ms.max(self.last_emitted_open_time + 1);
            self.last_emitted_open_time = open_time;
            self.cur = Some(PnfColumnPoint {
                open_time,
                column_id: self.next_column_id,
                is_x: true,
                bottom,
                top,
                volume: point.quantity,
                trades_count: 1,
            });
            self.next_column_id += 1;
            return self.cur.clone();
        }

        let col = self.cur.as_mut().unwrap();
        col.volume += point.quantity;
        col.trades_count += 1;

        if col.is_x {
            // Extend up if price clears next box top.
            if point.price >= col.top + self.box_size {
                let steps = ((point.price - col.top) / self.box_size).floor() as i64;
                col.top += steps as f64 * self.box_size;
                return self.cur.clone();
            }
            // Reverse to O column if price drops `reversal × box_size` from top.
            if point.price <= col.top - self.box_size * self.reversal_count as f64 {
                // New O column starts one box below the prior X top.
                let new_top = col.top - self.box_size;
                let drop_steps = (((col.top - self.box_size) - point.price)
                    / self.box_size).floor() as i64 + 1;
                let new_bot = new_top - drop_steps.max(1) as f64 * self.box_size;
                let open_time = point.ts_ms.max(self.last_emitted_open_time + 1);
                self.last_emitted_open_time = open_time;
                self.cur = Some(PnfColumnPoint {
                    open_time,
                    column_id: self.next_column_id,
                    is_x: false,
                    bottom: new_bot,
                    top: new_top,
                    volume: 0.0,
                    trades_count: 0,
                });
                self.next_column_id += 1;
                return self.cur.clone();
            }
        } else {
            // Extend down if price clears next box bottom.
            if point.price <= col.bottom - self.box_size {
                let steps = ((col.bottom - point.price) / self.box_size).floor() as i64;
                col.bottom -= steps as f64 * self.box_size;
                return self.cur.clone();
            }
            // Reverse to X column if price rises `reversal × box_size` from bottom.
            if point.price >= col.bottom + self.box_size * self.reversal_count as f64 {
                let new_bot = col.bottom + self.box_size;
                let rise_steps = ((point.price - (col.bottom + self.box_size))
                    / self.box_size).floor() as i64 + 1;
                let new_top = new_bot + rise_steps.max(1) as f64 * self.box_size;
                let open_time = point.ts_ms.max(self.last_emitted_open_time + 1);
                self.last_emitted_open_time = open_time;
                self.cur = Some(PnfColumnPoint {
                    open_time,
                    column_id: self.next_column_id,
                    is_x: true,
                    bottom: new_bot,
                    top: new_top,
                    volume: 0.0,
                    trades_count: 0,
                });
                self.next_column_id += 1;
                return self.cur.clone();
            }
        }

        self.cur.clone()
    }
}

// ---------------------------------------------------------------------------
// TradeToKagiBarDerived
// ---------------------------------------------------------------------------

/// Aggregates `Trade` events into Kagi segments.
///
/// ## Segment semantics
///
/// `reversal` from `Kind::KagiBar(r)` stored as `r / 1e8`. Direction stays
/// the same as long as price keeps moving in it. A reversal of at least
/// `reversal` in price closes the current segment and opens a new one in
/// the opposite direction. Yang/yin thickness flips at the prior
/// shoulder (highest high) or waist (lowest low) — when a down segment
/// crosses *below* the prior waist it flips to yin (thin); when an up
/// segment crosses *above* the prior shoulder it flips to yang (thick).
///
/// ## Output (`KagiSegmentPoint`)
///
/// Two flavours:
/// 1. Vertical segment: `is_connector = false`, `start_price`,
///    `end_price`, `yang: bool`.
/// 2. Horizontal connector: `is_connector = true`, emitted at the close
///    of each segment (price = the segment's terminal price).
///
/// ## Disabled guard: `reversal == 0.0`.
pub(crate) struct TradeToKagiBarDerived {
    reversal: f64,
    /// Anchor price for the current direction.
    anchor: f64,
    /// True once the seed direction has been determined.
    seeded: bool,
    /// Current direction.
    up: bool,
    /// Last seen shoulder (highest high across closed segments).
    last_shoulder: f64,
    /// Last seen waist (lowest low across closed segments).
    last_waist: f64,
    last_emitted_open_time: i64,
    /// Live Δ-tick adapter over the `Stream::Kline("1m")` upstream — see
    /// [`KlineDeltaState`]. Kline-sufficient kind: no `Stream::Trade` dependency.
    kline_state: KlineDeltaState,
}

impl DerivedStream for TradeToKagiBarDerived {
    type Output = KagiSegmentPoint;

    fn deps() -> &'static [Stream] { &[] }

    fn deps_for_key(_key: &SeriesKey) -> Vec<Stream> {
        vec![Stream::Kline(KlineInterval::new("1m"))]
    }

    fn new_for_key(key: &SeriesKey) -> Self {
        let reversal = match &key.kind {
            Kind::KagiBar(r) if *r > 0 => *r as f64 / 1e8,
            _ => 0.0,
        };
        Self {
            reversal,
            anchor: 0.0,
            seeded: false,
            up: true,
            last_shoulder: f64::NEG_INFINITY,
            last_waist: f64::INFINITY,
            last_emitted_open_time: 0,
            kline_state: KlineDeltaState::new(),
        }
    }

    fn seed_kline_baseline(&mut self, open_time: i64, volume: f64, close: f64) {
        self.kline_state.seed_baseline(open_time, volume, close);
    }

    fn on_upstream_event(&mut self, ev: &Event, _dep_idx: usize) -> Option<KagiSegmentPoint> {
        if self.reversal == 0.0 { return None; }
        match ev {
            Event::Trade { point, .. } => self.fold_trade(point),
            Event::Bar { point: bar, timeframe, exchange, symbol } => {
                let synth = self.kline_state.to_delta_trade(bar, timeframe, *exchange, symbol)?;
                let Event::Trade { point, .. } = &synth else { unreachable!("to_delta_trade always returns Event::Trade") };
                self.fold_trade(point)
            }
            _ => None,
        }
    }
}

impl TradeToKagiBarDerived {
    fn fold_trade(&mut self, point: &TradePoint) -> Option<KagiSegmentPoint> {
        // Seed phase: wait for the first significant move ≥ reversal to
        // determine direction. Do NOT pre-assume up.
        if !self.seeded {
            if self.anchor == 0.0 {
                self.anchor = point.price;
                return None;
            }
            if (point.price - self.anchor).abs() >= self.reversal {
                self.up = point.price > self.anchor;
                if self.up { self.last_waist = self.anchor; }
                else { self.last_shoulder = self.anchor; }
                self.seeded = true;
                // Emit the seed segment.
                let open_time = point.ts_ms.max(self.last_emitted_open_time + 1);
                self.last_emitted_open_time = open_time;
                let prev_anchor = self.anchor;
                self.anchor = point.price;
                return Some(KagiSegmentPoint {
                    open_time,
                    start_price: prev_anchor,
                    end_price: point.price,
                    up: self.up,
                    yang: true,
                    is_connector: false,
                });
            }
            // Track anchor to most extreme yet-seen price so seed direction
            // is from the actual swing, not the first trade noise.
            if self.up && point.price > self.anchor { self.anchor = point.price; }
            if !self.up && point.price < self.anchor { self.anchor = point.price; }
            return None;
        }

        // Active phase.
        if self.up && point.price > self.anchor {
            self.anchor = point.price;
            return None;
        }
        if !self.up && point.price < self.anchor {
            self.anchor = point.price;
            return None;
        }

        // Candidate reversal: price moved opposite by ≥ reversal.
        let against = if self.up { self.anchor - point.price }
                      else { point.price - self.anchor };
        if against < self.reversal { return None; }

        // Close current segment.
        let yang = if self.up {
            // Up segment closing — yang determined by whether anchor cleared
            // the prior shoulder during this segment.
            self.anchor > self.last_shoulder
        } else {
            // Down segment closing — yang (thick) when anchor breached prior
            // waist (a "yin" flip in classical Kagi means the price made a
            // new LOW below the prior waist).
            self.anchor < self.last_waist
        };
        // Persist extremum.
        if self.up { self.last_shoulder = self.last_shoulder.max(self.anchor); }
        else { self.last_waist = self.last_waist.min(self.anchor); }

        let close_ts = point.ts_ms.max(self.last_emitted_open_time + 1);
        self.last_emitted_open_time = close_ts;
        let closed = KagiSegmentPoint {
            open_time: close_ts,
            start_price: if self.up { self.anchor - against - 0.0 } else { self.anchor + against - 0.0 },
            end_price: self.anchor,
            up: self.up,
            yang,
            is_connector: false,
        };
        // Flip direction; new anchor is the trade that triggered the flip.
        self.up = !self.up;
        self.anchor = point.price;

        Some(closed)
    }
}

// ---------------------------------------------------------------------------
// TradeToCvdLineDerived
// ---------------------------------------------------------------------------

/// Running Cumulative Volume Delta line — scalar series indexed by trade
/// timestamp. Each trade adds `+qty` if buyer-aggressor (side==0), `-qty`
/// otherwise.
///
/// Disabled when `key.kind != Kind::CvdLine` (always-on otherwise).
pub(crate) struct TradeToCvdLineDerived {
    enabled: bool,
    cvd: f64,
    last_emitted_ts: i64,
}

impl DerivedStream for TradeToCvdLineDerived {
    type Output = ScalarBarPoint;

    fn deps() -> &'static [Stream] { &[Stream::Trade] }

    fn new_for_key(key: &SeriesKey) -> Self {
        let enabled = matches!(key.kind, Kind::CvdLine);
        Self { enabled, cvd: 0.0, last_emitted_ts: 0 }
    }

    fn on_upstream_event(&mut self, ev: &Event, _dep_idx: usize) -> Option<ScalarBarPoint> {
        if !self.enabled { return None; }
        let Event::Trade { point, .. } = ev else { return None };

        let signed = if point.side == 0 { point.quantity } else { -point.quantity };
        self.cvd += signed;
        let ts_ms = point.ts_ms.max(self.last_emitted_ts + 1);
        self.last_emitted_ts = ts_ms;
        Some(ScalarBarPoint { ts_ms, value: self.cvd })
    }
}

// ---------------------------------------------------------------------------
// TPO — shared session-accumulator state
// ---------------------------------------------------------------------------

/// State machine shared between the two TPO derived flavours
/// (`TpoFromKline1mDerived` and `TpoFromTradeDerived`). The bucket
/// extension API is feed-source-agnostic — both flavours call
/// [`TpoSessionState::extend_bucket`] with `(ts_ms, high, low)` after
/// session-roll detection.
///
/// Maintains a ring of closed sessions alongside the current one.
/// `max_history_sessions` (default 10) caps the ring — approximately
/// two trading weeks of daily profiles. On session close, the final
/// snapshot is appended to `history` before the current session is
/// cleared. The oldest entry is evicted when the ring is full.
pub(crate) struct TpoSessionState {
    freq_minutes: u16,
    value_area_pct: f64,
    /// Current session's start (UTC midnight ms).
    session_date_ms: i64,
    /// Letter buckets: each bucket = freq_minutes window, recording
    /// (high, low) of the source events that fell in it.
    buckets: Vec<(f64, f64)>,
    /// Closes / mid-prices accumulated this session (for tick-size
    /// detection in the kline flavour, recent trade prices in the trade
    /// flavour).
    samples: Vec<f64>,
    /// Detected tick size for current session (0.0 = unset).
    tick_size: f64,
    /// Session-wide high/low.
    session_high: f64,
    session_low: f64,
    /// Ring of closed-session final snapshots, ordered oldest → newest.
    /// Capped at `max_history_sessions`.
    history: VecDeque<TpoSessionPoint>,
    /// Maximum number of closed sessions retained in `history`.
    max_history_sessions: usize,
}

impl TpoSessionState {
    fn new(freq_minutes: u16) -> Self {
        Self {
            freq_minutes,
            value_area_pct: 0.70,
            session_date_ms: 0,
            buckets: Vec::new(),
            samples: Vec::new(),
            tick_size: 0.0,
            session_high: f64::NEG_INFINITY,
            session_low: f64::INFINITY,
            history: VecDeque::new(),
            max_history_sessions: 10,
        }
    }

    fn day_start_ms(ts_ms: i64) -> i64 {
        const MS_PER_DAY: i64 = 86_400_000;
        (ts_ms / MS_PER_DAY) * MS_PER_DAY
    }

    fn bucket_idx(&self, ts_ms: i64) -> usize {
        let into_session_ms = ts_ms - self.session_date_ms;
        (into_session_ms / (self.freq_minutes as i64 * 60_000)).max(0) as usize
    }

    fn maybe_roll_session(&mut self, ts_ms: i64) {
        let bar_day = Self::day_start_ms(ts_ms);
        if bar_day != self.session_date_ms {
            // Snapshot the closing session before clearing, provided there
            // is meaningful data (at least one finite bucket).
            let has_data = self.buckets.iter().any(|(h, l)| h.is_finite() && l.is_finite());
            if has_data && self.session_date_ms != 0 {
                let closed = self.build_point();
                self.history.push_back(closed);
                if self.history.len() > self.max_history_sessions {
                    self.history.pop_front();
                }
            }
            self.session_date_ms = bar_day;
            self.buckets.clear();
            self.samples.clear();
            self.tick_size = 0.0;
            self.session_high = f64::NEG_INFINITY;
            self.session_low = f64::INFINITY;
        }
    }

    /// Feed one (ts_ms, high, low, price_sample) tuple into the current
    /// session. `price_sample` is used for tick-size auto-detection
    /// (kline mode: close; trade mode: trade price).
    fn extend_bucket(&mut self, ts_ms: i64, high: f64, low: f64, price_sample: f64) {
        self.maybe_roll_session(ts_ms);

        if high > self.session_high { self.session_high = high; }
        if low < self.session_low { self.session_low = low; }
        self.samples.push(price_sample);
        if self.tick_size == 0.0 && self.samples.len() >= 10 {
            self.tick_size = self.detect_tick_size();
        }

        let bi = self.bucket_idx(ts_ms);
        while self.buckets.len() <= bi {
            self.buckets.push((f64::NEG_INFINITY, f64::INFINITY));
        }
        let (bhigh, blow) = &mut self.buckets[bi];
        if high > *bhigh { *bhigh = high; }
        if low < *blow { *blow = low; }
    }

    fn detect_tick_size(&self) -> f64 {
        if self.samples.len() < 2 { return 0.0; }
        let mut min_step = f64::INFINITY;
        for w in self.samples.windows(2) {
            let d = (w[1] - w[0]).abs();
            if d > 0.0 && d < min_step { min_step = d; }
        }
        if min_step.is_finite() && min_step > 0.0 {
            min_step
        } else {
            ((self.session_high - self.session_low) / 200.0).max(0.01)
        }
    }

    fn build_point(&self) -> TpoSessionPoint {
        let alphabet: Vec<char> = ('A'..='Z').chain('a'..='z').collect();
        let tick = if self.tick_size > 0.0 {
            self.tick_size
        } else {
            ((self.session_high - self.session_low) / 200.0).max(0.01)
        };

        // Build the price-level → letters map.
        let n_rows = (((self.session_high - self.session_low) / tick).ceil() as usize + 1).max(1);
        let mut rows: Vec<(f64, Vec<char>)> = (0..n_rows)
            .map(|i| (self.session_low + i as f64 * tick, Vec::<char>::new()))
            .collect();

        for (bi, &(bhigh, blow)) in self.buckets.iter().enumerate() {
            if !bhigh.is_finite() || !blow.is_finite() { continue; }
            let letter = alphabet[bi % 52];
            for (price, letters) in rows.iter_mut() {
                if *price >= blow && *price < bhigh {
                    letters.push(letter);
                }
            }
        }

        // POC = row with most letters; tie → closest to midpoint.
        let max_count = rows.iter().map(|(_, l)| l.len()).max().unwrap_or(0);
        let mid = (self.session_high + self.session_low) * 0.5;
        let poc_price = rows.iter()
            .filter(|(_, l)| l.len() == max_count)
            .min_by(|(p1, _), (p2, _)| {
                (p1 - mid).abs().partial_cmp(&(p2 - mid).abs())
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
            .map(|(p, _)| *p)
            .unwrap_or(mid);

        // Value Area: greedy 70% expansion from POC.
        let total: usize = rows.iter().map(|(_, l)| l.len()).sum();
        let target = (total as f64 * self.value_area_pct).ceil() as usize;
        let poc_idx = rows.iter().position(|(p, _)| (*p - poc_price).abs() < tick * 0.5)
            .unwrap_or(rows.len() / 2);
        let mut acc = rows[poc_idx].1.len();
        let mut va_lo_idx = poc_idx;
        let mut va_hi_idx = poc_idx;
        while acc < target && (va_lo_idx > 0 || va_hi_idx + 1 < rows.len()) {
            let above_n = if va_hi_idx + 1 < rows.len() { rows[va_hi_idx + 1].1.len() } else { 0 };
            let below_n = if va_lo_idx > 0 { rows[va_lo_idx - 1].1.len() } else { 0 };
            if above_n >= below_n && va_hi_idx + 1 < rows.len() {
                va_hi_idx += 1;
                acc += above_n;
            } else if va_lo_idx > 0 {
                va_lo_idx -= 1;
                acc += below_n;
            } else if va_hi_idx + 1 < rows.len() {
                va_hi_idx += 1;
                acc += above_n;
            } else {
                break;
            }
        }
        let vah_price = rows[va_hi_idx].0;
        let val_price = rows[va_lo_idx].0;

        let row_letters: Vec<(f64, Vec<char>)> = rows.into_iter()
            .filter(|(_, l)| !l.is_empty())
            .collect();

        TpoSessionPoint {
            open_time: self.session_date_ms,
            tick_size: tick,
            session_high: self.session_high,
            session_low: self.session_low,
            poc_price,
            vah_price,
            val_price,
            rows: row_letters,
        }
    }
}

// ---------------------------------------------------------------------------
// TpoFromKline1mDerived  (canonical: sivamgr / py-market-profile)
// ---------------------------------------------------------------------------

/// TPO Market Profile aggregator sourced from 1-minute klines.
///
/// Subscribes to `Stream::Kline(1m)` and feeds each bar's `(high, low,
/// close)` into the shared [`TpoSessionState`]. Sessions roll on UTC
/// date change. Emits the current session's profile snapshot on every
/// incoming bar (live intraday view via Series upsert on
/// `open_time = session_date_ms`).
///
/// Subscribing to a specific `Stream::Kline(interval)` requires a
/// per-key dep set — see [`DerivedStream::deps_for_key`].
pub(crate) struct TpoFromKline1mDerived {
    state: TpoSessionState,
}

impl DerivedStream for TpoFromKline1mDerived {
    type Output = TpoSessionPoint;

    fn deps() -> &'static [Stream] { &[] }

    fn deps_for_key(_key: &SeriesKey) -> Vec<Stream> {
        vec![Stream::Kline(KlineInterval::new("1m"))]
    }

    fn new_for_key(key: &SeriesKey) -> Self {
        let freq_minutes = match &key.kind {
            Kind::TpoProfile(f, TpoSource::Kline1m) if *f > 0 => *f,
            _ => 30,
        };
        Self { state: TpoSessionState::new(freq_minutes) }
    }

    fn on_upstream_event(&mut self, ev: &Event, _dep_idx: usize) -> Option<TpoSessionPoint> {
        let Event::Bar { point, .. } = ev else { return None };
        self.state.extend_bucket(point.open_time, point.high, point.low, point.close);
        Some(self.state.build_point())
    }
}

// ---------------------------------------------------------------------------
// TpoFromTradeDerived  (live tick path, no kline backfill needed)
// ---------------------------------------------------------------------------

/// TPO Market Profile aggregator sourced directly from the live trade
/// stream. Subscribes to `Stream::Trade`. Each trade extends the
/// (high, low) of its letter-period bucket using the trade price as
/// both high and low (degenerate point — bucket extremes grow as more
/// trades arrive). Tick-size auto-detection samples raw trade prices.
///
/// Faster cold start (no need to wait for 1m bars to backfill) and
/// finer-grain bucket extremes than the kline path; trade-off is more
/// upstream events on high-volume symbols.
pub(crate) struct TpoFromTradeDerived {
    state: TpoSessionState,
}

impl DerivedStream for TpoFromTradeDerived {
    type Output = TpoSessionPoint;

    fn deps() -> &'static [Stream] { &[Stream::Trade] }

    fn new_for_key(key: &SeriesKey) -> Self {
        let freq_minutes = match &key.kind {
            Kind::TpoProfile(f, TpoSource::TradeBucket) if *f > 0 => *f,
            _ => 30,
        };
        Self { state: TpoSessionState::new(freq_minutes) }
    }

    fn on_upstream_event(&mut self, ev: &Event, _dep_idx: usize) -> Option<TpoSessionPoint> {
        let Event::Trade { point, .. } = ev else { return None };
        // A single trade is a degenerate `[price, price]` bar; the
        // bucket's high/low grow as subsequent trades arrive.
        self.state.extend_bucket(point.ts_ms, point.price, point.price, point.price);
        Some(self.state.build_point())
    }
}

// ---------------------------------------------------------------------------
// FundingSettlementDerived
// ---------------------------------------------------------------------------

/// Monitors the `FundingRate` stream (dep index 0) and emits a
/// `FundingSettlementPoint` each time the exchange's `next_funding_time`
/// boundary is crossed — i.e., the current wall clock has passed the
/// previously-declared settlement time AND the exchange has advanced its
/// `next_funding_time` pointer to a new period.
///
/// ## Crossing logic
///
/// Fires when BOTH:
/// 1. `point.ts_ms >= self.last_next_funding_time` — time has passed the
///    previously-seen boundary.
/// 2. `point.next_funding_time_ms != self.last_next_funding_time` — exchange
///    advanced its pointer, which only happens after the settlement window
///    closes on the exchange side.
///
/// `settled_rate` carries `self.last_rate` (the rate from the *previous*
/// event), not the new rate — the rate active *during* the settled period is
/// the one from before the boundary crossed.
///
/// ## Exchanges where `next_funding_time_ms == 0`
///
/// HyperLiquid, Deribit, dYdX do not emit a settlement time on the wire.
/// All their events pass through the `new_nft == 0` guard and are silently
/// absorbed. The derived stream idles for those venues.
pub(crate) struct FundingSettlementDerived {
    /// Last seen `next_funding_time_ms`. 0 = uninitialized.
    last_next_funding_time: i64,
    /// Funding rate carried from the previous event (the one active during the
    /// *just-settled* period).
    last_rate: f64,
}

impl DerivedStream for FundingSettlementDerived {
    type Output = FundingSettlementPoint;

    fn deps() -> &'static [Stream] {
        &[Stream::FundingRate]
    }

    fn new_for_key(_key: &SeriesKey) -> Self {
        Self {
            last_next_funding_time: 0,
            last_rate: 0.0,
        }
    }

    fn on_upstream_event(&mut self, ev: &Event, _dep_idx: usize) -> Option<FundingSettlementPoint> {
        let Event::FundingRate { point, .. } = ev else { return None };

        let new_nft  = point.next_funding_time_ms;
        let new_rate = point.rate;
        let now_ms   = point.ts_ms;

        // Guard: no settlement time available on this wire frame.
        if new_nft == 0 {
            self.last_rate = new_rate;
            return None;
        }

        // First event: initialize state, no emission.
        if self.last_next_funding_time == 0 {
            self.last_next_funding_time = new_nft;
            self.last_rate = new_rate;
            return None;
        }

        // Crossing condition: time passed boundary AND boundary advanced.
        let output = if now_ms >= self.last_next_funding_time
            && new_nft != self.last_next_funding_time
        {
            Some(FundingSettlementPoint {
                ts_ms:           now_ms,
                settled_rate:    self.last_rate,
                settlement_time: self.last_next_funding_time,
            })
        } else {
            None
        };

        // Always advance state.
        self.last_next_funding_time = new_nft;
        self.last_rate = new_rate;

        output
    }
}

// ---------------------------------------------------------------------------
// Suppress unused-import warnings for the concrete point types used above
// ---------------------------------------------------------------------------
// These are consumed via Event destructuring in the impls; the compiler
// may flag them as unused if it doesn't see direct type mentions.
const _: fn() = || {
    let _ = std::mem::size_of::<MarkPricePoint>();
    let _ = std::mem::size_of::<IndexPricePoint>();
    let _ = std::mem::size_of::<FundingRatePoint>();
    let _ = std::mem::size_of::<TradePoint>();
    let _ = std::mem::size_of::<BarPoint>();
    let _ = std::mem::size_of::<FootprintPoint>();
};

// ---------------------------------------------------------------------------
// TradeToDollarBarDerived
// ---------------------------------------------------------------------------

/// Aggregates `Trade` events into Dollar Bars (López de Prado, AFML ch.2).
///
/// ## Bar semantics
///
/// A bar closes when the running sum of `trade.price * trade.quantity` (dollar
/// value) since the last close ≥ `dollar_threshold`. The crossing trade is
/// included in the closing bar (no dollar carry-over to the next bar).
///
/// ## EMA not required
///
/// Dollar bars use a fixed threshold (unlike imbalance / run bars). No EMA
/// warm-up needed — the first bar closes as soon as `Σ(price×qty) ≥ threshold`.
///
/// ## Monotonic `open_time`
///
/// Same scheme as [`TradeToRangeBarDerived`].
///
/// ## Disabled guard
///
/// `threshold == 0.0` ⇒ always `None`.
pub(crate) struct TradeToDollarBarDerived {
    /// Dollar threshold in native units (`dollar_threshold` as f64). `0.0` = disabled.
    threshold: f64,
    /// Accumulated dollar value in the current bar.
    cumulative_dollars: f64,
    /// Currently-open bar, if any.
    current: Option<BarPoint>,
    /// See [`TradeToRangeBarDerived`] doc.
    last_emitted_open_time: i64,
    /// Live Δ-tick adapter over the `Stream::Kline("1m")` upstream — see
    /// [`KlineDeltaState`]. Kline-sufficient kind: no `Stream::Trade` dependency.
    kline_state: KlineDeltaState,
}

impl DerivedStream for TradeToDollarBarDerived {
    type Output = BarPoint;

    fn deps() -> &'static [Stream] { &[] }

    fn deps_for_key(_key: &SeriesKey) -> Vec<Stream> {
        vec![Stream::Kline(KlineInterval::new("1m"))]
    }

    fn new_for_key(key: &SeriesKey) -> Self {
        let threshold = match &key.kind {
            Kind::DollarBar { dollar_threshold } if *dollar_threshold > 0 => *dollar_threshold as f64,
            _ => 0.0,
        };
        Self { threshold, cumulative_dollars: 0.0, current: None, last_emitted_open_time: 0, kline_state: KlineDeltaState::new() }
    }

    fn seed_kline_baseline(&mut self, open_time: i64, volume: f64, close: f64) {
        self.kline_state.seed_baseline(open_time, volume, close);
    }

    fn on_upstream_event(&mut self, ev: &Event, _dep_idx: usize) -> Option<BarPoint> {
        if self.threshold == 0.0 { return None; }
        match ev {
            Event::Trade { point, .. } => self.fold_trade(point),
            Event::Bar { point: bar, timeframe, exchange, symbol } => {
                let synth = self.kline_state.to_delta_trade(bar, timeframe, *exchange, symbol)?;
                let Event::Trade { point, .. } = &synth else { unreachable!("to_delta_trade always returns Event::Trade") };
                self.fold_trade(point)
            }
            _ => None,
        }
    }
}

impl TradeToDollarBarDerived {
    fn fold_trade(&mut self, point: &TradePoint) -> Option<BarPoint> {
        // Open bar if none.
        if self.current.is_none() {
            let open_time = point.ts_ms.max(self.last_emitted_open_time + 1);
            self.last_emitted_open_time = open_time;
            self.current = Some(BarPoint {
                open_time,
                open:        point.price,
                high:        point.price,
                low:         point.price,
                close:       point.price,
                volume:      point.quantity,
                quote_volume: point.price * point.quantity,
                trades_count: 1,
            });
            self.cumulative_dollars = point.price * point.quantity;
        } else {
            let bar = self.current.as_mut()?;
            if point.price > bar.high  { bar.high  = point.price; }
            if point.price < bar.low   { bar.low   = point.price; }
            bar.close        = point.price;
            bar.volume       += point.quantity;
            bar.quote_volume += point.price * point.quantity;
            bar.trades_count += 1;
            self.cumulative_dollars += point.price * point.quantity;
        }

        let bar = self.current.clone()?;

        // Close bar when cumulative dollar value crosses threshold.
        if self.cumulative_dollars >= self.threshold {
            self.current = None;
            self.cumulative_dollars = 0.0;
        }

        Some(bar)
    }
}

// ---------------------------------------------------------------------------
// TradeToTickImbalanceDerived
// ---------------------------------------------------------------------------

/// Aggregates `Trade` events into Tick Imbalance Bars (López de Prado, AFML ch.2).
///
/// ## Algorithm
///
/// Running imbalance: `θ = Σ b_t` where `b_t = +1` for buyer-initiated trades
/// (side=0) and `-1` for seller-initiated trades (side=1).
///
/// Bar closes when `|θ| ≥ E[|θ|] × E[T]`.
///
/// `E[T]` and `E[|θ|]` are updated via EMA after each bar closes:
/// - `E[T] = alpha * T_prev + (1 - alpha) * E[T]` (tick count per bar)
/// - `E[|θ|] = alpha * |θ_prev| + (1 - alpha) * E[|θ|]`
///
/// ## EMA seed
///
/// Initial `E[T] = min_ticks as f64`, `E[|θ|] = min_ticks as f64 * 0.5`.
/// With `alpha=0.20`, this means the first few bars will close at roughly
/// `min_ticks * 0.5` imbalance — a reasonable warm-up floor.
///
/// ## Disabled guard
///
/// `min_ticks == 0` ⇒ always `None`.
pub(crate) struct TradeToTickImbalanceDerived {
    /// EMA smoothing factor. `0.0` ⇒ disabled.
    alpha: f64,
    /// Sanity floor tick count (also used as EMA seed).
    min_ticks: u32,
    /// Running tick imbalance for the current bar.
    theta: f64,
    /// Number of ticks accumulated in the current bar.
    tick_count: u32,
    /// EMA of `|theta|` at bar close (updated after each closed bar).
    expected_theta_abs: f64,
    /// EMA of tick count per bar (updated after each closed bar).
    expected_ticks: f64,
    /// Currently-open bar, if any.
    current: Option<BarPoint>,
    /// See [`TradeToRangeBarDerived`] doc.
    last_emitted_open_time: i64,
}

impl TradeToTickImbalanceDerived {
    /// Dynamic close threshold: `E[|θ|] × E[T]`, floored at `min_ticks / 2`.
    fn close_threshold(&self) -> f64 {
        let dyn_threshold = self.expected_theta_abs * self.expected_ticks;
        dyn_threshold.max(self.min_ticks as f64 * 0.5)
    }
}

impl DerivedStream for TradeToTickImbalanceDerived {
    type Output = BarPoint;

    fn deps() -> &'static [Stream] { &[Stream::Trade] }

    fn new_for_key(key: &SeriesKey) -> Self {
        let (alpha, min_ticks) = match &key.kind {
            Kind::TickImbalanceBar { alpha_x100, min_ticks } if *min_ticks > 0 => {
                (*alpha_x100 as f64 / 100.0, *min_ticks)
            }
            _ => (0.0, 0),
        };
        // EMA seed: E[T] = min_ticks, E[|θ|] = min_ticks × 0.5 so the first
        // bar closes at roughly min_ticks/2 ticks of net imbalance.
        let expected_ticks = min_ticks as f64;
        let expected_theta_abs = min_ticks as f64 * 0.5;
        Self {
            alpha, min_ticks, theta: 0.0, tick_count: 0,
            expected_theta_abs, expected_ticks,
            current: None, last_emitted_open_time: 0,
        }
    }

    fn on_upstream_event(&mut self, ev: &Event, _dep_idx: usize) -> Option<BarPoint> {
        if self.alpha == 0.0 || self.min_ticks == 0 { return None; }
        let Event::Trade { point, .. } = ev else { return None };

        // b_t: side=0 (Buy) → +1, side=1 (Sell) → -1.
        let bt = if point.side == 0 { 1.0f64 } else { -1.0f64 };

        // Open bar if none.
        if self.current.is_none() {
            let open_time = point.ts_ms.max(self.last_emitted_open_time + 1);
            self.last_emitted_open_time = open_time;
            self.current = Some(BarPoint {
                open_time,
                open:        point.price,
                high:        point.price,
                low:         point.price,
                close:       point.price,
                volume:      point.quantity,
                quote_volume: point.price * point.quantity,
                trades_count: 1,
            });
            self.theta = bt;
            self.tick_count = 1;
        } else {
            let bar = self.current.as_mut()?;
            if point.price > bar.high  { bar.high  = point.price; }
            if point.price < bar.low   { bar.low   = point.price; }
            bar.close        = point.price;
            bar.volume       += point.quantity;
            bar.quote_volume += point.price * point.quantity;
            bar.trades_count += 1;
            self.theta += bt;
            self.tick_count += 1;
        }

        let bar = self.current.clone()?;

        // Close bar when |θ| ≥ threshold.
        if self.theta.abs() >= self.close_threshold() {
            // Update EMAs from the closed bar.
            let t = self.tick_count as f64;
            let theta_abs = self.theta.abs();
            self.expected_ticks = self.alpha * t + (1.0 - self.alpha) * self.expected_ticks;
            self.expected_theta_abs = self.alpha * theta_abs + (1.0 - self.alpha) * self.expected_theta_abs;
            // Reset bar state.
            self.current = None;
            self.theta = 0.0;
            self.tick_count = 0;
        }

        Some(bar)
    }
}

// ---------------------------------------------------------------------------
// TradeToVolumeImbalanceDerived
// ---------------------------------------------------------------------------

/// Aggregates `Trade` events into Volume Imbalance Bars (López de Prado, AFML ch.2).
///
/// ## Algorithm
///
/// Same as [`TradeToTickImbalanceDerived`] but uses signed volume instead of unit ticks:
/// `θ = Σ b_t × trade.quantity` where `b_t = +1` for buyer-initiated, `-1` for seller.
///
/// Bar closes when `|θ| ≥ E[|θ|] × E[T]`.
///
/// ## EMA seed
///
/// Same convention as [`TradeToTickImbalanceDerived`].
pub(crate) struct TradeToVolumeImbalanceDerived {
    alpha: f64,
    min_ticks: u32,
    /// Running signed-volume imbalance for the current bar.
    theta: f64,
    tick_count: u32,
    expected_theta_abs: f64,
    expected_ticks: f64,
    current: Option<BarPoint>,
    last_emitted_open_time: i64,
}

impl TradeToVolumeImbalanceDerived {
    fn close_threshold(&self) -> f64 {
        let dyn_threshold = self.expected_theta_abs * self.expected_ticks;
        dyn_threshold.max(self.min_ticks as f64 * 0.5)
    }
}

impl DerivedStream for TradeToVolumeImbalanceDerived {
    type Output = BarPoint;

    fn deps() -> &'static [Stream] { &[Stream::Trade] }

    fn new_for_key(key: &SeriesKey) -> Self {
        let (alpha, min_ticks) = match &key.kind {
            Kind::VolumeImbalanceBar { alpha_x100, min_ticks } if *min_ticks > 0 => {
                (*alpha_x100 as f64 / 100.0, *min_ticks)
            }
            _ => (0.0, 0),
        };
        let expected_ticks = min_ticks as f64;
        // EMA seed for signed-volume: assume average trade size ≈ 1.0, so
        // E[|θ|] seed = min_ticks * 0.5 × 1.0 = min_ticks * 0.5.
        let expected_theta_abs = min_ticks as f64 * 0.5;
        Self {
            alpha, min_ticks, theta: 0.0, tick_count: 0,
            expected_theta_abs, expected_ticks,
            current: None, last_emitted_open_time: 0,
        }
    }

    fn on_upstream_event(&mut self, ev: &Event, _dep_idx: usize) -> Option<BarPoint> {
        if self.alpha == 0.0 || self.min_ticks == 0 { return None; }
        let Event::Trade { point, .. } = ev else { return None };

        let bt_vol = if point.side == 0 { point.quantity } else { -point.quantity };

        if self.current.is_none() {
            let open_time = point.ts_ms.max(self.last_emitted_open_time + 1);
            self.last_emitted_open_time = open_time;
            self.current = Some(BarPoint {
                open_time,
                open:        point.price,
                high:        point.price,
                low:         point.price,
                close:       point.price,
                volume:      point.quantity,
                quote_volume: point.price * point.quantity,
                trades_count: 1,
            });
            self.theta = bt_vol;
            self.tick_count = 1;
        } else {
            let bar = self.current.as_mut()?;
            if point.price > bar.high  { bar.high  = point.price; }
            if point.price < bar.low   { bar.low   = point.price; }
            bar.close        = point.price;
            bar.volume       += point.quantity;
            bar.quote_volume += point.price * point.quantity;
            bar.trades_count += 1;
            self.theta += bt_vol;
            self.tick_count += 1;
        }

        let bar = self.current.clone()?;

        if self.theta.abs() >= self.close_threshold() {
            let t = self.tick_count as f64;
            let theta_abs = self.theta.abs();
            self.expected_ticks = self.alpha * t + (1.0 - self.alpha) * self.expected_ticks;
            self.expected_theta_abs = self.alpha * theta_abs + (1.0 - self.alpha) * self.expected_theta_abs;
            self.current = None;
            self.theta = 0.0;
            self.tick_count = 0;
        }

        Some(bar)
    }
}

// ---------------------------------------------------------------------------
// TradeToRunBarDerived
// ---------------------------------------------------------------------------

/// Aggregates `Trade` events into Run Bars (López de Prado, AFML ch.2).
///
/// ## Algorithm
///
/// Track the length of consecutive buy-runs and sell-runs. A run is the longest
/// streak of same-side ticks at the current bar boundary:
/// - When `side == 0` (Buy) and the last side was also Buy → increment `run_buy_len`.
/// - When `side == 1` (Sell) and the last side was also Sell → increment `run_sell_len`.
/// - On a side flip → reset the opposite run to 0.
///
/// Bar closes when `max(run_buy_len, run_sell_len) ≥ E[run] × E[T]`.
///
/// `E[run]` and `E[T]` are updated via EMA after each bar closes.
///
/// ## EMA seed
///
/// `E[T] = min_ticks`, `E[run] = min_ticks × 0.25` (a run is expected to be
/// about 1/4 of the bar's tick count on a balanced market).
///
/// ## Disabled guard
///
/// `min_ticks == 0` ⇒ always `None`.
pub(crate) struct TradeToRunBarDerived {
    alpha: f64,
    min_ticks: u32,
    /// Length of the current buy run (consecutive buy ticks).
    run_buy_len: u32,
    /// Length of the current sell run (consecutive sell ticks).
    run_sell_len: u32,
    /// Side of the last trade processed (0 = Buy, 1 = Sell, u8::MAX = none).
    last_side: u8,
    /// EMA of `max(run_buy, run_sell)` at bar close.
    expected_run: f64,
    /// EMA of tick count per bar.
    expected_ticks: f64,
    /// Number of ticks in the current bar.
    tick_count: u32,
    current: Option<BarPoint>,
    last_emitted_open_time: i64,
}

impl TradeToRunBarDerived {
    fn close_threshold(&self) -> f64 {
        let dyn_threshold = self.expected_run * self.expected_ticks;
        // Floor: at least 2 ticks of run length.
        dyn_threshold.max(2.0)
    }
}

impl DerivedStream for TradeToRunBarDerived {
    type Output = BarPoint;

    fn deps() -> &'static [Stream] { &[Stream::Trade] }

    fn new_for_key(key: &SeriesKey) -> Self {
        let (alpha, min_ticks) = match &key.kind {
            Kind::RunBar { alpha_x100, min_ticks } if *min_ticks > 0 => {
                (*alpha_x100 as f64 / 100.0, *min_ticks)
            }
            _ => (0.0, 0),
        };
        let expected_ticks = min_ticks as f64;
        // EMA seed: expected run ≈ 25% of bar tick count on a balanced market.
        let expected_run = min_ticks as f64 * 0.25;
        Self {
            alpha, min_ticks, run_buy_len: 0, run_sell_len: 0, last_side: u8::MAX,
            expected_run, expected_ticks, tick_count: 0,
            current: None, last_emitted_open_time: 0,
        }
    }

    fn on_upstream_event(&mut self, ev: &Event, _dep_idx: usize) -> Option<BarPoint> {
        if self.alpha == 0.0 || self.min_ticks == 0 { return None; }
        let Event::Trade { point, .. } = ev else { return None };

        // Update run lengths.
        if point.side == 0 {
            // Buy tick.
            if self.last_side == 0 {
                self.run_buy_len = self.run_buy_len.saturating_add(1);
            } else {
                self.run_buy_len = 1;
                self.run_sell_len = 0;
            }
        } else {
            // Sell tick.
            if self.last_side == 1 {
                self.run_sell_len = self.run_sell_len.saturating_add(1);
            } else {
                self.run_sell_len = 1;
                self.run_buy_len = 0;
            }
        }
        self.last_side = point.side;

        // Open bar if none.
        if self.current.is_none() {
            let open_time = point.ts_ms.max(self.last_emitted_open_time + 1);
            self.last_emitted_open_time = open_time;
            self.current = Some(BarPoint {
                open_time,
                open:        point.price,
                high:        point.price,
                low:         point.price,
                close:       point.price,
                volume:      point.quantity,
                quote_volume: point.price * point.quantity,
                trades_count: 1,
            });
            self.tick_count = 1;
        } else {
            let bar = self.current.as_mut()?;
            if point.price > bar.high  { bar.high  = point.price; }
            if point.price < bar.low   { bar.low   = point.price; }
            bar.close        = point.price;
            bar.volume       += point.quantity;
            bar.quote_volume += point.price * point.quantity;
            bar.trades_count += 1;
            self.tick_count += 1;
        }

        let bar = self.current.clone()?;

        let max_run = self.run_buy_len.max(self.run_sell_len) as f64;
        if max_run >= self.close_threshold() {
            let t = self.tick_count as f64;
            self.expected_ticks = self.alpha * t + (1.0 - self.alpha) * self.expected_ticks;
            self.expected_run = self.alpha * max_run + (1.0 - self.alpha) * self.expected_run;
            // Reset bar state but NOT run lengths — runs carry across bar boundaries.
            self.current = None;
            self.tick_count = 0;
        }

        Some(bar)
    }
}

// ---------------------------------------------------------------------------
// TradeToThreeLineBreakDerived
// ---------------------------------------------------------------------------

/// Aggregates `Trade` events into Three Line Break (san-sen-ashi) lines.
///
/// ## Algorithm (Steve Nison, "Beyond Candlesticks" ch. 6)
///
/// State tracks the last `lines_back` (default 3) closed lines. Each trade
/// updates the "pending" close price and tries to emit a new line:
///
/// * No lines yet — the first line is printed as soon as the close differs
///   from the seed open (up if `close > open`, down if `close < open`).
/// * Current direction **up** (last line is up):
///   - New UP line if `close > max(close of last N lines)`.
///   - Reversal (DOWN line) if `close < min(low of last N lines)` where
///     `low = min(open, close)` per line.
/// * Symmetric for **down**.
///
/// ## Output (`ThreeLineBreakLinePoint`)
///
/// `open` = previous line's close (or seed open for the very first line).
/// `close` = trade price that triggered the line.
/// `high = max(open, close)`, `low = min(open, close)` (no wicks by
/// construction — the algorithm only uses closes for line boundaries).
/// `direction`: 0 = up, 1 = down.
/// `volume`: cumulative trade quantity during the line.
///
/// ## Disabled guard
///
/// `lines_back == 0` ⇒ always `None`.
pub(crate) struct TradeToThreeLineBreakDerived {
    /// How many recent lines to compare against for breakout / reversal.
    lines_back: usize,
    /// Ring of the last `lines_back` closed lines.
    last_lines: std::collections::VecDeque<ThreeLineBreakLinePoint>,
    /// Open price of the line currently forming. `None` until first trade.
    current_open: Option<f64>,
    /// Timestamp of the trade that set `current_open`.
    current_open_ts: i64,
    /// Running close price — updated every trade.
    current_close: f64,
    /// Volume accumulator for the in-progress line.
    current_volume: f64,
    /// Monotonic open_ts guard (same scheme as range/tick bars).
    last_emitted_open_ts: i64,
    /// Live Δ-tick adapter over the `Stream::Kline("1m")` upstream — see
    /// [`KlineDeltaState`]. Kline-sufficient kind: no `Stream::Trade` dependency.
    kline_state: KlineDeltaState,
}

impl TradeToThreeLineBreakDerived {
    /// Emit a line and update state.
    ///
    /// Returns the closed `ThreeLineBreakLinePoint`.
    fn emit_line(&mut self, direction: u8, ts_close: i64) -> ThreeLineBreakLinePoint {
        let open = self.current_open.unwrap_or(self.current_close);
        let close = self.current_close;
        let ts_open = self.current_open_ts.max(self.last_emitted_open_ts + 1);
        self.last_emitted_open_ts = ts_open;

        let point = ThreeLineBreakLinePoint {
            ts_open,
            ts_close,
            open,
            close,
            volume: self.current_volume,
            direction,
        };

        // Push to ring; evict oldest if at capacity.
        self.last_lines.push_back(point.clone());
        if self.last_lines.len() > self.lines_back {
            self.last_lines.pop_front();
        }

        // Next line opens from this line's close.
        self.current_open = Some(close);
        self.current_open_ts = ts_close;
        self.current_volume = 0.0;

        point
    }
}

impl DerivedStream for TradeToThreeLineBreakDerived {
    type Output = ThreeLineBreakLinePoint;

    fn deps() -> &'static [Stream] {
        &[]
    }

    fn deps_for_key(_key: &SeriesKey) -> Vec<Stream> {
        vec![Stream::Kline(KlineInterval::new("1m"))]
    }

    fn new_for_key(key: &SeriesKey) -> Self {
        let lines_back = match &key.kind {
            Kind::ThreeLineBreak { lines_back } if *lines_back > 0 => *lines_back as usize,
            _ => 3,
        };
        Self {
            lines_back,
            last_lines: std::collections::VecDeque::with_capacity(lines_back + 1),
            current_open: None,
            current_open_ts: 0,
            current_close: 0.0,
            current_volume: 0.0,
            last_emitted_open_ts: 0,
            kline_state: KlineDeltaState::new(),
        }
    }

    fn seed_kline_baseline(&mut self, open_time: i64, volume: f64, close: f64) {
        self.kline_state.seed_baseline(open_time, volume, close);
    }

    fn on_upstream_event(
        &mut self,
        ev: &Event,
        _dep_idx: usize,
    ) -> Option<ThreeLineBreakLinePoint> {
        if self.lines_back == 0 {
            return None;
        }
        match ev {
            Event::Trade { point, .. } => self.fold_trade(point),
            Event::Bar { point: bar, timeframe, exchange, symbol } => {
                let synth = self.kline_state.to_delta_trade(bar, timeframe, *exchange, symbol)?;
                let Event::Trade { point, .. } = &synth else { unreachable!("to_delta_trade always returns Event::Trade") };
                self.fold_trade(point)
            }
            _ => None,
        }
    }
}

impl TradeToThreeLineBreakDerived {
    fn fold_trade(&mut self, point: &TradePoint) -> Option<ThreeLineBreakLinePoint> {
        // Seed: record the very first trade as current open.
        if self.current_open.is_none() {
            self.current_open = Some(point.price);
            self.current_open_ts = point.ts_ms;
            self.current_close = point.price;
            self.current_volume += point.quantity;
            return None;
        }

        self.current_close = point.price;
        self.current_volume += point.quantity;

        // First line — no prior lines yet.
        if self.last_lines.is_empty() {
            let seed_open = self.current_open.unwrap_or(self.current_close);
            if (self.current_close - seed_open).abs() < f64::EPSILON {
                return None; // price hasn't moved yet
            }
            let direction = if self.current_close > seed_open { 0u8 } else { 1u8 };
            return Some(self.emit_line(direction, point.ts_ms));
        }

        // Compute the high and low of the last N lines.
        // high of a line = max(open, close); low = min(open, close).
        let max_high = self
            .last_lines
            .iter()
            .map(|l| l.open.max(l.close))
            .fold(f64::NEG_INFINITY, f64::max);
        let min_low = self
            .last_lines
            .iter()
            .map(|l| l.open.min(l.close))
            .fold(f64::INFINITY, f64::min);

        let last_dir = self.last_lines.back().map(|l| l.direction).unwrap_or(0);

        match last_dir {
            // Last line was UP → look for continuation up or reversal down.
            0 => {
                if self.current_close > max_high {
                    return Some(self.emit_line(0, point.ts_ms));
                }
                if self.current_close < min_low {
                    return Some(self.emit_line(1, point.ts_ms));
                }
            }
            // Last line was DOWN → look for continuation down or reversal up.
            _ => {
                if self.current_close < min_low {
                    return Some(self.emit_line(1, point.ts_ms));
                }
                if self.current_close > max_high {
                    return Some(self.emit_line(0, point.ts_ms));
                }
            }
        }

        None
    }
}

// ---------------------------------------------------------------------------
// Kline-approx synthetic trade path (deep seed for price-path-triggered
// derived kinds: Renko / PnF / Kagi / Three-Line-Break)
// ---------------------------------------------------------------------------

/// Convert one 1m kline bar into up to 4 synthetic `Event::Trade`s tracing
/// the bar's O→H→L→C price path, for feeding into a price-path-triggered
/// derived state machine (`TradeToRenkoBarDerived` / `TradeToPnfBarDerived` /
/// `TradeToKagiBarDerived` / `TradeToThreeLineBreakDerived`) as a lossy-but-
/// honest approximation of the real tick path from weeks-old history (which
/// aggTrades cannot cover at that depth — see design doc "Seed strategy per
/// kind").
///
/// Path rule (non-standard-bars-spec):
/// - Bullish (`close >= open`): Open → Low → High → Close.
/// - Bearish (`close < open`): Open → High → Low → Close.
/// - 4 timestamps evenly spaced across `[open_time, open_time + interval_ms)`.
/// - Volume split evenly across the 4 synthetic legs (`bar.volume / 4`).
/// - `side` is a best-effort direction guess (0 = buy on rising leg, 1 = sell
///   on falling leg) — price-path derived kinds don't consume `side`, so
///   this is cosmetic only.
///
/// Returns exactly 4 events (interval_ms > 0), or an empty Vec if
/// `interval_ms <= 0` (malformed caller input — never happens for the "1m"
/// caller in `station.rs`, guarded defensively here).
pub(crate) fn kline_to_synthetic_trades(
    bar: &BarPoint,
    interval_ms: i64,
    exchange: digdigdig3::core::types::ExchangeId,
    symbol: &str,
) -> Vec<Event> {
    if interval_ms <= 0 {
        return Vec::new();
    }
    let bullish = bar.close >= bar.open;
    let path: [f64; 4] = if bullish {
        [bar.open, bar.low, bar.high, bar.close]
    } else {
        [bar.open, bar.high, bar.low, bar.close]
    };
    let leg_volume = bar.volume / 4.0;
    let step_ms = interval_ms / 4;

    (0..4)
        .map(|i| {
            let price = path[i];
            let side = if i == 0 {
                u8::from(!bullish)
            } else {
                u8::from(path[i] < path[i - 1])
            };
            Event::Trade {
                exchange,
                symbol: symbol.to_string(),
                point: TradePoint {
                    ts_ms: bar.open_time + step_ms * i as i64,
                    price,
                    quantity: leg_volume,
                    side,
                    trade_id_hash: 0,
                },
            }
        })
        .collect()
}

// ---------------------------------------------------------------------------
// Unit tests (inside module — need access to pub(crate) types)
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use digdigdig3::core::types::ExchangeId;
    use digdigdig3::core::types::AccountType;
    use digdigdig3::core::websocket::KlineInterval;

    // Helper constructors for Event variants.
    fn mark_price_event(ts_ms: i64, mark: f64) -> Event {
        Event::MarkPrice {
            exchange: ExchangeId::Binance,
            symbol: "BTCUSDT".to_string(),
            point: MarkPricePoint { ts_ms, mark, index: f64::NAN },
        }
    }

    fn index_price_event(ts_ms: i64, price: f64) -> Event {
        Event::IndexPrice {
            exchange: ExchangeId::Binance,
            symbol: "BTCUSDT".to_string(),
            point: IndexPricePoint { ts_ms, price },
        }
    }

    fn funding_rate_event(ts_ms: i64, rate: f64, next_funding_time_ms: i64) -> Event {
        Event::FundingRate {
            exchange: ExchangeId::Binance,
            symbol: "BTCUSDT".to_string(),
            point: FundingRatePoint { ts_ms, rate, next_funding_time_ms },
        }
    }

    fn test_key() -> SeriesKey {
        SeriesKey::new(ExchangeId::Binance, AccountType::FuturesCross, "BTCUSDT", crate::series::Kind::Basis)
    }

    // --- BasisDerived ---

    #[test]
    fn basis_no_emit_until_both_sides_seen() {
        let mut d = BasisDerived::new_for_key(&test_key());
        // Only mark — no emit.
        let r = d.on_upstream_event(&mark_price_event(1000, 50_000.0), 0);
        assert!(r.is_none(), "MarkPrice alone must not emit");
        // Only index — no emit (mark cached, but this is dep_idx=1 first call).
        let mut d2 = BasisDerived::new_for_key(&test_key());
        let r2 = d2.on_upstream_event(&index_price_event(1000, 49_990.0), 1);
        assert!(r2.is_none(), "IndexPrice alone must not emit");
    }

    #[test]
    fn basis_emits_on_paired_events() {
        let mut d = BasisDerived::new_for_key(&test_key());
        let r1 = d.on_upstream_event(&mark_price_event(1000, 50_000.0), 0);
        assert!(r1.is_none());
        let r2 = d.on_upstream_event(&index_price_event(1200, 49_990.0), 1);
        let p = r2.expect("should emit after both sides seen");
        assert!((p.value - 10.0).abs() < 1e-9, "value = mark - index = 10.0");
        assert_eq!(p.mark, 50_000.0);
        assert_eq!(p.index, 49_990.0);
        assert_eq!(p.ts_ms, 1200); // max(1000, 1200)
    }

    #[test]
    fn basis_skew_rejection() {
        let mut d = BasisDerived::new_for_key(&test_key());
        d.on_upstream_event(&mark_price_event(0, 50_000.0), 0);
        // Index arrives 3 seconds later — skew > 2000 ms.
        let r = d.on_upstream_event(&index_price_event(3000, 49_990.0), 1);
        assert!(r.is_none(), "stale pair must be rejected (skew > 2000 ms)");
    }

    #[test]
    fn basis_emits_on_each_update_once_seeded() {
        let mut d = BasisDerived::new_for_key(&test_key());
        d.on_upstream_event(&mark_price_event(1000, 50_000.0), 0);
        d.on_upstream_event(&index_price_event(1001, 49_990.0), 1);
        // Third event — MarkPrice update within skew.
        let r = d.on_upstream_event(&mark_price_event(1002, 50_010.0), 0);
        let p = r.expect("should emit after update when both seeded");
        assert!((p.value - 20.0).abs() < 1e-9, "updated mark=50010, index=49990 → 20.0");
    }

    #[test]
    fn basis_value_correct() {
        let mut d = BasisDerived::new_for_key(&test_key());
        d.on_upstream_event(&mark_price_event(100, 50_000.0), 0);
        let p = d.on_upstream_event(&index_price_event(100, 49_990.0), 1).unwrap();
        assert!((p.value - 10.0).abs() < 1e-9);
        assert_eq!(p.mark, 50_000.0);
        assert_eq!(p.index, 49_990.0);
    }

    // --- FundingSettlementDerived ---

    fn fs_key() -> SeriesKey {
        SeriesKey::new(ExchangeId::Binance, AccountType::FuturesCross, "BTCUSDT", crate::series::Kind::FundingSettlement)
    }

    #[test]
    fn settlement_no_emit_on_first_event() {
        let mut d = FundingSettlementDerived::new_for_key(&fs_key());
        let r = d.on_upstream_event(&funding_rate_event(500, 0.0001, 1000), 0);
        assert!(r.is_none(), "first event must only initialize state");
    }

    #[test]
    fn settlement_no_emit_if_nft_unchanged() {
        let mut d = FundingSettlementDerived::new_for_key(&fs_key());
        // Seed state: nft=1000.
        d.on_upstream_event(&funding_rate_event(500, 0.0001, 1000), 0);
        // Second event: ts still before nft, nft unchanged → no emit.
        let r = d.on_upstream_event(&funding_rate_event(800, 0.0001, 1000), 0);
        assert!(r.is_none(), "no crossing: nft unchanged and ts < nft");
    }

    #[test]
    fn settlement_emit_on_crossing() {
        let mut d = FundingSettlementDerived::new_for_key(&fs_key());
        // Seed: nft=1000, rate=0.0001.
        d.on_upstream_event(&funding_rate_event(500, 0.0001, 1000), 0);
        // Crossing: ts=1001 >= nft=1000, nft advanced to 2000.
        let r = d.on_upstream_event(&funding_rate_event(1001, 0.0002, 2000), 0);
        let p = r.expect("must emit on crossing");
        assert_eq!(p.ts_ms, 1001);
        assert!((p.settled_rate - 0.0001).abs() < 1e-12, "settled_rate must be from PREVIOUS event");
        assert_eq!(p.settlement_time, 1000);
    }

    #[test]
    fn settlement_no_emit_when_nft_zero() {
        let mut d = FundingSettlementDerived::new_for_key(&fs_key());
        let r = d.on_upstream_event(&funding_rate_event(1000, 0.0001, 0), 0);
        assert!(r.is_none(), "nft=0 must be silently absorbed");
    }

    #[test]
    fn settlement_rate_is_from_previous_event() {
        let mut d = FundingSettlementDerived::new_for_key(&fs_key());
        // Seed with rate=0.05.
        d.on_upstream_event(&funding_rate_event(500, 0.05, 1000), 0);
        // Trigger crossing with new_rate=0.03.
        let p = d.on_upstream_event(&funding_rate_event(1001, 0.03, 2000), 0).unwrap();
        assert!((p.settled_rate - 0.05).abs() < 1e-12, "settled_rate must be 0.05 (from prior event), not 0.03");
    }

    // -----------------------------------------------------------------------
    // interval_to_ms unit tests
    // -----------------------------------------------------------------------

    #[test]
    fn interval_to_ms_known_intervals() {
        assert_eq!(interval_to_ms("1s"),  Some(1_000));
        assert_eq!(interval_to_ms("3s"),  Some(3_000));
        assert_eq!(interval_to_ms("5s"),  Some(5_000));
        assert_eq!(interval_to_ms("10s"), Some(10_000));
        assert_eq!(interval_to_ms("15s"), Some(15_000));
        assert_eq!(interval_to_ms("30s"), Some(30_000));
        assert_eq!(interval_to_ms("1m"),  Some(60_000));
        assert_eq!(interval_to_ms("3m"),  Some(3 * 60_000));
        assert_eq!(interval_to_ms("5m"),  Some(5 * 60_000));
        assert_eq!(interval_to_ms("15m"), Some(15 * 60_000));
        assert_eq!(interval_to_ms("30m"), Some(30 * 60_000));
        assert_eq!(interval_to_ms("1h"),  Some(3_600_000));
        assert_eq!(interval_to_ms("2h"),  Some(2 * 3_600_000));
        assert_eq!(interval_to_ms("4h"),  Some(4 * 3_600_000));
        assert_eq!(interval_to_ms("6h"),  Some(6 * 3_600_000));
        assert_eq!(interval_to_ms("8h"),  Some(8 * 3_600_000));
        assert_eq!(interval_to_ms("12h"), Some(12 * 3_600_000));
        assert_eq!(interval_to_ms("1d"),  Some(86_400_000));
        assert_eq!(interval_to_ms("3d"),  Some(3 * 86_400_000));
        assert_eq!(interval_to_ms("1w"),  Some(7 * 86_400_000));
    }

    #[test]
    fn interval_to_ms_unknown() {
        assert!(interval_to_ms("").is_none());
        assert!(interval_to_ms("1x").is_none());
        assert!(interval_to_ms("abc").is_none());
        assert!(interval_to_ms("0m").is_none());
        assert!(interval_to_ms("-1m").is_none());
    }

    // -----------------------------------------------------------------------
    // TradeToBarDerived unit tests
    // -----------------------------------------------------------------------

    fn kline_key(interval: &str) -> SeriesKey {
        SeriesKey::new(
            ExchangeId::Binance,
            AccountType::FuturesCross,
            "BTCUSDT",
            crate::series::Kind::Kline(KlineInterval::new(interval)),
        )
    }

    fn trade_event(ts_ms: i64, price: f64, quantity: f64) -> Event {
        Event::Trade {
            exchange: ExchangeId::Binance,
            symbol: "BTCUSDT".to_string(),
            point: crate::data::TradePoint {
                ts_ms,
                price,
                quantity,
                side: 0,
                trade_id_hash: 0,
            },
        }
    }

    /// `Event::Bar` fixture for the kline-sufficient kinds' live Δ-tick
    /// adapter tests (Renko/PnF/Kagi/3LB/Range/Volume/Dollar) — a WS 1m
    /// kline update with `open` and `high`/`low` pinned to `close` (the
    /// folds under test only read `open_time` / `close` / `volume` via
    /// `KlineDeltaState::to_delta_trade`).
    fn bar_event(open_time: i64, close: f64, volume: f64) -> Event {
        Event::Bar {
            exchange: ExchangeId::Binance,
            symbol: "BTCUSDT".to_string(),
            timeframe: KlineInterval::new("1m"),
            point: BarPoint {
                open_time,
                open: close,
                high: close,
                low: close,
                close,
                volume,
                quote_volume: close * volume,
                trades_count: 1,
            },
        }
    }

    /// Trades within the same 1m bucket produce one bar whose OHLCV reflects
    /// all trades; a trade in the next bucket opens a new bar.
    #[test]
    fn trade_to_bar_bucketing_1m() {
        let key = kline_key("1m");
        let interval_ms = 60_000_i64;
        let mut d = TradeToBarDerived::new_for_key(&key);

        // t=0 — first trade, opens bucket [0, 60000).
        let p1 = d.on_upstream_event(&trade_event(0, 100.0, 1.0), 0)
            .expect("first trade must emit bar");
        assert_eq!(p1.open_time, 0);
        assert_eq!(p1.open, 100.0);
        assert_eq!(p1.high, 100.0);
        assert_eq!(p1.low,  100.0);
        assert_eq!(p1.close, 100.0);
        assert!((p1.volume - 1.0).abs() < 1e-12);
        assert_eq!(p1.trades_count, 1);

        // t=30_000 — same bucket, higher price.
        let p2 = d.on_upstream_event(&trade_event(30_000, 120.0, 2.0), 0)
            .expect("second trade must emit updated bar");
        assert_eq!(p2.open_time, 0, "same bucket — open_time must not change");
        assert_eq!(p2.open,  100.0, "open must be first trade price");
        assert_eq!(p2.high,  120.0, "high must update to 120");
        assert_eq!(p2.low,   100.0, "low stays at 100");
        assert_eq!(p2.close, 120.0, "close is most recent price");
        assert!((p2.volume - 3.0).abs() < 1e-12);
        assert_eq!(p2.trades_count, 2);

        // t=59_999 — still same bucket, lower price.
        let p3 = d.on_upstream_event(&trade_event(59_999, 90.0, 0.5), 0)
            .expect("third trade must emit");
        assert_eq!(p3.open_time, 0);
        assert_eq!(p3.low, 90.0, "new minimum");
        assert_eq!(p3.close, 90.0);
        assert_eq!(p3.trades_count, 3);

        // t=interval_ms — new bucket, resets bar.
        let p4 = d.on_upstream_event(&trade_event(interval_ms, 200.0, 5.0), 0)
            .expect("trade in new bucket must emit fresh bar");
        assert_eq!(p4.open_time, interval_ms, "new bar starts at next bucket boundary");
        assert_eq!(p4.open,  200.0);
        assert_eq!(p4.high,  200.0);
        assert_eq!(p4.low,   200.0);
        assert_eq!(p4.close, 200.0);
        assert!((p4.volume - 5.0).abs() < 1e-12);
        assert_eq!(p4.trades_count, 1);
    }

    /// A 1-second interval buckets at the correct ms boundary.
    #[test]
    fn trade_to_bar_sub_second_1s() {
        let key = kline_key("1s");
        let mut d = TradeToBarDerived::new_for_key(&key);

        let p1 = d.on_upstream_event(&trade_event(0, 50.0, 1.0), 0).unwrap();
        assert_eq!(p1.open_time, 0);

        // t=500ms — still inside bucket [0, 1000).
        let p2 = d.on_upstream_event(&trade_event(500, 60.0, 1.0), 0).unwrap();
        assert_eq!(p2.open_time, 0, "same 1s bucket");
        assert_eq!(p2.high, 60.0);

        // t=1000ms — new bucket.
        let p3 = d.on_upstream_event(&trade_event(1_000, 55.0, 1.0), 0).unwrap();
        assert_eq!(p3.open_time, 1_000, "second 1s bucket starts at 1000ms");
        assert_eq!(p3.open, 55.0);
    }

    /// Open must be first price, high=max, low=min, close=last across a sequence.
    #[test]
    fn trade_to_bar_ohlc_correctness() {
        let key = kline_key("5m");
        let mut d = TradeToBarDerived::new_for_key(&key);
        let bucket = 0_i64; // all inside [0, 5*60000)

        let prices = [300.0_f64, 100.0, 500.0, 200.0, 400.0];
        let qty    = [1.0_f64; 5];
        let ts     = [0_i64, 10_000, 20_000, 30_000, 40_000];

        let mut last = None;
        for i in 0..5 {
            last = d.on_upstream_event(&trade_event(ts[i], prices[i], qty[i]), 0);
        }
        let bar = last.unwrap();
        assert_eq!(bar.open_time, bucket);
        assert_eq!(bar.open,  300.0, "open = first price");
        assert_eq!(bar.high,  500.0, "high = max");
        assert_eq!(bar.low,   100.0, "low  = min");
        assert_eq!(bar.close, 400.0, "close = last price");
        let expected_vol: f64 = qty.iter().sum();
        assert!((bar.volume - expected_vol).abs() < 1e-9, "volume = sum of quantities");
        let expected_qvol: f64 = prices.iter().zip(qty.iter()).map(|(p, q)| p * q).sum();
        assert!((bar.quote_volume - expected_qvol).abs() < 1e-9);
        assert_eq!(bar.trades_count, 5);
    }

    /// `new_for_key` with a non-Kline kind sets `interval_ms=0` and never emits.
    #[test]
    fn trade_to_bar_non_kline_key_safe() {
        let key = SeriesKey::new(
            ExchangeId::Binance,
            AccountType::FuturesCross,
            "BTCUSDT",
            crate::series::Kind::Trade,
        );
        let mut d = TradeToBarDerived::new_for_key(&key);
        // Must never panic, must always return None.
        let r = d.on_upstream_event(&trade_event(0, 100.0, 1.0), 0);
        assert!(r.is_none(), "non-Kline key → interval_ms=0 → no emission");
    }

    /// `new_for_key` with an unknown interval string also sets `interval_ms=0`.
    #[test]
    fn trade_to_bar_unknown_interval_safe() {
        let key = kline_key("99x"); // not a valid interval
        let mut d = TradeToBarDerived::new_for_key(&key);
        let r = d.on_upstream_event(&trade_event(0, 100.0, 1.0), 0);
        assert!(r.is_none(), "unknown interval → interval_ms=0 → no emission");
    }

    // -----------------------------------------------------------------------
    // seed_from_events (Task A) unit tests
    // -----------------------------------------------------------------------

    /// seed_from_events primes state AND returns emitted bars.
    #[test]
    fn seed_from_events_primes_state_and_returns_bars() {
        let key = kline_key("1m");
        let mut d = TradeToBarDerived::new_for_key(&key);

        // Two trades in the same 1m bucket.
        let evs = vec![
            trade_event(0, 100.0, 1.0),
            trade_event(30_000, 120.0, 2.0),
        ];
        let emitted = d.seed_from_events(&evs, 0);

        // Both trades emitted (intra-bar updates).
        assert_eq!(emitted.len(), 2, "one bar emission per trade");
        let last = &emitted[1];
        assert_eq!(last.open, 100.0, "open = first trade");
        assert_eq!(last.high, 120.0, "high = second trade");
        assert_eq!(last.trades_count, 2);

        // State is primed: a new trade in the same bucket updates correctly.
        let cont = d.on_upstream_event(&trade_event(59_000, 110.0, 0.5), 0).unwrap();
        assert_eq!(cont.trades_count, 3, "live trade after seed updates state");
    }

    /// REGRESSION (fd58108): cold-seed and rewarm feed `kline_to_synthetic_trades`'
    /// 4-leg `Event::Trade` output directly through `seed_from_events` —
    /// NOT `Event::Bar`. `on_upstream_event` must accept `Event::Trade`
    /// unconditionally (dispatched straight to `fold_trade`) or the entire
    /// cold-seed/rewarm history path silently drops every leg (this is
    /// exactly the "history is empty" regression fd58108 introduced by
    /// requiring `Event::Bar` at the top of `on_upstream_event`).
    #[test]
    fn seed_from_events_range_bar_state_primed() {
        let key = range_bar_key(100_000_000); // $1 range
        let mut d = TradeToRangeBarDerived::new_for_key(&key);

        // Seed: open a bar at 100.0 via a synthetic Trade leg (cold-seed shape).
        let evs = vec![trade_event(0, 100.0, 1.0)];
        let emitted = d.seed_from_events(&evs, 0);
        assert_eq!(emitted.len(), 1, "Event::Trade seed legs must fold into bars");

        // State is primed — a further synthetic Trade leg crosses the range
        // and opens a new bar.
        let live = d.on_upstream_event(&trade_event(1, 101.0, 1.0), 0).unwrap();
        assert_eq!(live.open, 101.0, "new bar at crossing price");
    }

    /// Live WS path: repeated `Event::Bar` updates with growing volume fold
    /// into Δ-tick bars via `KlineDeltaState` (unchanged behavior from
    /// fd58108 — only the Trade-leg acceptance alongside it was missing).
    #[test]
    fn range_bar_live_bar_path_produces_delta_tick_bars() {
        let key = range_bar_key(100_000_000); // $1 range
        let mut d = TradeToRangeBarDerived::new_for_key(&key);

        assert!(d.on_upstream_event(&bar_event(0, 100.0, 1.0), 0).is_none(), "baseline-only, no emit");

        let p1 = d.on_upstream_event(&bar_event(0, 100.0, 1.5), 0).unwrap();
        assert_eq!(p1.open, 100.0);

        // Close moves to 100.5, Δvol=1.0 — within range.
        let p2 = d.on_upstream_event(&bar_event(0, 100.5, 2.5), 0).unwrap();
        assert_eq!(p2.open_time, p1.open_time, "same bar");
        assert_eq!(p2.high, 100.5, "high updated");
        assert_eq!(p2.close, 100.5);
        assert_eq!(p2.trades_count, 2);

        // Crossing range on a live Bar update opens a new bar.
        let p3 = d.on_upstream_event(&bar_event(0, 101.5, 3.5), 0).unwrap();
        assert_eq!(p3.open, 101.5, "new bar at crossing price");
    }

    /// seed_from_events with empty slice → no output, no side effects.
    #[test]
    fn seed_from_events_empty_slice_noop() {
        let key = kline_key("1m");
        let mut d = TradeToBarDerived::new_for_key(&key);
        let emitted = d.seed_from_events(&[], 0);
        assert!(emitted.is_empty());
        // Subsequent live trade opens a fresh bar.
        let p = d.on_upstream_event(&trade_event(0, 50.0, 1.0), 0).unwrap();
        assert_eq!(p.trades_count, 1);
    }

    // -----------------------------------------------------------------------
    // Helper for mechanical bar aggregator keys
    // -----------------------------------------------------------------------

    fn range_bar_key(range_fixed: u64) -> SeriesKey {
        SeriesKey::new(ExchangeId::Binance, AccountType::FuturesCross, "BTCUSDT",
            crate::series::Kind::RangeBar(range_fixed))
    }

    fn tick_bar_key(n: u32) -> SeriesKey {
        SeriesKey::new(ExchangeId::Binance, AccountType::FuturesCross, "BTCUSDT",
            crate::series::Kind::TickBar(n))
    }

    fn volume_bar_key(vol_fixed: u64) -> SeriesKey {
        SeriesKey::new(ExchangeId::Binance, AccountType::FuturesCross, "BTCUSDT",
            crate::series::Kind::VolumeBar(vol_fixed))
    }

    fn footprint_key(interval: &str) -> SeriesKey {
        SeriesKey::new(ExchangeId::Binance, AccountType::FuturesCross, "BTCUSDT",
            crate::series::Kind::Footprint(KlineInterval::new(interval)))
    }

    fn trade_event_side(ts_ms: i64, price: f64, quantity: f64, side: u8) -> Event {
        Event::Trade {
            exchange: ExchangeId::Binance,
            symbol: "BTCUSDT".to_string(),
            point: crate::data::TradePoint { ts_ms, price, quantity, side, trade_id_hash: 0 },
        }
    }

    // -----------------------------------------------------------------------
    // TradeToRangeBarDerived tests
    // -----------------------------------------------------------------------

    /// Trades within range stay in one bar. Fed as `Event::Trade` — the
    /// shape both the cold-seed and rewarm paths use.
    #[test]
    fn range_bar_stays_in_bar_while_within_range() {
        // range = $1.00 = 1_0000_0000 fixed-point
        let key = range_bar_key(100_000_000);
        let mut d = TradeToRangeBarDerived::new_for_key(&key);

        let p1 = d.on_upstream_event(&trade_event(0, 100.0, 1.0), 0).unwrap();
        assert_eq!(p1.open, 100.0);

        // Move 0.5 — within range.
        let p2 = d.on_upstream_event(&trade_event(1, 100.5, 1.0), 0).unwrap();
        assert_eq!(p2.open_time, p1.open_time, "same bar");
        assert_eq!(p2.open, 100.0, "open unchanged");
        assert_eq!(p2.high, 100.5, "high updated");
        assert_eq!(p2.close, 100.5);
        assert_eq!(p2.trades_count, 2);
    }

    /// Crossing range opens a new bar.
    #[test]
    fn range_bar_rolls_on_crossing() {
        // range = $1.00
        let key = range_bar_key(100_000_000);
        let mut d = TradeToRangeBarDerived::new_for_key(&key);

        d.on_upstream_event(&trade_event(0, 100.0, 1.0), 0).unwrap();
        // Exactly $1 movement — crosses.
        let p = d.on_upstream_event(&trade_event(10, 101.0, 2.0), 0).unwrap();
        // New bar started at 101.0.
        assert_eq!(p.open, 101.0, "new bar opens at crossing price");
        assert_eq!(p.trades_count, 1, "first trade in new bar");
    }

    /// OHLC correctness across two bars.
    #[test]
    fn range_bar_ohlc_correct() {
        let key = range_bar_key(100_000_000); // $1 range
        let mut d = TradeToRangeBarDerived::new_for_key(&key);

        // Bar 1: open 100, go up to 100.9, then cross with 101.
        d.on_upstream_event(&trade_event(0, 100.0, 1.0), 0).unwrap();
        d.on_upstream_event(&trade_event(1, 100.9, 1.0), 0).unwrap();
        let bar1_last = d.on_upstream_event(&trade_event(2, 100.4, 0.5), 0).unwrap();
        // bar1 still open (max deviation = 0.9 < 1.0)
        assert_eq!(bar1_last.open, 100.0);
        assert_eq!(bar1_last.high, 100.9);
        assert_eq!(bar1_last.low,  100.0);
        assert_eq!(bar1_last.close, 100.4);
    }

    /// Two bars closing at the same ms get distinct monotonic open_times.
    #[test]
    fn range_bar_monotonic_open_time_collision() {
        let key = range_bar_key(100_000_000); // $1 range
        let mut d = TradeToRangeBarDerived::new_for_key(&key);

        // ts=0: open bar1 at 100.0.
        let p1 = d.on_upstream_event(&trade_event(0, 100.0, 1.0), 0).unwrap();
        let ot1 = p1.open_time;

        // ts=0: cross at 101.0 — bar1 closes, bar2 opens. Same ms!
        let p2 = d.on_upstream_event(&trade_event(0, 101.0, 1.0), 0).unwrap();
        assert_ne!(p2.open_time, ot1, "bar2 must not share open_time with bar1");
        assert!(p2.open_time > ot1, "bar2 open_time must be strictly greater");
    }

    /// Zero range param → no emission.
    #[test]
    fn range_bar_zero_range_safe() {
        let key = range_bar_key(0);
        let mut d = TradeToRangeBarDerived::new_for_key(&key);
        assert!(d.on_upstream_event(&trade_event(0, 100.0, 1.0), 0).is_none());
    }

    // -----------------------------------------------------------------------
    // TradeToTickBarDerived tests
    // -----------------------------------------------------------------------

    /// Every n trades rolls a new bar.
    #[test]
    fn tick_bar_rolls_every_n() {
        let n = 3u32;
        let key = tick_bar_key(n);
        let mut d = TradeToTickBarDerived::new_for_key(&key);

        let p1 = d.on_upstream_event(&trade_event(0, 100.0, 1.0), 0).unwrap();
        assert_eq!(p1.trades_count, 1);
        let p2 = d.on_upstream_event(&trade_event(1, 101.0, 1.0), 0).unwrap();
        assert_eq!(p2.trades_count, 2);
        let p3 = d.on_upstream_event(&trade_event(2, 99.0, 1.0), 0).unwrap();
        assert_eq!(p3.trades_count, 3, "3rd trade completes bar");

        // 4th trade opens new bar.
        let p4 = d.on_upstream_event(&trade_event(3, 102.0, 2.0), 0).unwrap();
        assert_eq!(p4.trades_count, 1, "first trade in new bar");
        assert_eq!(p4.open, 102.0, "new bar open = 4th trade price");
    }

    /// OHLC across one complete bar.
    #[test]
    fn tick_bar_ohlc_correct() {
        let key = tick_bar_key(3);
        let mut d = TradeToTickBarDerived::new_for_key(&key);

        d.on_upstream_event(&trade_event(0, 200.0, 1.0), 0).unwrap();
        d.on_upstream_event(&trade_event(1,  50.0, 1.0), 0).unwrap();
        let last = d.on_upstream_event(&trade_event(2, 150.0, 1.0), 0).unwrap();

        assert_eq!(last.open,  200.0);
        assert_eq!(last.high,  200.0);
        assert_eq!(last.low,    50.0);
        assert_eq!(last.close, 150.0);
        assert!((last.volume - 3.0).abs() < 1e-12);
    }

    /// n=0 → no emission.
    #[test]
    fn tick_bar_zero_n_safe() {
        let key = tick_bar_key(0);
        let mut d = TradeToTickBarDerived::new_for_key(&key);
        assert!(d.on_upstream_event(&trade_event(0, 100.0, 1.0), 0).is_none());
    }

    // -----------------------------------------------------------------------
    // TradeToVolumeBarDerived tests
    // -----------------------------------------------------------------------

    /// Crossing threshold rolls a bar; crossing trade is in the closing bar.
    /// Fed as `Event::Trade` — the shape both cold-seed and rewarm use.
    #[test]
    fn volume_bar_rolls_on_threshold() {
        // threshold = 2.0 volume = 200_000_000 fixed-point
        let key = volume_bar_key(200_000_000);
        let mut d = TradeToVolumeBarDerived::new_for_key(&key);

        // Trade 1: vol=1.0 — cumulative 1.0 < 2.0 threshold.
        let p1 = d.on_upstream_event(&trade_event(0, 100.0, 1.0), 0).unwrap();
        assert!((p1.volume - 1.0).abs() < 1e-12);

        // Trade 2: vol=1.0 — cumulative 2.0 >= 2.0 → roll.
        let p2 = d.on_upstream_event(&trade_event(1, 101.0, 1.0), 0).unwrap();
        assert!((p2.volume - 2.0).abs() < 1e-12, "crossing trade in closing bar");
        assert_eq!(p2.close, 101.0, "close = crossing trade price");

        // Trade 3: opens new bar.
        let p3 = d.on_upstream_event(&trade_event(2, 102.0, 0.5), 0).unwrap();
        assert_eq!(p3.open, 102.0, "new bar");
        assert_ne!(p3.open_time, p2.open_time);
    }

    /// OHLC across one complete volume bar.
    #[test]
    fn volume_bar_ohlc_correct() {
        let key = volume_bar_key(300_000_000); // threshold = 3.0
        let mut d = TradeToVolumeBarDerived::new_for_key(&key);

        d.on_upstream_event(&trade_event(0, 100.0, 1.0), 0).unwrap();
        d.on_upstream_event(&trade_event(1, 200.0, 1.0), 0).unwrap();
        let last = d.on_upstream_event(&trade_event(2,  50.0, 1.0), 0).unwrap();

        assert_eq!(last.open,  100.0);
        assert_eq!(last.high,  200.0);
        assert_eq!(last.low,    50.0);
        assert_eq!(last.close,  50.0);
        assert!((last.volume - 3.0).abs() < 1e-12);
    }

    /// Zero threshold → no emission.
    #[test]
    fn volume_bar_zero_threshold_safe() {
        let key = volume_bar_key(0);
        let mut d = TradeToVolumeBarDerived::new_for_key(&key);
        assert!(d.on_upstream_event(&trade_event(0, 100.0, 1.0), 0).is_none());
    }

    /// Live WS path: repeated `Event::Bar` updates with growing volume fold
    /// into Δ-tick bars via `KlineDeltaState`, rolling on threshold exactly
    /// as the Trade-fed path does.
    #[test]
    fn volume_bar_live_bar_path_produces_delta_tick_bars() {
        // threshold = 2.0 volume = 200_000_000 fixed-point
        let key = volume_bar_key(200_000_000);
        let mut d = TradeToVolumeBarDerived::new_for_key(&key);

        d.on_upstream_event(&bar_event(0, 100.0, 0.0), 0); // baseline, vol=0

        // Δvol=1.0 — cumulative 1.0 < 2.0 threshold.
        let p1 = d.on_upstream_event(&bar_event(0, 100.0, 1.0), 0).unwrap();
        assert!((p1.volume - 1.0).abs() < 1e-12);

        // Δvol=1.0 — cumulative 2.0 >= 2.0 → roll.
        let p2 = d.on_upstream_event(&bar_event(0, 101.0, 2.0), 0).unwrap();
        assert!((p2.volume - 2.0).abs() < 1e-12, "crossing tick in closing bar");
        assert_eq!(p2.close, 101.0, "close = crossing tick price");

        // New open_time (bar rolled on the kline side too): baseline resets
        // to zero volume, so the first tick on the new bar reports its own
        // already-accrued volume (0.5) — opens the new derived bar.
        let p3 = d.on_upstream_event(&bar_event(60_000, 102.0, 0.5), 0).unwrap();
        assert_eq!(p3.open, 102.0, "new bar");
        assert_ne!(p3.open_time, p2.open_time);
    }

    // -----------------------------------------------------------------------
    // TradeToFootprintDerived tests
    // -----------------------------------------------------------------------

    /// Per-level buy/sell accumulate correctly by side.
    #[test]
    fn footprint_per_level_buy_sell() {
        let key = footprint_key("1m");
        let mut d = TradeToFootprintDerived::new_for_key(&key);

        // Two buys at 100.0, one sell at 100.0.
        d.on_upstream_event(&trade_event_side(0, 100.0, 1.5, 0), 0); // buy 1.5
        d.on_upstream_event(&trade_event_side(1, 100.0, 0.5, 1), 0); // sell 0.5
        let p = d.on_upstream_event(&trade_event_side(2, 100.0, 1.0, 0), 0).unwrap(); // buy 1.0

        assert_eq!(p.levels.len(), 1, "one unique price level");
        let (price, buy, sell) = p.levels[0];
        assert!((price - 100.0).abs() < 1e-12);
        assert!((buy  -  2.5 ).abs() < 1e-12, "buy = 1.5 + 1.0");
        assert!((sell -  0.5 ).abs() < 1e-12);
    }

    /// Bucket roll resets levels and OHLC.
    #[test]
    fn footprint_bucket_roll_resets() {
        let key = footprint_key("1m");
        let interval_ms = 60_000_i64;
        let mut d = TradeToFootprintDerived::new_for_key(&key);

        d.on_upstream_event(&trade_event_side(0, 100.0, 1.0, 0), 0);
        // Trade in next bucket.
        let p = d.on_upstream_event(&trade_event_side(interval_ms, 200.0, 2.0, 1), 0).unwrap();
        assert_eq!(p.open_time, interval_ms, "new bucket");
        assert_eq!(p.open, 200.0, "reset to new bucket open");
        assert_eq!(p.levels.len(), 1, "only new bucket level");
        let (_, buy, sell) = p.levels[0];
        assert!((buy - 0.0).abs() < 1e-12);
        assert!((sell - 2.0).abs() < 1e-12);
    }

    /// OHLC accumulates correctly across bucket.
    #[test]
    fn footprint_ohlc_correct() {
        let key = footprint_key("1m");
        let mut d = TradeToFootprintDerived::new_for_key(&key);

        d.on_upstream_event(&trade_event_side(0, 100.0, 1.0, 0), 0);
        d.on_upstream_event(&trade_event_side(1, 200.0, 1.0, 1), 0);
        let p = d.on_upstream_event(&trade_event_side(2,  50.0, 1.0, 0), 0).unwrap();

        assert_eq!(p.open,   100.0);
        assert_eq!(p.high,   200.0);
        assert_eq!(p.low,     50.0);
        assert_eq!(p.close,   50.0);
        assert!((p.volume - 3.0).abs() < 1e-12);
    }

    /// Multiple price levels are sorted by price (BTreeMap ordering of positive f64 bits).
    #[test]
    fn footprint_levels_sorted_by_price() {
        let key = footprint_key("1m");
        let mut d = TradeToFootprintDerived::new_for_key(&key);

        d.on_upstream_event(&trade_event_side(0, 300.0, 1.0, 0), 0);
        d.on_upstream_event(&trade_event_side(1, 100.0, 1.0, 0), 0);
        let p = d.on_upstream_event(&trade_event_side(2, 200.0, 1.0, 1), 0).unwrap();

        assert_eq!(p.levels.len(), 3);
        // Prices should be sorted ascending.
        let prices: Vec<f64> = p.levels.iter().map(|(pr, _, _)| *pr).collect();
        assert!(prices[0] < prices[1] && prices[1] < prices[2],
            "levels must be sorted ascending: {:?}", prices);
    }

    /// Unknown interval → disabled.
    #[test]
    fn footprint_unknown_interval_safe() {
        let key = footprint_key("99x");
        let mut d = TradeToFootprintDerived::new_for_key(&key);
        assert!(d.on_upstream_event(&trade_event_side(0, 100.0, 1.0, 0), 0).is_none());
    }

    // -----------------------------------------------------------------------
    // kline_to_synthetic_trades
    // -----------------------------------------------------------------------

    fn sample_bar(open: f64, high: f64, low: f64, close: f64, volume: f64) -> BarPoint {
        BarPoint {
            open_time: 1_000,
            open,
            high,
            low,
            close,
            volume,
            quote_volume: f64::NAN,
            trades_count: 0,
        }
    }

    #[test]
    fn kline_to_synthetic_trades_bullish_path_is_o_l_h_c() {
        let bar = sample_bar(100.0, 120.0, 90.0, 110.0, 40.0);
        let events = kline_to_synthetic_trades(&bar, 60_000, ExchangeId::Binance, "BTCUSDT");
        assert_eq!(events.len(), 4);
        let prices: Vec<f64> = events.iter().map(|e| {
            let Event::Trade { point, .. } = e else { panic!("expected Event::Trade") };
            point.price
        }).collect();
        assert_eq!(prices, vec![100.0, 90.0, 120.0, 110.0], "bullish bar must trace O->L->H->C");
    }

    #[test]
    fn kline_to_synthetic_trades_bearish_path_is_o_h_l_c() {
        let bar = sample_bar(110.0, 120.0, 90.0, 100.0, 40.0);
        let events = kline_to_synthetic_trades(&bar, 60_000, ExchangeId::Binance, "BTCUSDT");
        assert_eq!(events.len(), 4);
        let prices: Vec<f64> = events.iter().map(|e| {
            let Event::Trade { point, .. } = e else { panic!("expected Event::Trade") };
            point.price
        }).collect();
        assert_eq!(prices, vec![110.0, 120.0, 90.0, 100.0], "bearish bar must trace O->H->L->C");
    }

    #[test]
    fn kline_to_synthetic_trades_timestamps_evenly_spaced_within_bar() {
        let bar = sample_bar(100.0, 120.0, 90.0, 110.0, 40.0);
        let events = kline_to_synthetic_trades(&bar, 60_000, ExchangeId::Binance, "BTCUSDT");
        let ts: Vec<i64> = events.iter().map(|e| {
            let Event::Trade { point, .. } = e else { panic!("expected Event::Trade") };
            point.ts_ms
        }).collect();
        assert_eq!(ts, vec![1_000, 16_000, 31_000, 46_000]);
        // All 4 timestamps stay inside [open_time, open_time + interval_ms).
        assert!(ts.iter().all(|t| *t >= bar.open_time && *t < bar.open_time + 60_000));
    }

    #[test]
    fn kline_to_synthetic_trades_volume_split_evenly() {
        let bar = sample_bar(100.0, 120.0, 90.0, 110.0, 40.0);
        let events = kline_to_synthetic_trades(&bar, 60_000, ExchangeId::Binance, "BTCUSDT");
        for e in &events {
            let Event::Trade { point, .. } = e else { panic!("expected Event::Trade") };
            assert!((point.quantity - 10.0).abs() < 1e-12, "each leg should carry volume/4");
        }
    }

    #[test]
    fn kline_to_synthetic_trades_zero_interval_returns_empty() {
        let bar = sample_bar(100.0, 120.0, 90.0, 110.0, 40.0);
        assert!(kline_to_synthetic_trades(&bar, 0, ExchangeId::Binance, "BTCUSDT").is_empty());
    }

    #[test]
    fn kline_to_synthetic_trades_carries_exchange_and_symbol() {
        let bar = sample_bar(100.0, 120.0, 90.0, 110.0, 40.0);
        let events = kline_to_synthetic_trades(&bar, 60_000, ExchangeId::Bybit, "ETHUSDT");
        for e in &events {
            let Event::Trade { exchange, symbol, .. } = e else { panic!("expected Event::Trade") };
            assert_eq!(*exchange, ExchangeId::Bybit);
            assert_eq!(symbol, "ETHUSDT");
        }
    }

    // -----------------------------------------------------------------------
    // KlineDeltaState — live Δ-tick adapter tests
    // -----------------------------------------------------------------------

    fn extract_trade(ev: &Event) -> &TradePoint {
        let Event::Trade { point, .. } = ev else { panic!("expected Event::Trade") };
        point
    }

    /// Same open_time repeated updates → correct Δvolume ticks, no rollback,
    /// no double-count of already-reported volume.
    #[test]
    fn kline_delta_state_same_open_time_produces_correct_deltas() {
        let mut st = KlineDeltaState::new();
        let tf = KlineInterval::new("1m");

        // First event ever seen (no cold-seed baseline handed over) only
        // establishes the baseline — no synthetic trade.
        let bar0 = BarPoint { open_time: 0, open: 100.0, high: 100.0, low: 100.0, close: 100.0, volume: 1.0, quote_volume: 100.0, trades_count: 1 };
        assert!(st.to_delta_trade(&bar0, &tf, ExchangeId::Binance, "BTCUSDT").is_none());

        // Same open_time, volume grew 1.0 -> 2.5: Δ = 1.5.
        let bar1 = BarPoint { open_time: 0, open: 100.0, high: 101.0, low: 100.0, close: 101.0, volume: 2.5, quote_volume: 250.0, trades_count: 2 };
        let ev1 = st.to_delta_trade(&bar1, &tf, ExchangeId::Binance, "BTCUSDT").expect("volume grew — must emit");
        let t1 = extract_trade(&ev1);
        assert!((t1.quantity - 1.5).abs() < 1e-12, "Δvolume = 2.5 - 1.0 = 1.5");
        assert_eq!(t1.price, 101.0, "price = bar.close");
        assert_eq!(t1.side, 0, "close rose vs previous close — buy side");

        // Same open_time, volume grew again 2.5 -> 4.0: Δ = 1.5, price falls.
        let bar2 = BarPoint { open_time: 0, open: 100.0, high: 101.0, low: 99.0, close: 99.0, volume: 4.0, quote_volume: 396.0, trades_count: 3 };
        let ev2 = st.to_delta_trade(&bar2, &tf, ExchangeId::Binance, "BTCUSDT").expect("volume grew — must emit");
        let t2 = extract_trade(&ev2);
        assert!((t2.quantity - 1.5).abs() < 1e-12);
        assert_eq!(t2.side, 1, "close fell vs previous close — sell side");

        // Duplicate frame (same open_time, same volume) → no emission, no
        // double-count.
        assert!(st.to_delta_trade(&bar2, &tf, ExchangeId::Binance, "BTCUSDT").is_none(), "zero delta must not emit");
    }

    /// New open_time (bar rolled) → previous bar is final and never
    /// re-folded; the new bar's baseline resets to zero volume so its first
    /// observed update reports its OWN accrued volume, not a delta against
    /// the old bar.
    #[test]
    fn kline_delta_state_rollover_resets_baseline_no_double_count() {
        let mut st = KlineDeltaState::new();
        let tf = KlineInterval::new("1m");

        let bar_a0 = BarPoint { open_time: 0, open: 100.0, high: 100.0, low: 100.0, close: 100.0, volume: 5.0, quote_volume: 500.0, trades_count: 1 };
        assert!(st.to_delta_trade(&bar_a0, &tf, ExchangeId::Binance, "BTCUSDT").is_none(), "baseline only");

        let bar_a1 = BarPoint { open_time: 0, open: 100.0, high: 102.0, low: 100.0, close: 102.0, volume: 9.0, quote_volume: 900.0, trades_count: 2 };
        let ev_a1 = st.to_delta_trade(&bar_a1, &tf, ExchangeId::Binance, "BTCUSDT").expect("must emit");
        assert!((extract_trade(&ev_a1).quantity - 4.0).abs() < 1e-12, "Δvolume within bar A = 9-5 = 4");

        // Bar rolls to a NEW open_time — bar A (final volume 9.0) is never
        // re-folded. Bar B's first observed update carries volume=1.2 —
        // must be reported as 1.2 (its own accrued volume), NOT as
        // 1.2 - 9.0 (which would be negative / would imply double-counting
        // bar A's volume against bar B).
        let bar_b0 = BarPoint { open_time: 60_000, open: 102.0, high: 103.0, low: 102.0, close: 103.0, volume: 1.2, quote_volume: 123.6, trades_count: 1 };
        let ev_b0 = st.to_delta_trade(&bar_b0, &tf, ExchangeId::Binance, "BTCUSDT").expect("new bar's first update must emit");
        let t_b0 = extract_trade(&ev_b0);
        assert!((t_b0.quantity - 1.2).abs() < 1e-12, "new bar reports its own accrued volume, not a delta vs bar A");
        assert!(t_b0.ts_ms >= 60_000, "ts_ms must fall within the new bar's window");

        // Continuing bar B accrues correctly against the reset baseline.
        let bar_b1 = BarPoint { open_time: 60_000, open: 102.0, high: 103.0, low: 102.0, close: 103.0, volume: 2.0, quote_volume: 206.0, trades_count: 2 };
        let ev_b1 = st.to_delta_trade(&bar_b1, &tf, ExchangeId::Binance, "BTCUSDT").expect("must emit");
        assert!((extract_trade(&ev_b1).quantity - 0.8).abs() < 1e-12, "Δvolume within bar B = 2.0-1.2 = 0.8");
    }

    /// `seed_baseline` primes the adapter exactly as the cold-seed→live seam
    /// requires: a live update sharing the seeded `open_time` computes a
    /// delta against the seed's already-folded volume instead of re-folding
    /// (double-counting) the whole bar.
    #[test]
    fn kline_delta_state_seed_baseline_prevents_seam_double_count() {
        let mut st = KlineDeltaState::new();
        let tf = KlineInterval::new("1m");

        // Cold-seed folded this bar's volume up to 7.0 already (as either a
        // 4-leg synthetic path for a closed bar, or as the unclosed-bar
        // baseline handoff — either way, 7.0 units are already accounted).
        st.seed_baseline(120_000, 7.0, 105.0);

        // Live WS delivers the SAME open_time with more volume accrued.
        let bar = BarPoint { open_time: 120_000, open: 105.0, high: 106.0, low: 105.0, close: 106.0, volume: 9.5, quote_volume: 1000.0, trades_count: 3 };
        let ev = st.to_delta_trade(&bar, &tf, ExchangeId::Binance, "BTCUSDT").expect("must emit");
        let t = extract_trade(&ev);
        assert!((t.quantity - 2.5).abs() < 1e-12, "Δvolume against the SEEDED baseline = 9.5 - 7.0 = 2.5, not the full 9.5");
    }
}