kestrel-chartkit 0.11.3

High-performance Rust technical analysis library for indicator math, market regime classification, composite scoring, and SVG visualization.
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
use std::collections::HashMap;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use super::adx::Adx;
use super::alligator::AlligatorEngine;
use super::anchored_vwap::{AnchoredVwapEngine, VwapAnchorKind, ZeroVolumePolicy};
use super::atr::{Atr, TrueRangeSmoothing};
use super::bbtrend::BbTrend;
use super::bollinger::{BollingerBands, VarianceConvention};
use super::bop::BalanceOfPowerEngine;
use super::bos_choch::BosChochEngine;
use super::buy_sell_pressure::BuySellPressureEstimator;
use super::candle_story::{CandleStoryConfig, CandleStoryEngine};
use super::cci::Cci;
use super::chaikin_osc::ChaikinOscillatorEngine;
use super::chande_kroll::ChandeKrollStop;
use super::chandelier_exit::ChandelierExitEngine;
use super::chandelier_flip_radar::ChandelierFlipRadarEngine;
use super::choppiness::ChoppinessIndexEngine;
use super::connors_rsi::ConnorsRsiEngine;
use super::coppock::CoppockCurveEngine;
use super::dpo::DpoEngine;
use super::efficiency::LegEfficiencyEngine;
use super::envelope::EnvelopeEngine;
use super::eom::EomEngine;
use super::fisher_transform::FisherTransform;
use super::force_index::ElderForceIndex;
use super::kst::KstEngine;
use super::liquidity_fvg::LiquidityFvgEngine;
use super::liquidity_sweeps::LiquiditySweepEngine;
use super::lsma::LsmaEngine;
use super::macd::Macd;
use super::market_structure_breaks::MarketStructureBreaksEngine;
use super::mass_index::MassIndexEngine;
use super::mcginley::McGinleyDynamicEngine;
use super::mfi::Mfi;
use super::midas::{MidasCurveEngine, MidasMode};
use super::momentum_indicators::{
    AwesomeOscillatorEngine, CmoEngine, ElderRayEngine, PpoEngine, RocEngine, StochasticEngine,
    UltimateOscillatorEngine,
};
use super::money_flow_profile::MoneyFlowProfileEngine;
use super::moving_averages::{
    DemaEngine, EmaEngine, HmaEngine, KamaEngine, SmaEngine, VwmaEngine, WmaEngine,
};
use super::multi_factor::MultiFactorMarketScore;
use super::nvi_pvi::{NviEngine, PviEngine};
use super::order_block::OrderBlockEngine;
pub use super::params::{ParamValue, TypedParams};
use super::pivot_sets::{PivotSetType, PivotSetsEngine};
use super::pivots_structure::PivotStructureEngine;
use super::pmo::PriceMomentumOscillator;
use super::pvt::PriceVolumeTrend;
use super::rci::RciEngine;
use super::relative_volatility::{RelativeVolatilityIndex, RelativeVolatilityVariant};
use super::rsi::{Rsi, RsiSmoothing};
use super::rvat::RelativeVolumeAtTime;
use super::rvi::RviEngine;
use super::smi::StochasticMomentumIndex;
use super::smoothing::EmaInit;
use super::stoch_rsi::StochRsi;
use super::t3::T3;
use super::tema::TemaEngine;
use super::trend_quality::TrendQualityScoreEngine;
use super::trend_structural::{
    AroonEngine, DmiEngine, IchimokuEngine, ParabolicSarEngine, SupertrendEngine,
};
use super::trix::Trix;
use super::tsi::Tsi;
use super::twap::{AnchoredTwap, TwapAnchor, TwapWeighting};
use super::ulcer::UlcerIndexEngine;
use super::vidya::Vidya;
use super::vix_fix::WilliamsVixFix;
use super::volatility_indicators::{
    DonchianChannelEngine, GarmanKlassVolatilityEngine, HistoricalVolatilityEngine,
    KeltnerChannelEngine, TrueRangeEngine,
};
use super::volatility_regime::VolatilityRegimeDetector;
use super::volume_flow::{CvdEngine, KlingerVolumeForceEngine};
use super::volume_flow_hires::HiResVolumeFlowEngine;
use super::volume_indicators::{AccDistEngine, CmfEngine, ObvEngine, RvolEngine, VolumeEngine};
use super::volume_profile::VolumeProfileEngine;
use super::volume_profile_extended::ExtendedVolumeProfileEngine;
use super::volume_profile_persistent::PersistentVolumeProfileEngine;
use super::vortex::VortexEngine;
use super::vwap::Vwap;
use super::wavetrend::WaveTrendEngine;
use super::williams_r::WilliamsR;
use super::zigzag::ZigZagEngine;
use super::zigzag_advanced::{AdvancedZigZagEngine, ZigZagDeviationMode};
use super::zscore::ZScoreEngine;
use super::Indicator;

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct IndicatorCatalogEntry {
    pub name: &'static str,
    pub description: &'static str,
    pub default_params: HashMap<String, f64>,
}

pub fn catalog() -> Vec<IndicatorCatalogEntry> {
    vec![
        IndicatorCatalogEntry {
            name: "rsi",
            description: "Relative Strength Index (build_typed accepts smoothing=wilder|ema for the up/down averages; wilder is the default)",
            default_params: [
                ("rsi_len".to_string(), 14.0),
                ("avg_len".to_string(), 3.0),
                ("sig_len".to_string(), 3.0),
                ("overbought".to_string(), 70.0),
                ("oversold".to_string(), 30.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "macd",
            description: "Moving Average Convergence Divergence",
            default_params: [
                ("fast_len".to_string(), 12.0),
                ("slow_len".to_string(), 26.0),
                ("signal_len".to_string(), 9.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "bollinger",
            description: "Bollinger Bands (build_typed accepts variance=population|sample for the standard-deviation divisor; population is the default)",
            default_params: [("len".to_string(), 20.0), ("mult".to_string(), 2.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "adx",
            description: "Average Directional Index",
            default_params: [
                ("di_len".to_string(), 14.0),
                ("adx_smooth".to_string(), 14.0),
                ("level_weak".to_string(), 20.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "stoch_rsi",
            description: "Stochastic RSI",
            default_params: [
                ("rsi_len".to_string(), 14.0),
                ("stoch_len".to_string(), 14.0),
                ("k_len".to_string(), 3.0),
                ("d_len".to_string(), 3.0),
                ("overbought".to_string(), 80.0),
                ("oversold".to_string(), 20.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "cci",
            description: "Commodity Channel Index",
            default_params: [
                ("cci_len".to_string(), 20.0),
                ("overbought".to_string(), 100.0),
                ("oversold".to_string(), -100.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "mfi",
            description: "Money Flow Index",
            default_params: [
                ("mfi_len".to_string(), 14.0),
                ("overbought".to_string(), 80.0),
                ("oversold".to_string(), 20.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "twap",
            description: "Anchored Time Weighted Average Price (no volume; build_typed accepts weighting=per_bar|by_duration and anchor=continuous|daily|manual_timestamp)",
            default_params: [("day_start_offset".to_string(), 0.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "relative_volatility",
            description: "Relative Volatility Index (the RSI construction applied to the standard deviation; build_typed accepts variant=close|high_low). Unrelated to \"rvi\", the Relative Vigor Index",
            default_params: [
                ("stdev_len".to_string(), 10.0),
                ("smooth_len".to_string(), 14.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "bbtrend",
            description: "BBTrend (how far a short Bollinger set has moved out of a long one, in percent of the short basis; build_typed accepts variance=population|sample for both sets)",
            default_params: [
                ("short_len".to_string(), 20.0),
                ("long_len".to_string(), 50.0),
                ("mult".to_string(), 2.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "pvt",
            description: "Price Volume Trend (volume weighted by the relative price change, accumulated)",
            default_params: [].into(),
        },
        IndicatorCatalogEntry {
            name: "pmo",
            description: "Price Momentum Oscillator (twice-smoothed one-bar return with alpha = 2/length, scaled by ten)",
            default_params: [
                ("length_1".to_string(), 35.0),
                ("length_2".to_string(), 20.0),
                ("signal_len".to_string(), 10.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "rvat",
            description: "Relative Volume at Time (volume against the same time of day on previous days, regular and cumulative)",
            default_params: [
                ("days".to_string(), 10.0),
                ("day_start_offset".to_string(), 0.0),
                ("bar_seconds".to_string(), 60.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "smi",
            description: "Stochastic Momentum Index (double-smoothed position of the close relative to the midpoint of the high-low range)",
            default_params: [
                ("len".to_string(), 10.0),
                ("smooth_1".to_string(), 3.0),
                ("smooth_2".to_string(), 3.0),
                ("signal_len".to_string(), 3.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "rci",
            description: "Rank Correlation Index (rank of prices against rank of time, scaled by 100)",
            default_params: [("len".to_string(), 9.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "ulcer_index",
            description: "Ulcer Index (root mean square of the percentage drawdowns below the running high)",
            default_params: [("len".to_string(), 14.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "t3",
            description: "Tillson T3 (weighted combination of six chained EMAs; v is a shape factor, not volume)",
            default_params: [("period".to_string(), 5.0), ("v".to_string(), 0.7)].into(),
        },
        IndicatorCatalogEntry {
            name: "vidya",
            description: "Variable Index Dynamic Average (CMO-scaled exponential smoothing)",
            default_params: [("cmo_len".to_string(), 9.0), ("ema_len".to_string(), 12.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "trix",
            description: "TRIX (rate of change of a triple-smoothed price series, in percent)",
            default_params: [("len".to_string(), 15.0), ("signal_len".to_string(), 9.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "efi",
            description: "Elder's Force Index (price change times volume, EMA-smoothed)",
            default_params: [("ema_len".to_string(), 13.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "atr",
            description: "Average True Range (build_typed accepts smoothing=rma|sma|ema|wma for the true-range average; rma is the default and the signal line stays Wilder-smoothed)",
            default_params: [("atr_len".to_string(), 14.0), ("sig_len".to_string(), 20.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "chande_kroll",
            description: "Chande Kroll Stop (window extremes minus/plus a Wilder-smoothed ATR, passed through a second extreme window)",
            default_params: [
                ("atr_len".to_string(), 10.0),
                ("stop_len".to_string(), 9.0),
                ("mult".to_string(), 3.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "chandelier_exit",
            description: "Chandelier Exit (ATR trailing stop with direction flip)",
            default_params: [("length".to_string(), 22.0), ("atr_mult".to_string(), 3.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "chandelier_flip_radar",
            description: "Chandelier Exit ratchet extended with adaptive multiplier, body-filtered weak flips, and bull/bear trap detection (use ChandelierFlipRadarEngine::new directly for use_close_extremes=false or simple_adaptive=true; this f64-only entry uses the documented defaults for both)",
            default_params: [
                ("length".to_string(), 30.0),
                ("atr_mult".to_string(), 4.5),
                ("body_filter_atr".to_string(), 0.80),
                ("danger_dist_atr".to_string(), 0.35),
                ("warn_dist_atr".to_string(), 0.75),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "midas",
            description: "MIDAS launch-anchored curve with Topfinder/Bottomfinder projection (build_typed with mode=topfinder|bottomfinder)",
            default_params: [("maturity_bars".to_string(), 20.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "hires_volume_flow",
            description: "High-resolution volume flow with absorption detection (OHLC-estimated via this registry entry point; use HiResVolumeFlowEngine::on_bar_with_aggressor/on_intrabar_group directly for direct aggressor/intrabar-delta resolution)",
            default_params: [("window_len".to_string(), 20.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "extended_volume_profile",
            description: "Full-bin price/volume profile with HVN/LVN/AVN classification, a delta profile, and zone formation (use ExtendedVolumeProfileEngine::on_intrabar_group directly for intrabar-resolution distribution)",
            default_params: [("lookback".to_string(), 70.0), ("num_bins".to_string(), 30.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "persistent_volume_profile",
            description: "Fixed-price-grid volume profile with real bin lifecycle (birth/growth/expiry across updates) and a per-bin absorption profile",
            default_params: [("lookback".to_string(), 70.0), ("bin_width".to_string(), 1.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "trend_relationship",
            description: "Adaptive trend relationship between two configurable smoothers (build via build_typed with fast_kind/slow_kind params: ema|sma|rma|alma|jma)",
            default_params: [("fast_len".to_string(), 9.0), ("slow_len".to_string(), 21.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "williams_r",
            description: "Williams %R",
            default_params: [
                ("wpr_len".to_string(), 14.0),
                ("overbought".to_string(), 80.0),
                ("oversold".to_string(), 20.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "tsi",
            description: "True Strength Index",
            default_params: [
                ("long_len".to_string(), 25.0),
                ("short_len".to_string(), 13.0),
                ("sig_len".to_string(), 7.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "fisher_transform",
            description: "Fisher Transform",
            default_params: [
                ("fish_len".to_string(), 10.0),
                ("overbought".to_string(), 1.5),
                ("oversold".to_string(), -1.5),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "order_block",
            description: "Order block detection from displacement candles (ATR-filtered)",
            default_params: [
                ("atr_len".to_string(), 14.0),
                ("min_disp".to_string(), 1.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "liquidity_fvg",
            description: "Fair value gap (imbalance) detection",
            default_params: [("lookback".to_string(), 20.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "market_structure_breaks",
            description: "Break of structure / change of character (BOS/CHoCH) detection",
            default_params: [("lookback".to_string(), 5.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "pivots_structure",
            description: "Swing pivot detection with a rolling structure score",
            default_params: [
                ("left_bars".to_string(), 5.0),
                ("right_bars".to_string(), 5.0),
                ("score_window".to_string(), 10.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "volume_profile",
            description: "Price/volume distribution profile with point-of-control",
            default_params: [
                ("lookback".to_string(), 70.0),
                ("num_bins".to_string(), 30.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "money_flow_profile",
            description: "Volume-by-price profile binned by dollar volume (volume x price) instead of raw volume, plus an aggregate bull/bear flow-bias percentage",
            default_params: [
                ("lookback".to_string(), 200.0),
                ("rows".to_string(), 25.0),
                ("va_pct".to_string(), 0.70),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "vwap",
            description: "Rolling Volume Weighted Average Price with sigma bands and slope",
            default_params: [
                ("window".to_string(), 390.0),
                ("slope_lookback".to_string(), 20.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "vix_fix",
            description: "Williams Vix Fix volatility spike detector",
            default_params: [
                ("pd".to_string(), 22.0),
                ("bband_len".to_string(), 20.0),
                ("mult".to_string(), 2.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "candle_story",
            description: "Normalised candle classification — reports every pattern it recognises",
            default_params: [
                ("pin_wick_min".to_string(), 0.55),
                ("pin_close_pos".to_string(), 0.65),
                ("marubozu_body_min".to_string(), 0.82),
                ("doji_body_max".to_string(), 0.08),
                ("hammer_wick_body_min".to_string(), 2.0),
                ("min_range_atr".to_string(), 0.5),
                ("atr_len".to_string(), 14.0),
                ("trend_lookback".to_string(), 10.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "efficiency",
            description: "Kaufman-style leg efficiency ratio",
            default_params: [("len".to_string(), 14.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "volume",
            description: "Volume and Average Volume",
            default_params: [("ma_period".to_string(), 20.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "rvol",
            description: "Relative Volume vs Moving Average",
            default_params: [("period".to_string(), 20.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "obv",
            description: "On-Balance Volume",
            default_params: HashMap::new(),
        },
        IndicatorCatalogEntry {
            name: "cmf",
            description: "Chaikin Money Flow",
            default_params: [("period".to_string(), 20.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "acc_dist",
            description: "Accumulation / Distribution Line",
            default_params: HashMap::new(),
        },
        IndicatorCatalogEntry {
            name: "true_range",
            description: "True Range in price units",
            default_params: HashMap::new(),
        },
        IndicatorCatalogEntry {
            name: "keltner",
            description: "Keltner Channels",
            default_params: [
                ("ema_period".to_string(), 20.0),
                ("atr_period".to_string(), 10.0),
                ("multiplier".to_string(), 2.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "donchian",
            description: "Donchian Channels",
            default_params: [("period".to_string(), 20.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "historical_volatility",
            description: "Annualized Historical Volatility",
            default_params: [("period".to_string(), 20.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "garman_klass",
            description: "Garman-Klass Volatility Estimator",
            default_params: [("period".to_string(), 20.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "sma",
            description: "Simple Moving Average",
            default_params: [("period".to_string(), 20.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "ema",
            description: "Exponential Moving Average (build_typed accepts init=first_sample|sma for the seed; first_sample is the default)",
            default_params: [("period".to_string(), 20.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "wma",
            description: "Weighted Moving Average",
            default_params: [("period".to_string(), 20.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "vwma",
            description: "Volume-Weighted Moving Average",
            default_params: [("period".to_string(), 20.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "hma",
            description: "Hull Moving Average",
            default_params: [("period".to_string(), 20.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "dema",
            description: "Double Exponential Moving Average",
            default_params: [("period".to_string(), 20.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "kama",
            description: "Kaufman's Adaptive Moving Average",
            default_params: [
                ("period".to_string(), 10.0),
                ("fast_period".to_string(), 2.0),
                ("slow_period".to_string(), 30.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "dmi",
            description: "Directional Movement Index (+DI / -DI)",
            default_params: [("period".to_string(), 14.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "aroon",
            description: "Aroon Indicator (Up, Down, Oscillator)",
            default_params: [("period".to_string(), 14.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "parabolic_sar",
            description: "Parabolic SAR",
            default_params: [("step".to_string(), 0.02), ("max_step".to_string(), 0.20)].into(),
        },
        IndicatorCatalogEntry {
            name: "supertrend",
            description: "Supertrend ATR Trailing Stop",
            default_params: [
                ("period".to_string(), 10.0),
                ("multiplier".to_string(), 3.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "ichimoku",
            description: "Ichimoku Kinko Hyo Cloud",
            default_params: [
                ("tenkan_p".to_string(), 9.0),
                ("kijun_p".to_string(), 26.0),
                ("senkou_b_p".to_string(), 52.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "stochastic",
            description: "Classic Stochastic Oscillator",
            default_params: [
                ("k_period".to_string(), 14.0),
                ("d_period".to_string(), 3.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "roc",
            description: "Rate of Change / Momentum",
            default_params: [("period".to_string(), 12.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "ultimate_oscillator",
            description: "Ultimate Oscillator",
            default_params: [
                ("period1".to_string(), 7.0),
                ("period2".to_string(), 14.0),
                ("period3".to_string(), 28.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "awesome_oscillator",
            description: "Awesome Oscillator",
            default_params: [
                ("fast_period".to_string(), 5.0),
                ("slow_period".to_string(), 34.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "ppo",
            description: "Percentage Price Oscillator",
            default_params: [
                ("fast_period".to_string(), 12.0),
                ("slow_period".to_string(), 26.0),
                ("signal_period".to_string(), 9.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "wavetrend",
            description: "WaveTrend Oscillator (wt1, wt2)",
            default_params: [
                ("n1".to_string(), 10.0),
                ("n2".to_string(), 21.0),
                ("ob_level".to_string(), 60.0),
                ("os_level".to_string(), -60.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "cmo",
            description: "Chande Momentum Oscillator",
            default_params: [("period".to_string(), 14.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "elder_ray",
            description: "Elder Ray Index (Bull/Bear Power)",
            default_params: [("period".to_string(), 13.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "anchored_vwap",
            description: "Anchored VWAP Engine",
            default_params: [("mult1".to_string(), 1.0), ("mult2".to_string(), 2.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "cvd",
            // Der Name verspricht Kauf- minus Verkaufsvolumen, also die
            // Aggressorseite. Diese Fassung schaetzt sie aus der Bar-Form
            // (`(close - low) / (high - low)`) und sieht keinen einzigen
            // Abschluss an — deshalb `needs_trade_direction: false`, was
            // korrekt ist, aber ohne diesen Zusatz irrefuehrend waere.
            description: "Cumulative Volume Delta (Aufteilung aus der Bar-Form geschätzt, \
                          nicht aus klassifizierten Abschlüssen)",
            default_params: [].into(),
        },
        IndicatorCatalogEntry {
            name: "klinger",
            description: "Klinger Volume Force Oscillator",
            default_params: [
                ("fast_len".to_string(), 34.0),
                ("slow_len".to_string(), 55.0),
                ("signal_len".to_string(), 13.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "zigzag",
            description: "ZigZag Swing Leg Engine",
            default_params: [
                ("depth".to_string(), 12.0),
                ("deviation_pct".to_string(), 5.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "zigzag_advanced",
            description: "ZigZag with backstep, running-leg/confirmation status, and ATR-mode deviation (build_typed with deviation_mode=percent|atr_multiple); AdvancedZigZagEngine::reduce/project_to_timeframe for recursive levels and HTF projection",
            default_params: [
                ("depth".to_string(), 3.0),
                ("backstep".to_string(), 2.0),
                ("deviation_pct".to_string(), 1.0),
                ("atr_len".to_string(), 14.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "pivot_sets",
            description: "Multi-Pivot Set Engine",
            default_params: [].into(),
        },
        IndicatorCatalogEntry {
            name: "tema",
            description: "Triple Exponential Moving Average",
            default_params: [("period".to_string(), 14.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "lsma",
            description: "Least Squares Moving Average / Linear Regression",
            default_params: [("period".to_string(), 25.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "mcginley",
            description: "McGinley Dynamic Moving Average",
            default_params: [("period".to_string(), 14.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "envelope",
            description: "Moving Average Envelopes",
            default_params: [("period".to_string(), 20.0), ("percent".to_string(), 2.5)].into(),
        },
        IndicatorCatalogEntry {
            name: "choppiness",
            description: "Choppiness Index",
            default_params: [("period".to_string(), 14.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "vortex",
            description: "Vortex Indicator (+VI, -VI)",
            default_params: [("period".to_string(), 14.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "alligator",
            description: "Williams Alligator (Jaw, Teeth, Lips)",
            default_params: [].into(),
        },
        IndicatorCatalogEntry {
            name: "connors_rsi",
            description: "Connors RSI",
            default_params: [
                ("rsi_len".to_string(), 3.0),
                ("streak_len".to_string(), 2.0),
                ("rank_len".to_string(), 100.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "coppock",
            description: "Coppock Curve",
            default_params: [].into(),
        },
        IndicatorCatalogEntry {
            name: "dpo",
            description: "Detrended Price Oscillator",
            default_params: [("period".to_string(), 21.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "kst",
            description: "Know Sure Thing Oscillator",
            default_params: [].into(),
        },
        IndicatorCatalogEntry {
            name: "mass_index",
            description: "Mass Index Reversal Detector",
            default_params: [("period".to_string(), 25.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "rvi",
            description: "Relative Vigor Index",
            default_params: [("period".to_string(), 10.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "bop",
            description: "Balance of Power",
            default_params: [("period".to_string(), 14.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "eom",
            description: "Ease of Movement",
            default_params: [
                ("period".to_string(), 14.0),
                ("volume_divisor".to_string(), 10000.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "nvi",
            description: "Negative Volume Index",
            default_params: [].into(),
        },
        IndicatorCatalogEntry {
            name: "pvi",
            description: "Positive Volume Index",
            default_params: [].into(),
        },
        IndicatorCatalogEntry {
            name: "chaikin_oscillator",
            description: "Chaikin Oscillator",
            default_params: [
                ("fast_len".to_string(), 3.0),
                ("slow_len".to_string(), 10.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "bos_choch",
            description: "BOS and CHoCH Market Structure Engine",
            default_params: [("pivot_len".to_string(), 5.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "liquidity_sweeps",
            description: "Liquidity Sweeps and EQH/EQL Detector",
            default_params: [
                ("pivot_len".to_string(), 5.0),
                ("tolerance_pct".to_string(), 0.2),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "liquidity_pools",
            description: "BSL/SSL liquidity pools with explicit stop-hunt/breakout/reclaim classification (see also FvgZoneTracker and SmartMoneyStructureLinker for FVG-fill tracking and cross-detector confluence)",
            default_params: [
                ("pivot_len".to_string(), 5.0),
                ("tolerance_pct".to_string(), 0.2),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "wyckoff",
            description: "Wyckoff accumulation/distribution state machine: range-lock, Phases A-E, Spring/UTAD, SOS/SOW/LPS/LPSY, sequence validation and Cause/Quality scoring",
            default_params: [
                ("range_lookback".to_string(), 20.0),
                ("range_atr_max".to_string(), 3.0),
                ("min_range_bars".to_string(), 6.0),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "trend_quality",
            description: "Trend Quality Score Engine",
            default_params: [("period".to_string(), 14.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "buy_sell_pressure",
            description: "Buy/Sell Pressure Estimator",
            default_params: [("period".to_string(), 14.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "volatility_regime",
            description: "Volatility Regime & Squeeze Detector",
            default_params: [
                ("period".to_string(), 20.0),
                ("bb_mult".to_string(), 2.0),
                ("kc_mult".to_string(), 1.5),
            ]
            .into(),
        },
        IndicatorCatalogEntry {
            name: "zscore",
            description: "Rolling Z-Score Engine",
            default_params: [("period".to_string(), 20.0)].into(),
        },
        IndicatorCatalogEntry {
            name: "multi_factor",
            description: "Multi-Factor Composite Market Score",
            default_params: [("period".to_string(), 14.0)].into(),
        },
    ]
}

/// Der Wertebereich, in dem die Ausgabe eines Indikators liegt.
///
/// Eine Eigenschaft des Indikators, keine Darstellungsvorliebe: Ein RSI ist per Konstruktion auf
/// `0..=100` begrenzt, ein MACD schwankt unbegrenzt um null. Ein Konsument, der eine Achse
/// auslegt, braucht diese Angabe — ohne sie bildet er die Achse aus den zufälligen Extrema des
/// gerade verwendeten Datensatzes und beschriftet Werte, die nichts bedeuten.
///
/// [`OutputRange::Unbounded`] ist die ehrliche Voreinstellung: Sie sagt, dass über den Bereich
/// hier nichts erklärt wird — nicht, dass er unbegrenzt wäre.
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum OutputRange {
    /// Fest begrenzt: Der Wert kann den Bereich konstruktionsbedingt nicht verlassen.
    Bounded { min: f64, max: f64 },
    /// Nach beiden Seiten offen, aber um eine ausgezeichnete Mitte schwankend. Die Mittellinie
    /// trägt die Aussage — ein MACD über null bedeutet etwas anderes als einer darunter.
    Centered { center: f64 },
    /// Nie negativ, nach oben offen: Spannen, Mengen, Verhältnisse.
    NonNegative,
    /// Über den Bereich wird nichts erklärt.
    Unbounded,
}

/// Der Wertebereich der Ausgabe von `name`.
///
/// Deklariert wird nur, was sich aus der Konstruktion des Indikators ergibt. Der Rest bleibt
/// [`OutputRange::Unbounded`] — eine Deklaration auf Verdacht wäre schlechter als keine, weil ein
/// Konsument sie für bare Münze nimmt. `tests/output_range_invariants.rs` prüft jede Angabe hier
/// gegen tatsächliche Läufe, damit sie nicht still veralten kann.
pub fn output_range(name: &str) -> OutputRange {
    // Auf 0..100 normierte Anteilsmaße. `williams_r` gehört hierher und nicht nach -100..0: die
    // Implementierung rechnet `100 * (close - lowest_low) / range`, also in der aufsteigenden
    // Konvention — was auch die Voreinstellungen `oversold: 20` / `overbought: 80` erklärt.
    const PROZENT: OutputRange = OutputRange::Bounded {
        min: 0.0,
        max: 100.0,
    };

    match name {
        "adx"
        | "choppiness"
        | "connors_rsi"
        | "efficiency"
        | "mfi"
        | "relative_volatility"
        | "rsi"
        | "stoch_rsi"
        | "stochastic"
        | "ultimate_oscillator"
        | "williams_r" => PROZENT,

        // Auf -100..100 normierte Differenzmaße. `dmi` gehört hierher und nicht zu den
        // Prozentmaßen: seine Hauptreihe ist `plus_di - minus_di`, die Differenz zweier
        // 0..100-Werte — die einzelnen DI liegen als Nebenreihen darin. `aroon` ebenso: die
        // Hauptreihe ist der Oszillator `up - down`, nicht eine der beiden Linien.
        "aroon" | "cmo" | "dmi" | "rci" | "tsi" => OutputRange::Bounded {
            min: -100.0,
            max: 100.0,
        },

        // Anteilsmaße mit Vorzeichen.
        "bop" | "cmf" => OutputRange::Bounded {
            min: -1.0,
            max: 1.0,
        },

        // Um null schwankend und unbegrenzt: Differenzen, Abweichungen, Transformationen.
        "awesome_oscillator" | "cci" | "chaikin_oscillator" | "coppock" | "dpo" | "efi"
        | "elder_ray" | "eom" | "fisher_transform" | "klinger" | "kst" | "macd" | "ppo" | "roc"
        | "bbtrend" | "pmo" | "smi" | "trix" | "wavetrend" | "zscore" => {
            OutputRange::Centered { center: 0.0 }
        }

        // Spannen, Mengen und Verhältnisse — nie negativ, nach oben offen.
        "atr"
        | "garman_klass"
        | "historical_volatility"
        | "mass_index"
        | "rvat"
        | "rvol"
        | "true_range"
        | "ulcer_index"
        | "vix_fix"
        | "volume"
        | "vortex" => OutputRange::NonNegative,

        _ => OutputRange::Unbounded,
    }
}

/// Die Parameter von `name`, die eine Schwelle im Wertebereich der Ausgabe bezeichnen.
///
/// Als Parameternamen statt als Zahlen: Die Schwelle folgt damit dem, was der Aufrufer eingestellt
/// hat, statt eine zweite Wahrheit daneben zu führen. Ein Konsument, der die Ausgabe zeichnet,
/// findet so die Linien, ohne die Bedeutung einzelner Parameter kennen zu müssen.
pub fn threshold_params(name: &str) -> &'static [&'static str] {
    match name {
        "cci" | "fisher_transform" | "mfi" | "rsi" | "stoch_rsi" | "williams_r" => {
            &["oversold", "overbought"]
        }
        "adx" => &["level_weak"],
        "wavetrend" => &["os_level", "ob_level"],
        _ => &[],
    }
}

impl IndicatorCatalogEntry {
    /// Siehe [`output_range`].
    pub fn output_range(&self) -> OutputRange {
        output_range(self.name)
    }

    /// Die Schwellenwerte dieses Eintrags, aufgelöst über seine Voreinstellungen.
    ///
    /// Aufsteigend sortiert, damit ein Zeichner sie ohne weitere Annahme von unten nach oben
    /// abarbeiten kann.
    pub fn thresholds(&self) -> Vec<f64> {
        let mut werte: Vec<f64> = threshold_params(self.name)
            .iter()
            .filter_map(|p| self.default_params.get(*p).copied())
            .filter(|v| v.is_finite())
            .collect();
        werte.sort_by(|a, b| a.partial_cmp(b).expect("filtered to finite values"));
        werte
    }
}

#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum RegistryError {
    UnknownIndicator(String),
    InvalidParameter {
        parameter: String,
        value: f64,
        reason: String,
    },
    /// A [`ParamValue`] with no numeric equivalent (`Enum`/`Text`/`Timeframe`/`Source`) was
    /// passed to [`build_typed`] for an indicator whose current parameter surface is `f64`-only.
    UnsupportedParameterType {
        parameter: String,
        type_name: String,
    },
    /// A [`ParamValue::Enum`] string did not match any variant accepted for this parameter.
    InvalidEnumValue {
        parameter: String,
        value: String,
        reason: String,
    },
    /// A parameter is a known, supported type but cannot be applied to this specific indicator
    /// (e.g. a non-`Close` `source` on a range/OHLC-dependent indicator — see
    /// [`super::source_mapped::SourceMapped`]'s doc comment for why).
    IncompatibleParameter {
        parameter: String,
        indicator: String,
        reason: String,
    },
}

impl std::fmt::Display for RegistryError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RegistryError::UnknownIndicator(name) => write!(f, "Unknown indicator: {}", name),
            RegistryError::InvalidParameter {
                parameter,
                value,
                reason,
            } => write!(
                f,
                "Invalid parameter '{}' (value {}): {}",
                parameter, value, reason
            ),
            RegistryError::UnsupportedParameterType {
                parameter,
                type_name,
            } => write!(
                f,
                "Parameter '{}' has unsupported type '{}' for this indicator",
                parameter, type_name
            ),
            RegistryError::InvalidEnumValue {
                parameter,
                value,
                reason,
            } => write!(
                f,
                "Invalid value '{}' for parameter '{}': {}",
                value, parameter, reason
            ),
            RegistryError::IncompatibleParameter {
                parameter,
                indicator,
                reason,
            } => write!(
                f,
                "Parameter '{}' is not compatible with indicator '{}': {}",
                parameter, indicator, reason
            ),
        }
    }
}

impl std::error::Error for RegistryError {}

fn get_usize_p(
    params: &HashMap<String, f64>,
    name: &str,
    default: usize,
    min: usize,
    max: usize,
) -> Result<usize, RegistryError> {
    if let Some(&val) = params.get(name) {
        if !val.is_finite() || val.fract() != 0.0 || val < (min as f64) || val > (max as f64) {
            return Err(RegistryError::InvalidParameter {
                parameter: name.to_string(),
                value: val,
                reason: format!(
                    "Value must be a whole, finite number between {} and {}",
                    min, max
                ),
            });
        }
        Ok(val as usize)
    } else {
        Ok(default)
    }
}

fn get_f64_p(
    params: &HashMap<String, f64>,
    name: &str,
    default: f64,
    min: f64,
    max: f64,
) -> Result<f64, RegistryError> {
    if let Some(&val) = params.get(name) {
        if !val.is_finite() || val < min || val > max {
            return Err(RegistryError::InvalidParameter {
                parameter: name.to_string(),
                value: val,
                reason: format!("Value must be a finite number between {} and {}", min, max),
            });
        }
        Ok(val)
    } else {
        Ok(default)
    }
}

/// Reads a `usize` parameter that has a canonical name and a deprecated legacy alias (finding
/// 05): if both are present with different values, that is treated as an ambiguous configuration
/// and rejected rather than silently preferring one; if only one is present, it is validated and
/// used under the canonical name's semantics; if neither is present, `default` applies.
fn get_usize_p_aliased(
    params: &HashMap<String, f64>,
    canonical: &str,
    legacy_alias: &str,
    default: usize,
    min: usize,
    max: usize,
) -> Result<usize, RegistryError> {
    match (params.get(canonical), params.get(legacy_alias)) {
        (Some(&canonical_val), Some(&alias_val)) if canonical_val != alias_val => {
            Err(RegistryError::InvalidParameter {
                parameter: canonical.to_string(),
                value: canonical_val,
                reason: format!(
                    "conflicting values for '{canonical}' ({canonical_val}) and legacy alias \
                     '{legacy_alias}' ({alias_val}); set only one"
                ),
            })
        }
        (Some(_), _) => get_usize_p(params, canonical, default, min, max),
        (None, Some(_)) => get_usize_p(params, legacy_alias, default, min, max),
        (None, None) => Ok(default),
    }
}

fn ensure_less(
    parameter: &str,
    value: f64,
    upper_parameter: &str,
    upper_value: f64,
) -> Result<(), RegistryError> {
    if value < upper_value {
        return Ok(());
    }

    Err(RegistryError::InvalidParameter {
        parameter: parameter.to_string(),
        value,
        reason: format!("{} must be smaller than {}", parameter, upper_parameter),
    })
}

pub fn build_checked(
    name: &str,
    params: &HashMap<String, f64>,
) -> Result<Box<dyn Indicator>, RegistryError> {
    match name.to_lowercase().as_str() {
        "rsi" => Ok(Box::new(build_rsi(params, RsiSmoothing::Wilder)?)),
        "macd" => {
            let fast_len = get_usize_p(params, "fast_len", 12, 1, 10000)?;
            let slow_len = get_usize_p(params, "slow_len", 26, 1, 10000)?;
            let signal_len = get_usize_p(params, "signal_len", 9, 1, 10000)?;
            ensure_less("fast_len", fast_len as f64, "slow_len", slow_len as f64)?;
            Ok(Box::new(Macd::new(fast_len, slow_len, signal_len)))
        }
        "bollinger" | "bb" => Ok(Box::new(build_bollinger(
            params,
            VarianceConvention::Population,
        )?)),
        "adx" => {
            let di_len = get_usize_p(params, "di_len", 14, 1, 10000)?;
            let adx_smooth = get_usize_p(params, "adx_smooth", 14, 1, 10000)?;
            let level_weak = get_f64_p(params, "level_weak", 20.0, 0.0, 100.0)?;
            Ok(Box::new(Adx::new(di_len, adx_smooth, 3, level_weak)))
        }
        "stoch_rsi" | "srsi" => {
            let rsi_len = get_usize_p(params, "rsi_len", 14, 1, 10000)?;
            let stoch_len = get_usize_p(params, "stoch_len", 14, 1, 10000)?;
            let k_len = get_usize_p(params, "k_len", 3, 1, 10000)?;
            let d_len = get_usize_p(params, "d_len", 3, 1, 10000)?;
            let overbought = get_f64_p(params, "overbought", 80.0, 0.0, 100.0)?;
            let oversold = get_f64_p(params, "oversold", 20.0, 0.0, 100.0)?;
            ensure_less("oversold", oversold, "overbought", overbought)?;
            Ok(Box::new(StochRsi::new(
                rsi_len, stoch_len, k_len, d_len, 50.0, overbought, oversold, 5, true, 50, 50, 4,
                10.0,
            )))
        }
        "cci" => {
            let cci_len = get_usize_p(params, "cci_len", 20, 1, 10000)?;
            let overbought = get_f64_p(params, "overbought", 100.0, -1000.0, 1000.0)?;
            let oversold = get_f64_p(params, "oversold", -100.0, -1000.0, 1000.0)?;
            ensure_less("oversold", oversold, "overbought", overbought)?;
            Ok(Box::new(Cci::new(
                cci_len, 3, 3, 5, oversold, overbought, true, 100, 4, 25.0,
            )))
        }
        "mfi" => {
            let mfi_len = get_usize_p(params, "mfi_len", 14, 1, 10000)?;
            let overbought = get_f64_p(params, "overbought", 80.0, 0.0, 100.0)?;
            let oversold = get_f64_p(params, "oversold", 20.0, 0.0, 100.0)?;
            ensure_less("oversold", oversold, "overbought", overbought)?;
            Ok(Box::new(Mfi::new(
                mfi_len, 3, 3, 50.0, overbought, oversold, 5, true,
            )))
        }
        "twap" => {
            let offset = get_f64_p(params, "day_start_offset", 0.0, -86_400.0, 86_400.0)?;
            Ok(Box::new(AnchoredTwap::new(
                TwapAnchor::Daily {
                    start_offset_seconds: offset as i64,
                },
                crate::model::Source::Close,
                TwapWeighting::PerBar,
            )))
        }
        "relative_volatility" => Ok(Box::new(build_relative_volatility(
            params,
            RelativeVolatilityVariant::Close,
        )?)),
        "bbtrend" => Ok(Box::new(build_bbtrend(
            params,
            VarianceConvention::Population,
        )?)),
        "pvt" => Ok(Box::new(PriceVolumeTrend::new())),
        "pmo" => {
            let length_1 = get_usize_p(params, "length_1", 35, 1, 10000)?;
            let length_2 = get_usize_p(params, "length_2", 20, 1, 10000)?;
            let signal_len = get_usize_p(params, "signal_len", 10, 1, 10000)?;
            Ok(Box::new(PriceMomentumOscillator::new(
                length_1, length_2, signal_len,
            )))
        }
        "rvat" => {
            let days = get_usize_p(params, "days", 10, 1, 1000)?;
            let day_start_offset = get_f64_p(params, "day_start_offset", 0.0, -86_400.0, 86_400.0)?;
            let bar_seconds = get_f64_p(params, "bar_seconds", 60.0, 1.0, 86_400.0)?;
            Ok(Box::new(RelativeVolumeAtTime::new(
                days,
                day_start_offset as i64,
                bar_seconds as i64,
            )))
        }
        "smi" => {
            let len = get_usize_p(params, "len", 10, 1, 10000)?;
            let smooth_1 = get_usize_p(params, "smooth_1", 3, 1, 10000)?;
            let smooth_2 = get_usize_p(params, "smooth_2", 3, 1, 10000)?;
            let signal_len = get_usize_p(params, "signal_len", 3, 1, 10000)?;
            Ok(Box::new(StochasticMomentumIndex::new(
                len, smooth_1, smooth_2, signal_len,
            )))
        }
        "rci" => {
            let len = get_usize_p(params, "len", 9, 2, 10000)?;
            Ok(Box::new(RciEngine::new(len)))
        }
        "ulcer_index" => {
            let len = get_usize_p(params, "len", 14, 1, 10000)?;
            Ok(Box::new(UlcerIndexEngine::new(len)))
        }
        "t3" => {
            let period = get_usize_p(params, "period", 5, 1, 10000)?;
            let v = get_f64_p(params, "v", 0.7, 0.0, 1.0)?;
            Ok(Box::new(T3::new(period, v)))
        }
        "vidya" => {
            let cmo_len = get_usize_p(params, "cmo_len", 9, 1, 10000)?;
            let ema_len = get_usize_p(params, "ema_len", 12, 1, 10000)?;
            Ok(Box::new(Vidya::new(cmo_len, ema_len)))
        }
        "trix" => {
            let len = get_usize_p(params, "len", 15, 1, 10000)?;
            let signal_len = get_usize_p(params, "signal_len", 9, 1, 10000)?;
            Ok(Box::new(Trix::new(len, signal_len)))
        }
        "efi" => {
            let ema_len = get_usize_p(params, "ema_len", 13, 1, 10000)?;
            Ok(Box::new(ElderForceIndex::new(ema_len)))
        }
        "atr" => Ok(Box::new(build_atr(params, TrueRangeSmoothing::Rma)?)),
        "chande_kroll" | "cks" => {
            let atr_len = get_usize_p(params, "atr_len", 10, 1, 10000)?;
            let stop_len = get_usize_p(params, "stop_len", 9, 1, 10000)?;
            let mult = get_f64_p(params, "mult", 3.0, 0.01, 100.0)?;
            Ok(Box::new(ChandeKrollStop::new(atr_len, stop_len, mult)))
        }
        "chandelier_exit" | "ce" => {
            let length = get_usize_p(params, "length", 22, 1, 10000)?;
            let atr_mult = get_f64_p(params, "atr_mult", 3.0, 0.01, 100.0)?;
            Ok(Box::new(ChandelierExitEngine::new(length, atr_mult)))
        }
        "chandelier_flip_radar" | "chfr" => {
            let length = get_usize_p(params, "length", 30, 1, 10000)?;
            let atr_mult = get_f64_p(params, "atr_mult", 4.5, 0.01, 100.0)?;
            let body_filter_atr = get_f64_p(params, "body_filter_atr", 0.80, 0.0, 100.0)?;
            let danger_dist_atr = get_f64_p(params, "danger_dist_atr", 0.35, 0.0, 100.0)?;
            let warn_dist_atr = get_f64_p(params, "warn_dist_atr", 0.75, 0.0, 100.0)?;
            // `use_close_extremes`/`simple_adaptive` are fixed to their documented defaults
            // here (true/false) —
            // this f64-only registry surface has no boolean parameter type; use
            // `ChandelierFlipRadarEngine::new` directly to override them.
            Ok(Box::new(ChandelierFlipRadarEngine::new(
                length,
                atr_mult,
                true,
                false,
                body_filter_atr,
                danger_dist_atr,
                warn_dist_atr,
            )))
        }
        "midas" => {
            // Fixed Topfinder/Hlc3 via this f64-only entry point; use `build_typed` with `mode`
            // (ParamValue::Enum) and `source` to select Bottomfinder or another price source.
            let maturity_bars = get_usize_p(params, "maturity_bars", 20, 1, 10000)?;
            Ok(Box::new(MidasCurveEngine::new(
                MidasMode::Topfinder,
                crate::model::Source::Hlc3,
                maturity_bars as u32,
            )))
        }
        "trend_relationship" => {
            // Fixed EMA/EMA via this f64-only entry point; use `build_typed` with
            // `fast_kind`/`slow_kind` (ParamValue::Enum) to select other smoother kinds.
            let fast_len = get_usize_p(params, "fast_len", 9, 1, 10000)?;
            let slow_len = get_usize_p(params, "slow_len", 21, 1, 10000)?;
            ensure_less("fast_len", fast_len as f64, "slow_len", slow_len as f64)?;
            Ok(Box::new(
                super::trend_relationship::AdaptiveTrendRelationship::new(
                    super::smoothing::SmootherKind::Ema,
                    fast_len,
                    super::smoothing::SmootherKind::Ema,
                    slow_len,
                ),
            ))
        }
        "williams_r" | "wpr" => {
            let wpr_len = get_usize_p(params, "wpr_len", 14, 1, 10000)?;
            let overbought = get_f64_p(params, "overbought", 80.0, 0.0, 100.0)?;
            let oversold = get_f64_p(params, "oversold", 20.0, 0.0, 100.0)?;
            ensure_less("oversold", oversold, "overbought", overbought)?;
            Ok(Box::new(WilliamsR::new(
                wpr_len, 3, 3, 50.0, overbought, oversold, 5, true, 50, 4, 10.0,
            )))
        }
        "tsi" => {
            let long_len = get_usize_p(params, "long_len", 25, 1, 10000)?;
            let short_len = get_usize_p(params, "short_len", 13, 1, 10000)?;
            let sig_len = get_usize_p(params, "sig_len", 7, 1, 10000)?;
            ensure_less("short_len", short_len as f64, "long_len", long_len as f64)?;
            Ok(Box::new(Tsi::new(
                long_len, short_len, sig_len, 0.0, 25.0, -25.0, 5, true, 50, 25, 4, 5.0,
            )))
        }
        "fisher_transform" | "fisher" => {
            let fish_len = get_usize_p(params, "fish_len", 10, 1, 10000)?;
            let overbought = get_f64_p(params, "overbought", 1.5, -100.0, 100.0)?;
            let oversold = get_f64_p(params, "oversold", -1.5, -100.0, 100.0)?;
            ensure_less("oversold", oversold, "overbought", overbought)?;
            Ok(Box::new(FisherTransform::new(
                fish_len, 2, 3, 0.0, overbought, oversold, 5, true, 40, 4, 0.5,
            )))
        }
        "order_block" | "ob" => {
            let atr_len = get_usize_p(params, "atr_len", 14, 1, 10000)?;
            let min_disp = get_f64_p(params, "min_disp", 1.0, 0.01, 100.0)?;
            Ok(Box::new(OrderBlockEngine::new(atr_len, min_disp)))
        }
        "liquidity_fvg" | "fvg" | "smc" => {
            let lookback = get_usize_p(params, "lookback", 20, 1, 10000)?;
            Ok(Box::new(LiquidityFvgEngine::new(lookback)))
        }
        "market_structure_breaks" | "bos" | "choch" => {
            let lookback = get_usize_p(params, "lookback", 5, 1, 10000)?;
            Ok(Box::new(MarketStructureBreaksEngine::new(lookback)))
        }
        "pivots_structure" | "pivots" => {
            let left_bars = get_usize_p(params, "left_bars", 5, 1, 10000)?;
            let right_bars = get_usize_p(params, "right_bars", 5, 1, 10000)?;
            let score_window = get_usize_p(params, "score_window", 10, 1, 10000)?;
            Ok(Box::new(PivotStructureEngine::new(
                left_bars,
                right_bars,
                score_window,
            )))
        }
        "volume_profile" | "vp" => {
            let lookback = get_usize_p(params, "lookback", 70, 1, 10000)?;
            let num_bins = get_usize_p(params, "num_bins", 30, 1, 1000)?;
            Ok(Box::new(VolumeProfileEngine::new(lookback, num_bins)))
        }
        "money_flow_profile" | "mfp" => {
            let lookback = get_usize_p(params, "lookback", 200, 1, 10000)?;
            let rows = get_usize_p(params, "rows", 25, 1, 1000)?;
            let va_pct = get_f64_p(params, "va_pct", 0.70, 0.0, 1.0)?;
            Ok(Box::new(MoneyFlowProfileEngine::new(
                lookback, rows, va_pct,
            )))
        }
        "extended_volume_profile" | "vp_extended" => {
            let lookback = get_usize_p(params, "lookback", 70, 1, 10000)?;
            let num_bins = get_usize_p(params, "num_bins", 30, 1, 1000)?;
            Ok(Box::new(ExtendedVolumeProfileEngine::new(
                lookback, num_bins,
            )))
        }
        "persistent_volume_profile" | "vp_persistent" => {
            let lookback = get_usize_p(params, "lookback", 70, 1, 10000)?;
            let bin_width = get_f64_p(params, "bin_width", 1.0, 1e-6, 1_000_000.0)?;
            Ok(Box::new(PersistentVolumeProfileEngine::new(
                lookback, bin_width,
            )))
        }
        "vwap" => {
            let window = get_usize_p(params, "window", 390, 1, 10000)?;
            let slope_lookback = get_usize_p(params, "slope_lookback", 20, 1, 10000)?;
            Ok(Box::new(Vwap::new(window, slope_lookback)))
        }
        "vix_fix" | "wvf" => {
            let pd = get_usize_p(params, "pd", 22, 1, 10000)?;
            let bband_len = get_usize_p(params, "bband_len", 20, 1, 10000)?;
            let mult = get_f64_p(params, "mult", 2.0, 0.01, 100.0)?;
            Ok(Box::new(WilliamsVixFix::new(pd, bband_len, mult)))
        }
        "candle_story" | "pinbar" => {
            let d = CandleStoryConfig::default();
            Ok(Box::new(CandleStoryEngine::with_config(
                CandleStoryConfig {
                    pin_wick_min: get_f64_p(params, "pin_wick_min", d.pin_wick_min, 0.1, 0.95)?,
                    pin_close_pos: get_f64_p(params, "pin_close_pos", d.pin_close_pos, 0.5, 1.0)?,
                    marubozu_body_min: get_f64_p(
                        params,
                        "marubozu_body_min",
                        d.marubozu_body_min,
                        0.5,
                        1.0,
                    )?,
                    belt_hold_body_min: get_f64_p(
                        params,
                        "belt_hold_body_min",
                        d.belt_hold_body_min,
                        0.3,
                        1.0,
                    )?,
                    belt_hold_open_wick_max: get_f64_p(
                        params,
                        "belt_hold_open_wick_max",
                        d.belt_hold_open_wick_max,
                        0.0,
                        0.3,
                    )?,
                    doji_body_max: get_f64_p(params, "doji_body_max", d.doji_body_max, 0.0, 0.4)?,
                    spinning_top_body_max: get_f64_p(
                        params,
                        "spinning_top_body_max",
                        d.spinning_top_body_max,
                        0.05,
                        0.6,
                    )?,
                    hammer_wick_body_min: get_f64_p(
                        params,
                        "hammer_wick_body_min",
                        d.hammer_wick_body_min,
                        0.5,
                        20.0,
                    )?,
                    hammer_opposite_max: get_f64_p(
                        params,
                        "hammer_opposite_max",
                        d.hammer_opposite_max,
                        0.0,
                        5.0,
                    )?,
                    tweezer_tolerance: get_f64_p(
                        params,
                        "tweezer_tolerance",
                        d.tweezer_tolerance,
                        0.0,
                        0.1,
                    )?,
                    min_range_atr: get_f64_p(params, "min_range_atr", d.min_range_atr, 0.0, 10.0)?,
                    atr_len: get_usize_p(params, "atr_len", d.atr_len, 1, 10000)?,
                    trend_lookback: get_usize_p(
                        params,
                        "trend_lookback",
                        d.trend_lookback,
                        1,
                        10000,
                    )?,
                    trend_min_atr: get_f64_p(params, "trend_min_atr", d.trend_min_atr, 0.0, 100.0)?,
                },
            )))
        }
        "efficiency" | "leg_efficiency" | "er" => {
            let len = get_usize_p(params, "len", 14, 1, 10000)?;
            Ok(Box::new(LegEfficiencyEngine::new(len)))
        }
        "volume" => {
            let ma = get_usize_p(params, "ma_period", 20, 1, 10000)?;
            Ok(Box::new(VolumeEngine::new(ma)))
        }
        "rvol" => {
            let p = get_usize_p(params, "period", 20, 1, 10000)?;
            Ok(Box::new(RvolEngine::new(p)))
        }
        "obv" => Ok(Box::new(ObvEngine::new())),
        "cmf" => {
            let p = get_usize_p(params, "period", 20, 1, 10000)?;
            Ok(Box::new(CmfEngine::new(p)))
        }
        "acc_dist" => Ok(Box::new(AccDistEngine::new())),
        "true_range" => Ok(Box::new(TrueRangeEngine::new())),
        "keltner" => {
            // Canonical key is "ema_period" (matches the catalog contract and the EMA base the
            // engine actually uses); "ma_period" is accepted as a legacy alias. See finding 05.
            let ema = get_usize_p_aliased(params, "ema_period", "ma_period", 20, 1, 10000)?;
            let atr = get_usize_p(params, "atr_period", 10, 1, 10000)?;
            let mult = get_f64_p(params, "multiplier", 2.0, 0.01, 100.0)?;
            Ok(Box::new(KeltnerChannelEngine::new(ema, atr, mult)))
        }
        "donchian" => {
            let p = get_usize_p(params, "period", 20, 1, 10000)?;
            Ok(Box::new(DonchianChannelEngine::new(p)))
        }
        "historical_volatility" => {
            let p = get_usize_p(params, "period", 20, 1, 10000)?;
            Ok(Box::new(HistoricalVolatilityEngine::new(p)))
        }
        "garman_klass" => {
            let p = get_usize_p(params, "period", 20, 1, 10000)?;
            Ok(Box::new(GarmanKlassVolatilityEngine::new(p)))
        }
        "sma" => {
            let p = get_usize_p(params, "period", 20, 1, 10000)?;
            Ok(Box::new(SmaEngine::new(p)))
        }
        "ema" => Ok(Box::new(build_ema(params, EmaInit::FirstSample)?)),
        "wma" => {
            let p = get_usize_p(params, "period", 20, 1, 10000)?;
            Ok(Box::new(WmaEngine::new(p)))
        }
        "vwma" => {
            let p = get_usize_p(params, "period", 20, 1, 10000)?;
            Ok(Box::new(VwmaEngine::new(p)))
        }
        "hma" => {
            let p = get_usize_p(params, "period", 20, 1, 10000)?;
            Ok(Box::new(HmaEngine::new(p)))
        }
        "dema" => {
            let p = get_usize_p(params, "period", 20, 1, 10000)?;
            Ok(Box::new(DemaEngine::new(p)))
        }
        "kama" => {
            let p = get_usize_p(params, "period", 10, 1, 10000)?;
            let fast = get_usize_p(params, "fast_period", 2, 1, 10000)?;
            let slow = get_usize_p(params, "slow_period", 30, 1, 10000)?;
            ensure_less("fast_period", fast as f64, "slow_period", slow as f64)?;
            Ok(Box::new(KamaEngine::new(p, fast, slow)))
        }
        "dmi" => {
            let p = get_usize_p(params, "period", 14, 1, 10000)?;
            Ok(Box::new(DmiEngine::new(p)))
        }
        "aroon" => {
            let p = get_usize_p(params, "period", 14, 1, 10000)?;
            Ok(Box::new(AroonEngine::new(p)))
        }
        "parabolic_sar" => {
            let step = get_f64_p(params, "step", 0.02, 0.001, 1.0)?;
            let max_step = get_f64_p(params, "max_step", 0.20, 0.001, 1.0)?;
            if step > max_step {
                return Err(RegistryError::InvalidParameter {
                    parameter: "step".to_string(),
                    value: step,
                    reason: "step must not exceed max_step".to_string(),
                });
            }
            Ok(Box::new(ParabolicSarEngine::new(step, max_step)))
        }
        "supertrend" => {
            let p = get_usize_p(params, "period", 10, 1, 10000)?;
            let mult = get_f64_p(params, "multiplier", 3.0, 0.01, 100.0)?;
            Ok(Box::new(SupertrendEngine::new(p, mult)))
        }
        "ichimoku" => {
            let tenkan = get_usize_p(params, "tenkan_p", 9, 1, 10000)?;
            let kijun = get_usize_p(params, "kijun_p", 26, 1, 10000)?;
            let senkou_b = get_usize_p(params, "senkou_b_p", 52, 1, 10000)?;
            ensure_less("tenkan_p", tenkan as f64, "kijun_p", kijun as f64)?;
            ensure_less("kijun_p", kijun as f64, "senkou_b_p", senkou_b as f64)?;
            Ok(Box::new(IchimokuEngine::new(tenkan, kijun, senkou_b)))
        }
        "stochastic" => {
            let k = get_usize_p(params, "k_period", 14, 1, 10000)?;
            let d = get_usize_p(params, "d_period", 3, 1, 10000)?;
            Ok(Box::new(StochasticEngine::new(k, d)))
        }
        "roc" => {
            let p = get_usize_p(params, "period", 12, 1, 10000)?;
            Ok(Box::new(RocEngine::new(p)))
        }
        "ultimate_oscillator" => {
            let p1 = get_usize_p(params, "period1", 7, 1, 10000)?;
            let p2 = get_usize_p(params, "period2", 14, 1, 10000)?;
            let p3 = get_usize_p(params, "period3", 28, 1, 10000)?;
            ensure_less("period1", p1 as f64, "period2", p2 as f64)?;
            ensure_less("period2", p2 as f64, "period3", p3 as f64)?;
            Ok(Box::new(UltimateOscillatorEngine::new(p1, p2, p3)))
        }
        "awesome_oscillator" => {
            let fast = get_usize_p(params, "fast_period", 5, 1, 10000)?;
            let slow = get_usize_p(params, "slow_period", 34, 1, 10000)?;
            ensure_less("fast_period", fast as f64, "slow_period", slow as f64)?;
            Ok(Box::new(AwesomeOscillatorEngine::new(fast, slow)))
        }
        "ppo" => {
            let fast = get_usize_p(params, "fast_period", 12, 1, 10000)?;
            let slow = get_usize_p(params, "slow_period", 26, 1, 10000)?;
            let signal = get_usize_p(params, "signal_period", 9, 1, 10000)?;
            ensure_less("fast_period", fast as f64, "slow_period", slow as f64)?;
            Ok(Box::new(PpoEngine::new(fast, slow, signal)))
        }
        "wavetrend" | "wt" => {
            let n1 = get_usize_p(params, "n1", 10, 1, 10000)?;
            let n2 = get_usize_p(params, "n2", 21, 1, 10000)?;
            let ob = get_f64_p(params, "ob_level", 60.0, -100.0, 100.0)?;
            let os = get_f64_p(params, "os_level", -60.0, -100.0, 100.0)?;
            Ok(Box::new(WaveTrendEngine::new(n1, n2, ob, os)))
        }
        "cmo" => {
            let p = get_usize_p(params, "period", 14, 1, 10000)?;
            Ok(Box::new(CmoEngine::new(p)))
        }
        "elder_ray" => {
            let p = get_usize_p(params, "period", 13, 1, 10000)?;
            Ok(Box::new(ElderRayEngine::new(p)))
        }
        "anchored_vwap" | "avwap" => {
            let m1 = get_f64_p(params, "mult1", 1.0, 0.01, 100.0)?;
            let m2 = get_f64_p(params, "mult2", 2.0, 0.01, 100.0)?;
            Ok(Box::new(AnchoredVwapEngine::new(
                VwapAnchorKind::Session,
                m1,
                m2,
            )))
        }
        "cvd" => Ok(Box::new(CvdEngine::new())),
        "hires_volume_flow" => {
            let window_len = get_usize_p(params, "window_len", 20, 2, 10000)?;
            Ok(Box::new(HiResVolumeFlowEngine::new(window_len)))
        }
        "klinger" | "kvo" => {
            let fast = get_usize_p(params, "fast_len", 34, 1, 10000)?;
            let slow = get_usize_p(params, "slow_len", 55, 1, 10000)?;
            let sig = get_usize_p(params, "signal_len", 13, 1, 10000)?;
            ensure_less("fast_len", fast as f64, "slow_len", slow as f64)?;
            Ok(Box::new(KlingerVolumeForceEngine::new(fast, slow, sig)))
        }
        "zigzag" => {
            let depth = get_usize_p(params, "depth", 12, 2, 10000)?;
            let dev = get_f64_p(params, "deviation_pct", 5.0, 0.01, 100.0)?;
            Ok(Box::new(ZigZagEngine::new(depth, dev)))
        }
        "zigzag_advanced" => {
            // Fixed Percent deviation via this f64-only entry point; use `build_typed` with
            // `deviation_mode` (ParamValue::Enum) to select AtrMultiple instead.
            let depth = get_usize_p(params, "depth", 3, 1, 10000)?;
            let backstep = get_usize_p(params, "backstep", 2, 0, 10000)?;
            let deviation_pct = get_f64_p(params, "deviation_pct", 1.0, 0.001, 100.0)?;
            let atr_len = get_usize_p(params, "atr_len", 14, 1, 10000)?;
            Ok(Box::new(AdvancedZigZagEngine::new(
                depth,
                backstep,
                ZigZagDeviationMode::Percent(deviation_pct),
                atr_len,
            )))
        }
        "pivot_sets" | "multi_pivots" => Ok(Box::new(PivotSetsEngine::new(PivotSetType::Classic))),
        "tema" => {
            let p = get_usize_p(params, "period", 14, 1, 10000)?;
            Ok(Box::new(TemaEngine::new(p)))
        }
        "lsma" => {
            let p = get_usize_p(params, "period", 25, 2, 10000)?;
            Ok(Box::new(LsmaEngine::new(p)))
        }
        "mcginley" => {
            let p = get_usize_p(params, "period", 14, 1, 10000)?;
            Ok(Box::new(McGinleyDynamicEngine::new(p)))
        }
        "envelope" => {
            let p = get_usize_p(params, "period", 20, 1, 10000)?;
            let pct = get_f64_p(params, "percent", 2.5, 0.01, 100.0)?;
            Ok(Box::new(EnvelopeEngine::new(p, pct)))
        }
        "choppiness" | "chop" => {
            let p = get_usize_p(params, "period", 14, 2, 10000)?;
            Ok(Box::new(ChoppinessIndexEngine::new(p)))
        }
        "vortex" | "vi" => {
            let p = get_usize_p(params, "period", 14, 1, 10000)?;
            Ok(Box::new(VortexEngine::new(p)))
        }
        "alligator" => Ok(Box::new(AlligatorEngine::new())),
        "connors_rsi" => {
            let rsi_len = get_usize_p(params, "rsi_len", 3, 1, 10000)?;
            let streak_len = get_usize_p(params, "streak_len", 2, 1, 10000)?;
            let rank_len = get_usize_p(params, "rank_len", 100, 1, 10000)?;
            Ok(Box::new(ConnorsRsiEngine::new(
                rsi_len, streak_len, rank_len,
            )))
        }
        "coppock" => Ok(Box::new(CoppockCurveEngine::new())),
        "dpo" => {
            let p = get_usize_p(params, "period", 21, 2, 10000)?;
            Ok(Box::new(DpoEngine::new(p)))
        }
        "kst" => Ok(Box::new(KstEngine::new())),
        "mass_index" => {
            let p = get_usize_p(params, "period", 25, 1, 10000)?;
            Ok(Box::new(MassIndexEngine::new(p)))
        }
        "rvi" => {
            let p = get_usize_p(params, "period", 10, 1, 10000)?;
            Ok(Box::new(RviEngine::new(p)))
        }
        "bop" => {
            let p = get_usize_p(params, "period", 14, 1, 10000)?;
            Ok(Box::new(BalanceOfPowerEngine::new(p)))
        }
        "eom" => {
            let p = get_usize_p(params, "period", 14, 1, 10000)?;
            let div = get_f64_p(params, "volume_divisor", 10000.0, 1.0, 1e9)?;
            Ok(Box::new(EomEngine::new(p, div)))
        }
        "nvi" => Ok(Box::new(NviEngine::new())),
        "pvi" => Ok(Box::new(PviEngine::new())),
        "chaikin_oscillator" | "cho" => {
            let fast = get_usize_p(params, "fast_len", 3, 1, 10000)?;
            let slow = get_usize_p(params, "slow_len", 10, 1, 10000)?;
            ensure_less("fast_len", fast as f64, "slow_len", slow as f64)?;
            Ok(Box::new(ChaikinOscillatorEngine::new(fast, slow)))
        }
        "bos_choch" => {
            let pivot_len = get_usize_p(params, "pivot_len", 5, 2, 10000)?;
            Ok(Box::new(BosChochEngine::new(pivot_len)))
        }
        "liquidity_sweeps" | "sweeps" => {
            let p = get_usize_p(params, "pivot_len", 5, 2, 10000)?;
            let tol = get_f64_p(params, "tolerance_pct", 0.2, 0.01, 100.0)?;
            Ok(Box::new(LiquiditySweepEngine::new(p, tol)))
        }
        "liquidity_pools" => {
            let p = get_usize_p(params, "pivot_len", 5, 2, 10000)?;
            let tol = get_f64_p(params, "tolerance_pct", 0.2, 0.001, 100.0)?;
            Ok(Box::new(
                super::smart_money_structure::LiquidityPoolEngine::new(p, tol),
            ))
        }
        "wyckoff" => {
            let lookback = get_usize_p(params, "range_lookback", 20, 3, 10000)?;
            let atr_max = get_f64_p(params, "range_atr_max", 3.0, 0.1, 1000.0)?;
            let min_bars = get_usize_p(params, "min_range_bars", 6, 2, 10000)?;
            Ok(Box::new(super::wyckoff::WyckoffStateMachine::new(
                lookback, atr_max, min_bars,
            )))
        }
        "trend_quality" => {
            let p = get_usize_p(params, "period", 14, 2, 10000)?;
            Ok(Box::new(TrendQualityScoreEngine::new(p)))
        }
        "buy_sell_pressure" | "pressure" => {
            let p = get_usize_p(params, "period", 14, 1, 10000)?;
            Ok(Box::new(BuySellPressureEstimator::new(p)))
        }
        "volatility_regime" => {
            let p = get_usize_p(params, "period", 20, 1, 10000)?;
            let bb_mult = get_f64_p(params, "bb_mult", 2.0, 0.01, 100.0)?;
            let kc_mult = get_f64_p(params, "kc_mult", 1.5, 0.01, 100.0)?;
            Ok(Box::new(VolatilityRegimeDetector::new(p, bb_mult, kc_mult)))
        }
        "zscore" => {
            let p = get_usize_p(params, "period", 20, 2, 10000)?;
            Ok(Box::new(ZScoreEngine::new(p)))
        }
        "multi_factor" => {
            let p = get_usize_p(params, "period", 14, 2, 10000)?;
            Ok(Box::new(MultiFactorMarketScore::new(p)))
        }
        _ => Err(RegistryError::UnknownIndicator(name.to_string())),
    }
}

/// Dynamically builds an `Indicator` instance by its catalog name and parameters.
/// Delegates to `build_checked` and discards errors to return `Option`.
pub fn build(name: &str, params: &HashMap<String, f64>) -> Option<Box<dyn Indicator>> {
    build_checked(name, params).ok()
}

/// Builds an `Indicator` instance from typed parameters (see [`ParamValue`]).
///
/// Numeric-compatible values (`Float`, `Int`, `Bool`, `Timestamp`) are flattened to `f64` and
/// forwarded to [`build_checked`], reusing its full per-indicator validation. Values with no
/// scalar form (`Enum`, `Text`, `Timeframe`, `Source`) are rejected with
/// [`RegistryError::UnsupportedParameterType`], since no indicator in this registry currently
/// consumes them through the `f64` parameter map.
/// Indicators known to depend on the genuine OHLC range (true range, high/low pivots, volume-at-
/// price, market-structure detection, ...), for which [`super::source_mapped::SourceMapped`]
/// would silently collapse `high == low == open == close` to the selected source and degenerate
/// their math. `build_typed` rejects a non-`Close` `source` for these rather than silently
/// applying it. Not necessarily exhaustive over the full catalog — extend as new range-dependent
/// indicators are added.
const RANGE_DEPENDENT_INDICATORS: &[&str] = &[
    "atr",
    "relative_volatility",
    "smi",
    "chande_kroll",
    "cks",
    "true_range",
    "adx",
    "dmi",
    "chandelier_exit",
    "chandelier_flip_radar",
    "chfr",
    "wyckoff",
    "volume_profile",
    "vp",
    "money_flow_profile",
    "mfp",
    "extended_volume_profile",
    "vp_extended",
    "persistent_volume_profile",
    "vp_persistent",
    "pivots_structure",
    "pivots",
    "pivot_sets",
    "multi_pivots",
    "zigzag",
    "zigzag_advanced",
    "liquidity_pools",
    "liquidity_sweeps",
    "sweeps",
    "liquidity_fvg",
    "fvg",
    "smc",
    "order_block",
    "ob",
    "ce",
    "bos_choch",
    "market_structure_breaks",
    "bos",
    "choch",
    "vix_fix",
    "wvf",
    "keltner",
    "donchian",
    "vortex",
    "vi",
    "choppiness",
    "chop",
    "mass_index",
    "supertrend",
    "parabolic_sar",
    "ichimoku",
    "aroon",
    "garman_klass",
    "hires_volume_flow",
    "cvd",
    "klinger",
    "kvo",
    "volatility_regime",
    "swing_structure",
];

/// Indicators whose price source is fixed by an explicit decision rather than by their math:
/// `SourceMapped` would compute a differently-defined series under the same name. `efi` weighs a
/// close-to-close change by the bar's volume; pairing that volume with a derived price (hlc3,
/// ohlc4, ...) needs its own documented contract before it is offered.
const SOURCE_FIXED_INDICATORS: &[&str] = &["efi"];

pub fn build_typed(name: &str, params: &TypedParams) -> Result<Box<dyn Indicator>, RegistryError> {
    if name.to_lowercase() == "midas" {
        // Bypasses the generic `source` handling below; see `build_midas_typed`.
        return build_midas_typed(params);
    }

    let source = match params.get("source") {
        None => None,
        Some(ParamValue::Source(s)) => Some(*s),
        Some(other) => {
            return Err(RegistryError::UnsupportedParameterType {
                parameter: "source".to_string(),
                type_name: other.type_name().to_string(),
            });
        }
    };

    if let Some(s) = source {
        if s != crate::model::Source::Close
            && SOURCE_FIXED_INDICATORS.contains(&name.to_lowercase().as_str())
        {
            return Err(RegistryError::IncompatibleParameter {
                parameter: "source".to_string(),
                indicator: name.to_string(),
                reason: "price source is fixed to the close by contract; another source would \
                         redefine the series under the same name"
                    .to_string(),
            });
        }

        if s != crate::model::Source::Close
            && RANGE_DEPENDENT_INDICATORS.contains(&name.to_lowercase().as_str())
        {
            return Err(RegistryError::IncompatibleParameter {
                parameter: "source".to_string(),
                indicator: name.to_string(),
                reason: "range/OHLC-dependent indicator; SourceMapped would collapse its true range to zero"
                    .to_string(),
            });
        }
    }

    // `source` is a cross-cutting concern applied uniformly via `SourceMapped` below, not an
    // indicator-specific parameter, so it is stripped before delegating to the per-indicator
    // builders.
    let mut remaining = params.clone();
    remaining.remove("source");

    let built = match name.to_lowercase().as_str() {
        "anchored_vwap" | "avwap" => build_anchored_vwap_typed(&remaining)?,
        "atr" => build_atr_typed(&remaining)?,
        "ema" => build_ema_typed(&remaining)?,
        "rsi" => build_rsi_typed(&remaining)?,
        "bbtrend" => build_bbtrend_typed(&remaining)?,
        "relative_volatility" => build_relative_volatility_typed(&remaining)?,
        "twap" => build_twap_typed(&remaining, source)?,
        "bollinger" | "bb" => build_bollinger_typed(&remaining)?,
        "pivot_sets" | "multi_pivots" => build_pivot_sets_typed(&remaining)?,
        "trend_relationship" => build_trend_relationship_typed(&remaining)?,
        "zigzag_advanced" => build_zigzag_advanced_typed(&remaining)?,
        _ => build_typed_by_flattening(name, &remaining)?,
    };

    Ok(match source {
        Some(s) if s != crate::model::Source::Close => {
            Box::new(super::source_mapped::SourceMapped::new(built, s))
        }
        _ => built,
    })
}

/// Default typed-build strategy for indicators whose full configuration surface is numeric:
/// flattens every value to `f64` via [`ParamValue::as_f64`] and delegates to [`build_checked`],
/// reusing its per-indicator validation. Rejects any value with no scalar form.
fn build_typed_by_flattening(
    name: &str,
    params: &TypedParams,
) -> Result<Box<dyn Indicator>, RegistryError> {
    build_checked(name, &flatten_typed(params)?)
}

/// Flattens every entry to `f64`, rejecting values with no scalar form. Used both by
/// [`build_typed_by_flattening`] and by the per-indicator typed builders, which read their own
/// enum parameters first and then hand the numeric remainder to the same `build_checked`
/// validation as the `f64`-only surface.
fn flatten_typed(params: &TypedParams) -> Result<HashMap<String, f64>, RegistryError> {
    let mut flat = HashMap::with_capacity(params.len());
    for (key, value) in params {
        match value.as_f64() {
            Some(v) => {
                flat.insert(key.clone(), v);
            }
            None => {
                return Err(RegistryError::UnsupportedParameterType {
                    parameter: key.clone(),
                    type_name: value.type_name().to_string(),
                });
            }
        }
    }
    Ok(flat)
}

/// The numeric part of an ATR configuration; see [`build_rsi`] for why this is shared.
fn build_atr(
    params: &HashMap<String, f64>,
    smoothing: TrueRangeSmoothing,
) -> Result<Atr, RegistryError> {
    let atr_len = get_usize_p(params, "atr_len", 14, 1, 10000)?;
    let sig_len = get_usize_p(params, "sig_len", 20, 1, 10000)?;
    Ok(Atr::new(atr_len, sig_len).with_smoothing(smoothing))
}

fn build_atr_typed(params: &TypedParams) -> Result<Box<dyn Indicator>, RegistryError> {
    let smoothing = match get_enum_p(params, "smoothing")?.as_deref() {
        None | Some("rma") => TrueRangeSmoothing::Rma,
        Some("sma") => TrueRangeSmoothing::Sma,
        Some("ema") => TrueRangeSmoothing::Ema,
        Some("wma") => TrueRangeSmoothing::Wma,
        Some(other) => {
            return Err(RegistryError::InvalidEnumValue {
                parameter: "smoothing".to_string(),
                value: other.to_string(),
                reason: "expected one of rma|sma|ema|wma".to_string(),
            });
        }
    };

    let mut numeric = params.clone();
    numeric.remove("smoothing");
    Ok(Box::new(build_atr(&flatten_typed(&numeric)?, smoothing)?))
}

/// The numeric part of an EMA configuration; see [`build_rsi`] for why this is shared.
fn build_ema(params: &HashMap<String, f64>, init: EmaInit) -> Result<EmaEngine, RegistryError> {
    let period = get_usize_p(params, "period", 20, 1, 10000)?;
    Ok(EmaEngine::new(period).with_init(init))
}

fn build_ema_typed(params: &TypedParams) -> Result<Box<dyn Indicator>, RegistryError> {
    let init = match get_enum_p(params, "init")?.as_deref() {
        None | Some("first_sample") => EmaInit::FirstSample,
        Some("sma") => EmaInit::Sma,
        Some(other) => {
            return Err(RegistryError::InvalidEnumValue {
                parameter: "init".to_string(),
                value: other.to_string(),
                reason: "expected one of first_sample|sma".to_string(),
            });
        }
    };

    let mut numeric = params.clone();
    numeric.remove("init");
    Ok(Box::new(build_ema(&flatten_typed(&numeric)?, init)?))
}

/// TWAP takes its own price source rather than being wrapped in `SourceMapped`: the wrapper
/// flattens a bar to one value, which would make a duration-weighted average of a flattened bar
/// series — the same number, but arrived at in a way that hides what was averaged.
fn build_twap_typed(
    params: &TypedParams,
    source: Option<crate::model::Source>,
) -> Result<Box<dyn Indicator>, RegistryError> {
    let weighting = match get_enum_p(params, "weighting")?.as_deref() {
        None | Some("per_bar") => TwapWeighting::PerBar,
        Some("by_duration") => TwapWeighting::ByDuration,
        Some(other) => {
            return Err(RegistryError::InvalidEnumValue {
                parameter: "weighting".to_string(),
                value: other.to_string(),
                reason: "expected one of per_bar|by_duration".to_string(),
            });
        }
    };

    let numeric = extract_numeric_subset(params, &["day_start_offset"])?;
    let offset = get_f64_p(&numeric, "day_start_offset", 0.0, -86_400.0, 86_400.0)? as i64;

    let anchor = match get_enum_p(params, "anchor")?.as_deref() {
        None | Some("daily") => TwapAnchor::Daily {
            start_offset_seconds: offset,
        },
        Some("continuous") => TwapAnchor::Continuous,
        Some("manual_timestamp") => {
            let timestamp = get_timestamp_p(params, "anchor_timestamp")?.ok_or_else(|| {
                RegistryError::InvalidEnumValue {
                    parameter: "anchor".to_string(),
                    value: "manual_timestamp".to_string(),
                    reason: "requires an accompanying 'anchor_timestamp' Timestamp parameter"
                        .to_string(),
                }
            })?;
            TwapAnchor::ManualTimestamp(timestamp)
        }
        Some(other) => {
            return Err(RegistryError::InvalidEnumValue {
                parameter: "anchor".to_string(),
                value: other.to_string(),
                reason: "expected one of continuous|daily|manual_timestamp".to_string(),
            });
        }
    };

    Ok(Box::new(AnchoredTwap::new(
        anchor,
        source.unwrap_or(crate::model::Source::Close),
        weighting,
    )))
}

/// The numeric part of a Relative Volatility configuration; the variant selects which prices are
/// measured.
fn build_relative_volatility(
    params: &HashMap<String, f64>,
    variant: RelativeVolatilityVariant,
) -> Result<RelativeVolatilityIndex, RegistryError> {
    let stdev_len = get_usize_p(params, "stdev_len", 10, 2, 10000)?;
    let smooth_len = get_usize_p(params, "smooth_len", 14, 1, 10000)?;
    Ok(RelativeVolatilityIndex::new(stdev_len, smooth_len, variant))
}

fn build_relative_volatility_typed(
    params: &TypedParams,
) -> Result<Box<dyn Indicator>, RegistryError> {
    let variant = match get_enum_p(params, "variant")?.as_deref() {
        None | Some("close") => RelativeVolatilityVariant::Close,
        Some("high_low") => RelativeVolatilityVariant::HighLow,
        Some(other) => {
            return Err(RegistryError::InvalidEnumValue {
                parameter: "variant".to_string(),
                value: other.to_string(),
                reason: "expected one of close|high_low".to_string(),
            });
        }
    };

    let mut numeric = params.clone();
    numeric.remove("variant");
    Ok(Box::new(build_relative_volatility(
        &flatten_typed(&numeric)?,
        variant,
    )?))
}

/// The numeric part of a BBTrend configuration; the variance convention applies to both band
/// sets, since comparing sets built on different conventions would measure the convention.
fn build_bbtrend(
    params: &HashMap<String, f64>,
    variance: VarianceConvention,
) -> Result<BbTrend, RegistryError> {
    let short_len = get_usize_p(params, "short_len", 20, 1, 10000)?;
    let long_len = get_usize_p(params, "long_len", 50, 1, 10000)?;
    let mult = get_f64_p(params, "mult", 2.0, 0.01, 100.0)?;
    ensure_less("short_len", short_len as f64, "long_len", long_len as f64)?;
    if variance == VarianceConvention::Sample && short_len < 2 {
        return Err(RegistryError::IncompatibleParameter {
            parameter: "variance".to_string(),
            indicator: "bbtrend".to_string(),
            reason: "sample variance divides by len - 1 and is undefined for len < 2".to_string(),
        });
    }
    Ok(BbTrend::new(short_len, long_len, mult, variance))
}

fn build_bbtrend_typed(params: &TypedParams) -> Result<Box<dyn Indicator>, RegistryError> {
    let variance = match get_enum_p(params, "variance")?.as_deref() {
        None | Some("population") => VarianceConvention::Population,
        Some("sample") => VarianceConvention::Sample,
        Some(other) => {
            return Err(RegistryError::InvalidEnumValue {
                parameter: "variance".to_string(),
                value: other.to_string(),
                reason: "expected one of population|sample".to_string(),
            });
        }
    };

    let mut numeric = params.clone();
    numeric.remove("variance");
    Ok(Box::new(build_bbtrend(
        &flatten_typed(&numeric)?,
        variance,
    )?))
}

/// The numeric part of an RSI configuration, shared by the `f64`-only and the typed surface so
/// both validate identically and only the smoothing method differs.
fn build_rsi(params: &HashMap<String, f64>, smoothing: RsiSmoothing) -> Result<Rsi, RegistryError> {
    let rsi_len = get_usize_p(params, "rsi_len", 14, 1, 10000)?;
    let avg_len = get_usize_p(params, "avg_len", 3, 1, 10000)?;
    let sig_len = get_usize_p(params, "sig_len", 3, 1, 10000)?;
    let overbought = get_f64_p(params, "overbought", 70.0, 0.0, 100.0)?;
    let oversold = get_f64_p(params, "oversold", 30.0, 0.0, 100.0)?;
    ensure_less("oversold", oversold, "overbought", overbought)?;
    Ok(Rsi::new(
        rsi_len, avg_len, sig_len, 50.0, overbought, oversold, 5, true, 100, 4, 10.0,
    )
    .with_smoothing(smoothing))
}

fn build_rsi_typed(params: &TypedParams) -> Result<Box<dyn Indicator>, RegistryError> {
    let smoothing = match get_enum_p(params, "smoothing")?.as_deref() {
        None | Some("wilder") => RsiSmoothing::Wilder,
        Some("ema") => RsiSmoothing::Ema,
        Some(other) => {
            return Err(RegistryError::InvalidEnumValue {
                parameter: "smoothing".to_string(),
                value: other.to_string(),
                reason: "expected one of wilder|ema".to_string(),
            });
        }
    };

    let mut numeric = params.clone();
    numeric.remove("smoothing");
    Ok(Box::new(build_rsi(&flatten_typed(&numeric)?, smoothing)?))
}

/// The numeric part of a Bollinger configuration; see [`build_rsi`] for why this is shared.
fn build_bollinger(
    params: &HashMap<String, f64>,
    variance: VarianceConvention,
) -> Result<BollingerBands, RegistryError> {
    let len = get_usize_p(params, "len", 20, 1, 10000)?;
    let mult = get_f64_p(params, "mult", 2.0, 0.01, 100.0)?;
    if variance == VarianceConvention::Sample && len < 2 {
        return Err(RegistryError::IncompatibleParameter {
            parameter: "variance".to_string(),
            indicator: "bollinger".to_string(),
            reason: "sample variance divides by len - 1 and is undefined for len < 2".to_string(),
        });
    }
    Ok(BollingerBands::new(len, mult).with_variance(variance))
}

fn build_bollinger_typed(params: &TypedParams) -> Result<Box<dyn Indicator>, RegistryError> {
    let variance = match get_enum_p(params, "variance")?.as_deref() {
        None | Some("population") => VarianceConvention::Population,
        Some("sample") => VarianceConvention::Sample,
        Some(other) => {
            return Err(RegistryError::InvalidEnumValue {
                parameter: "variance".to_string(),
                value: other.to_string(),
                reason: "expected one of population|sample".to_string(),
            });
        }
    };

    let mut numeric = params.clone();
    numeric.remove("variance");
    Ok(Box::new(build_bollinger(
        &flatten_typed(&numeric)?,
        variance,
    )?))
}

/// Reads a `ParamValue::Enum` parameter, lower-cased. Returns `Ok(None)` if the key is absent, and
/// [`RegistryError::UnsupportedParameterType`] if present with a non-`Enum` type.
fn get_enum_p(params: &TypedParams, name: &str) -> Result<Option<String>, RegistryError> {
    match params.get(name) {
        None => Ok(None),
        Some(ParamValue::Enum(value)) => Ok(Some(value.to_lowercase())),
        Some(other) => Err(RegistryError::UnsupportedParameterType {
            parameter: name.to_string(),
            type_name: other.type_name().to_string(),
        }),
    }
}

/// Reads a `ParamValue::Timestamp` parameter. Returns `Ok(None)` if the key is absent, and
/// [`RegistryError::UnsupportedParameterType`] if present with a non-`Timestamp` type.
fn get_timestamp_p(params: &TypedParams, name: &str) -> Result<Option<i64>, RegistryError> {
    match params.get(name) {
        None => Ok(None),
        Some(ParamValue::Timestamp(value)) => Ok(Some(*value)),
        Some(other) => Err(RegistryError::UnsupportedParameterType {
            parameter: name.to_string(),
            type_name: other.type_name().to_string(),
        }),
    }
}

/// Extracts the numeric-compatible entries of `keys` from `params` into a fresh `f64` map, for
/// forwarding to the existing `get_f64_p`/`get_usize_p` validators.
fn extract_numeric_subset(
    params: &TypedParams,
    keys: &[&str],
) -> Result<HashMap<String, f64>, RegistryError> {
    let mut numeric = HashMap::new();
    for key in keys {
        if let Some(value) = params.get(*key) {
            match value.as_f64() {
                Some(v) => {
                    numeric.insert((*key).to_string(), v);
                }
                None => {
                    return Err(RegistryError::UnsupportedParameterType {
                        parameter: (*key).to_string(),
                        type_name: value.type_name().to_string(),
                    });
                }
            }
        }
    }
    Ok(numeric)
}

fn build_anchored_vwap_typed(params: &TypedParams) -> Result<Box<dyn Indicator>, RegistryError> {
    let anchor_kind = match get_enum_p(params, "anchor_kind")?.as_deref() {
        None | Some("session") => VwapAnchorKind::Session,
        Some("day") => VwapAnchorKind::Day,
        Some("week") => VwapAnchorKind::Week,
        Some("month") => VwapAnchorKind::Month,
        Some("external") => VwapAnchorKind::External,
        Some("manual_timestamp") => {
            let ts = get_timestamp_p(params, "anchor_timestamp")?.ok_or_else(|| {
                RegistryError::InvalidEnumValue {
                    parameter: "anchor_kind".to_string(),
                    value: "manual_timestamp".to_string(),
                    reason: "requires an accompanying 'anchor_timestamp' Timestamp parameter"
                        .to_string(),
                }
            })?;
            VwapAnchorKind::ManualTimestamp(ts)
        }
        Some(other) => {
            return Err(RegistryError::InvalidEnumValue {
                parameter: "anchor_kind".to_string(),
                value: other.to_string(),
                reason: "expected one of session|day|week|month|external|manual_timestamp"
                    .to_string(),
            });
        }
    };

    let zero_volume_policy = match get_enum_p(params, "zero_volume_policy")?.as_deref() {
        None | Some("equal_weight") => ZeroVolumePolicy::EqualWeight,
        Some("skip") => ZeroVolumePolicy::Skip,
        Some(other) => {
            return Err(RegistryError::InvalidEnumValue {
                parameter: "zero_volume_policy".to_string(),
                value: other.to_string(),
                reason: "expected one of equal_weight|skip".to_string(),
            });
        }
    };

    let numeric = extract_numeric_subset(params, &["mult1", "mult2"])?;
    let m1 = get_f64_p(&numeric, "mult1", 1.0, 0.01, 100.0)?;
    let m2 = get_f64_p(&numeric, "mult2", 2.0, 0.01, 100.0)?;

    Ok(Box::new(
        AnchoredVwapEngine::new(anchor_kind, m1, m2).with_zero_volume_policy(zero_volume_policy),
    ))
}

fn build_pivot_sets_typed(params: &TypedParams) -> Result<Box<dyn Indicator>, RegistryError> {
    let pivot_type = match get_enum_p(params, "pivot_type")?.as_deref() {
        None | Some("classic") => PivotSetType::Classic,
        Some("fibonacci") => PivotSetType::Fibonacci,
        Some("camarilla") => PivotSetType::Camarilla,
        Some("woodie") => PivotSetType::Woodie,
        Some("demark") => PivotSetType::DeMark,
        Some("cpr") => PivotSetType::Cpr,
        Some(other) => {
            return Err(RegistryError::InvalidEnumValue {
                parameter: "pivot_type".to_string(),
                value: other.to_string(),
                reason: "expected one of classic|fibonacci|camarilla|woodie|demark|cpr".to_string(),
            });
        }
    };

    Ok(Box::new(PivotSetsEngine::new(pivot_type)))
}

fn parse_smoother_kind(
    params: &TypedParams,
    parameter_name: &str,
    default: super::smoothing::SmootherKind,
) -> Result<super::smoothing::SmootherKind, RegistryError> {
    use super::smoothing::SmootherKind;

    match get_enum_p(params, parameter_name)?.as_deref() {
        None => Ok(default),
        Some("ema") => Ok(SmootherKind::Ema),
        Some("sma") => Ok(SmootherKind::Sma),
        Some("rma") => Ok(SmootherKind::Rma),
        Some("alma") => Ok(SmootherKind::Alma),
        Some("jma") => Ok(SmootherKind::Jma),
        Some(other) => Err(RegistryError::InvalidEnumValue {
            parameter: parameter_name.to_string(),
            value: other.to_string(),
            reason: "expected one of ema|sma|rma|alma|jma".to_string(),
        }),
    }
}

/// Builds a MIDAS engine directly from typed params, bypassing the generic `source`
/// strip-then-`SourceMapped`-wrap path in [`build_typed`]: MIDAS needs its own `Source` for the
/// cumulative curve while still reading genuine `bar.high`/`bar.low` for Topfinder/Bottomfinder
/// extreme tracking, which a bar flattened to a single OHLC value (what `SourceMapped` produces)
/// would break.
fn build_midas_typed(params: &TypedParams) -> Result<Box<dyn Indicator>, RegistryError> {
    let mode = match get_enum_p(params, "mode")?.as_deref() {
        None | Some("topfinder") => MidasMode::Topfinder,
        Some("bottomfinder") => MidasMode::Bottomfinder,
        Some(other) => {
            return Err(RegistryError::InvalidEnumValue {
                parameter: "mode".to_string(),
                value: other.to_string(),
                reason: "expected one of topfinder|bottomfinder".to_string(),
            });
        }
    };

    let source = match params.get("source") {
        None => crate::model::Source::Hlc3,
        Some(ParamValue::Source(s)) => *s,
        Some(other) => {
            return Err(RegistryError::UnsupportedParameterType {
                parameter: "source".to_string(),
                type_name: other.type_name().to_string(),
            });
        }
    };

    let numeric = extract_numeric_subset(params, &["maturity_bars"])?;
    let maturity_bars = get_usize_p(&numeric, "maturity_bars", 20, 1, 10000)?;

    Ok(Box::new(MidasCurveEngine::new(
        mode,
        source,
        maturity_bars as u32,
    )))
}

fn build_zigzag_advanced_typed(params: &TypedParams) -> Result<Box<dyn Indicator>, RegistryError> {
    let numeric =
        extract_numeric_subset(params, &["depth", "backstep", "deviation_value", "atr_len"])?;
    let depth = get_usize_p(&numeric, "depth", 3, 1, 10000)?;
    let backstep = get_usize_p(&numeric, "backstep", 2, 0, 10000)?;
    let atr_len = get_usize_p(&numeric, "atr_len", 14, 1, 10000)?;

    let deviation = match get_enum_p(params, "deviation_mode")?.as_deref() {
        None | Some("percent") => {
            let value = get_f64_p(&numeric, "deviation_value", 1.0, 0.001, 100.0)?;
            ZigZagDeviationMode::Percent(value)
        }
        Some("atr_multiple") => {
            let value = get_f64_p(&numeric, "deviation_value", 1.0, 0.001, 1000.0)?;
            ZigZagDeviationMode::AtrMultiple(value)
        }
        Some(other) => {
            return Err(RegistryError::InvalidEnumValue {
                parameter: "deviation_mode".to_string(),
                value: other.to_string(),
                reason: "expected one of percent|atr_multiple".to_string(),
            });
        }
    };

    Ok(Box::new(AdvancedZigZagEngine::new(
        depth, backstep, deviation, atr_len,
    )))
}

fn build_trend_relationship_typed(
    params: &TypedParams,
) -> Result<Box<dyn Indicator>, RegistryError> {
    use super::smoothing::SmootherKind;
    use super::trend_relationship::AdaptiveTrendRelationship;

    let fast_kind = parse_smoother_kind(params, "fast_kind", SmootherKind::Ema)?;
    let slow_kind = parse_smoother_kind(params, "slow_kind", SmootherKind::Ema)?;

    let numeric = extract_numeric_subset(params, &["fast_len", "slow_len"])?;
    let fast_len = get_usize_p(&numeric, "fast_len", 9, 1, 10000)?;
    let slow_len = get_usize_p(&numeric, "slow_len", 21, 1, 10000)?;
    ensure_less("fast_len", fast_len as f64, "slow_len", slow_len as f64)?;

    Ok(Box::new(AdaptiveTrendRelationship::new(
        fast_kind, fast_len, slow_kind, slow_len,
    )))
}

// Note: `indicator::swing_structure::SwingStructureEngine` and
// `indicator::relative_strength::RelativeStrengthEngine` are intentionally not registered in the
// single-bar `build(name, params)` registry. `SwingStructureEngine` requires raw ATR injected per
// bar (`update(bar, atr)`), while `RelativeStrengthEngine` requires dual-series input (`update(own_bar, bench_bar)`).
// Both are exported directly from `kestrel_chartkit::indicator` for explicit use.

/// Finding 04: every canonical indicator name `build_checked` can construct, kept as an explicit
/// list (rather than derived from the match arms at runtime) so `catalog()` is checked against a
/// concrete, reviewable contract instead of only a minimum count. Aliases (e.g. "vp", "ob", "wvf")
/// are deliberately excluded: they must remain buildable but are not separate catalog entries.
///
/// Public (not `#[cfg(test)]`-gated) so tooling outside this crate's test suite — e.g.
/// `examples/export_applicability.rs` — can iterate the same canonical name list rather than
/// maintaining a second one.
pub const CANONICAL_INDICATOR_NAMES: &[&str] = &[
    "rsi",
    "macd",
    "bollinger",
    "adx",
    "stoch_rsi",
    "cci",
    "mfi",
    "atr",
    "chande_kroll",
    "efi",
    "trix",
    "vidya",
    "t3",
    "ulcer_index",
    "rci",
    "smi",
    "rvat",
    "bbtrend",
    "relative_volatility",
    "twap",
    "pvt",
    "pmo",
    "chandelier_exit",
    "chandelier_flip_radar",
    "midas",
    "trend_relationship",
    "williams_r",
    "tsi",
    "fisher_transform",
    "order_block",
    "liquidity_fvg",
    "market_structure_breaks",
    "pivots_structure",
    "volume_profile",
    "money_flow_profile",
    "extended_volume_profile",
    "persistent_volume_profile",
    "vwap",
    "vix_fix",
    "candle_story",
    "efficiency",
    "volume",
    "rvol",
    "obv",
    "cmf",
    "acc_dist",
    "true_range",
    "keltner",
    "donchian",
    "historical_volatility",
    "garman_klass",
    "sma",
    "ema",
    "wma",
    "vwma",
    "hma",
    "dema",
    "kama",
    "dmi",
    "aroon",
    "parabolic_sar",
    "supertrend",
    "ichimoku",
    "stochastic",
    "roc",
    "ultimate_oscillator",
    "awesome_oscillator",
    "ppo",
    "wavetrend",
    "cmo",
    "elder_ray",
    "anchored_vwap",
    "cvd",
    "hires_volume_flow",
    "klinger",
    "zigzag",
    "zigzag_advanced",
    "pivot_sets",
    "tema",
    "lsma",
    "mcginley",
    "envelope",
    "choppiness",
    "vortex",
    "alligator",
    "connors_rsi",
    "coppock",
    "dpo",
    "kst",
    "mass_index",
    "rvi",
    "bop",
    "eom",
    "nvi",
    "pvi",
    "chaikin_oscillator",
    "bos_choch",
    "liquidity_sweeps",
    "liquidity_pools",
    "wyckoff",
    "trend_quality",
    "buy_sell_pressure",
    "volatility_regime",
    "zscore",
    "multi_factor",
];

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashSet;

    /// Finding 04: `catalog()` must expose exactly the canonical, buildable indicator names —
    /// no fewer (a name silently missing from discovery) and no more (a stray or alias-as-
    /// canonical entry). This is the "buildable canonical name -> catalog entry" direction that a
    /// simple `catalog().len() > N` check does not exercise.
    #[test]
    fn test_catalog_matches_canonical_indicator_names_exactly() {
        let catalog_names: HashSet<&str> = catalog().iter().map(|e| e.name).collect();
        let canonical: HashSet<&str> = CANONICAL_INDICATOR_NAMES.iter().copied().collect();

        let missing_from_catalog: Vec<&&str> = canonical.difference(&catalog_names).collect();
        assert!(
            missing_from_catalog.is_empty(),
            "buildable but not discoverable via catalog(): {missing_from_catalog:?}"
        );

        let extra_in_catalog: Vec<&&str> = catalog_names.difference(&canonical).collect();
        assert!(
            extra_in_catalog.is_empty(),
            "catalog() entries with no matching canonical build_checked arm: {extra_in_catalog:?}"
        );

        assert_eq!(CANONICAL_INDICATOR_NAMES.len(), 105);
        assert_eq!(catalog().len(), 105);
    }

    #[test]
    fn test_catalog_has_no_duplicate_names() {
        let names: Vec<&str> = catalog().iter().map(|e| e.name).collect();
        let unique: HashSet<&str> = names.iter().copied().collect();
        assert_eq!(
            names.len(),
            unique.len(),
            "catalog() contains a duplicate indicator name"
        );
    }

    #[test]
    fn test_every_catalog_entry_builds_with_its_default_params() {
        for entry in catalog() {
            let built = build_checked(entry.name, &entry.default_params);
            assert!(
                built.is_ok(),
                "catalog entry '{}' failed to build with its own default params: {:?}",
                entry.name,
                built.err()
            );
        }
    }

    /// Negative test: a name that is only meant to be an alias must not have snuck in as a
    /// second, separate catalog entry alongside its canonical name.
    #[test]
    fn test_catalog_does_not_contain_aliases() {
        let catalog_names: HashSet<&str> = catalog().iter().map(|e| e.name).collect();
        for alias in [
            "vp",
            "wvf",
            "ob",
            "fvg",
            "smc",
            "bos",
            "choch",
            "pivots",
            "pinbar",
            "leg_efficiency",
            "er",
            "vp_extended",
            "vp_persistent",
        ] {
            assert!(
                !catalog_names.contains(alias),
                "'{alias}' is an alias, not a canonical name, and must not be its own catalog entry"
            );
        }
    }

    #[test]
    fn test_build_checked_valid_and_invalid_params() {
        let valid_params = HashMap::from([("period".to_string(), 14.0)]);
        assert!(build_checked("rsi", &valid_params).is_ok());

        // Period 0 is invalid
        let zero_params = HashMap::from([("rsi_len".to_string(), 0.0)]);
        let err = match build_checked("rsi", &zero_params) {
            Err(e) => e,
            Ok(_) => panic!("Expected error for zero period"),
        };
        assert!(matches!(err, RegistryError::InvalidParameter { .. }));

        // Negative period is invalid
        let neg_params = HashMap::from([("period".to_string(), -5.0)]);
        let err = match build_checked("sma", &neg_params) {
            Err(e) => e,
            Ok(_) => panic!("Expected error for negative period"),
        };
        assert!(matches!(err, RegistryError::InvalidParameter { .. }));

        // Fractional periods are rejected instead of silently truncated
        let fractional_params = HashMap::from([("period".to_string(), 14.5)]);
        assert!(matches!(
            build_checked("sma", &fractional_params),
            Err(RegistryError::InvalidParameter { .. })
        ));

        // Values above the allocation guard are rejected
        let huge_params = HashMap::from([("period".to_string(), 10_001.0)]);
        assert!(matches!(
            build_checked("sma", &huge_params),
            Err(RegistryError::InvalidParameter { .. })
        ));

        // NaN is invalid
        let nan_params = HashMap::from([("period".to_string(), f64::NAN)]);
        let err = match build_checked("sma", &nan_params) {
            Err(e) => e,
            Ok(_) => panic!("Expected error for NaN period"),
        };
        assert!(matches!(err, RegistryError::InvalidParameter { .. }));

        // Threshold and period relationships are validated
        let reversed_rsi = HashMap::from([
            ("oversold".to_string(), 80.0),
            ("overbought".to_string(), 20.0),
        ]);
        assert!(matches!(
            build_checked("rsi", &reversed_rsi),
            Err(RegistryError::InvalidParameter { .. })
        ));

        let reversed_ultimate = HashMap::from([
            ("period1".to_string(), 28.0),
            ("period2".to_string(), 14.0),
            ("period3".to_string(), 7.0),
        ]);
        assert!(matches!(
            build_checked("ultimate_oscillator", &reversed_ultimate),
            Err(RegistryError::InvalidParameter { .. })
        ));

        let oversized_bins = HashMap::from([("num_bins".to_string(), 1_001.0)]);
        assert!(matches!(
            build_checked("volume_profile", &oversized_bins),
            Err(RegistryError::InvalidParameter { .. })
        ));

        // Infinity is invalid
        let inf_params = HashMap::from([("period".to_string(), f64::INFINITY)]);
        let err = match build_checked("sma", &inf_params) {
            Err(e) => e,
            Ok(_) => panic!("Expected error for Infinity period"),
        };
        assert!(matches!(err, RegistryError::InvalidParameter { .. }));

        // MACD fast_len >= slow_len is invalid
        let macd_bad = HashMap::from([
            ("fast_len".to_string(), 30.0),
            ("slow_len".to_string(), 20.0),
        ]);
        let err = match build_checked("macd", &macd_bad) {
            Err(e) => e,
            Ok(_) => panic!("Expected error for fast >= slow"),
        };
        assert!(matches!(err, RegistryError::InvalidParameter { .. }));

        // Unknown indicator
        let err = match build_checked("non_existent_ind", &HashMap::new()) {
            Err(e) => e,
            Ok(_) => panic!("Expected error for unknown indicator"),
        };
        assert_eq!(
            err,
            RegistryError::UnknownIndicator("non_existent_ind".to_string())
        );
    }

    #[test]
    fn test_keltner_ema_period_is_the_canonical_catalog_key() {
        // Finding 05: the catalog publishes "ema_period"; the builder must actually read it
        // rather than silently ignoring it and falling back to the period-20 default.
        // `warmup_period` is `max(ema_period, atr_period)`, so atr_period is pinned to 1 here to
        // isolate what ema_period alone drove.
        let ind = build_checked(
            "keltner",
            &HashMap::from([
                ("ema_period".to_string(), 5.0),
                ("atr_period".to_string(), 1.0),
            ]),
        )
        .unwrap();
        assert_eq!(ind.warmup_period(), 5);

        let default_ind =
            build_checked("keltner", &HashMap::from([("atr_period".to_string(), 1.0)])).unwrap();
        assert_eq!(default_ind.warmup_period(), 20);
    }

    #[test]
    fn test_keltner_ma_period_legacy_alias_still_works() {
        let ind = build_checked(
            "keltner",
            &HashMap::from([
                ("ma_period".to_string(), 5.0),
                ("atr_period".to_string(), 1.0),
            ]),
        )
        .unwrap();
        assert_eq!(ind.warmup_period(), 5);
    }

    #[test]
    fn test_keltner_ema_period_invalid_value_rejected() {
        let err = match build_checked("keltner", &HashMap::from([("ema_period".to_string(), 0.0)]))
        {
            Err(e) => e,
            Ok(_) => panic!("Expected error for zero ema_period"),
        };
        assert!(matches!(err, RegistryError::InvalidParameter { .. }));
    }

    #[test]
    fn test_keltner_conflicting_canonical_and_alias_rejected() {
        let err = match build_checked(
            "keltner",
            &HashMap::from([
                ("ema_period".to_string(), 5.0),
                ("ma_period".to_string(), 10.0),
            ]),
        ) {
            Err(e) => e,
            Ok(_) => panic!("Expected error for conflicting ema_period/ma_period"),
        };
        assert!(matches!(err, RegistryError::InvalidParameter { .. }));

        // Identical values under both names is not a conflict.
        assert!(build_checked(
            "keltner",
            &HashMap::from([
                ("ema_period".to_string(), 5.0),
                ("ma_period".to_string(), 5.0),
            ]),
        )
        .is_ok());
    }

    #[test]
    fn test_build_typed_flattens_numeric_params() {
        let params: TypedParams = HashMap::from([("period".to_string(), ParamValue::Int(14))]);
        assert!(build_typed("rsi", &params).is_ok());

        let bool_params: TypedParams =
            HashMap::from([("period".to_string(), ParamValue::Bool(true))]);
        // Bool flattens to 1.0, which build_checked's own validation then accepts or rejects.
        assert!(build_typed("rsi", &bool_params).is_ok());
    }

    #[test]
    fn test_build_typed_rejects_non_numeric_params() {
        let params: TypedParams =
            HashMap::from([("period".to_string(), ParamValue::Enum("fast".to_string()))]);
        let err = match build_typed("rsi", &params) {
            Err(e) => e,
            Ok(_) => panic!("Expected error for enum parameter"),
        };
        assert!(matches!(
            err,
            RegistryError::UnsupportedParameterType { .. }
        ));
    }

    #[test]
    fn test_build_typed_propagates_indicator_validation_errors() {
        let params: TypedParams =
            HashMap::from([("period".to_string(), ParamValue::Float(f64::INFINITY))]);
        let err = match build_typed("sma", &params) {
            Err(e) => e,
            Ok(_) => panic!("Expected error for infinite period"),
        };
        assert!(matches!(err, RegistryError::InvalidParameter { .. }));
    }

    #[test]
    fn test_build_typed_anchored_vwap_native_enum_selection() {
        // Default (no anchor_kind given) stays Session, matching build_checked's behavior.
        let defaulted = build_typed("anchored_vwap", &TypedParams::new());
        assert!(defaulted.is_ok());

        let day_params: TypedParams = HashMap::from([(
            "anchor_kind".to_string(),
            ParamValue::Enum("day".to_string()),
        )]);
        assert!(build_typed("avwap", &day_params).is_ok());

        let skip_zero_vol: TypedParams = HashMap::from([(
            "zero_volume_policy".to_string(),
            ParamValue::Enum("skip".to_string()),
        )]);
        assert!(build_typed("anchored_vwap", &skip_zero_vol).is_ok());

        let manual_without_timestamp: TypedParams = HashMap::from([(
            "anchor_kind".to_string(),
            ParamValue::Enum("manual_timestamp".to_string()),
        )]);
        let err = match build_typed("anchored_vwap", &manual_without_timestamp) {
            Err(e) => e,
            Ok(_) => panic!("Expected error: manual_timestamp requires anchor_timestamp"),
        };
        assert!(matches!(err, RegistryError::InvalidEnumValue { .. }));

        let manual_with_timestamp: TypedParams = HashMap::from([
            (
                "anchor_kind".to_string(),
                ParamValue::Enum("manual_timestamp".to_string()),
            ),
            (
                "anchor_timestamp".to_string(),
                ParamValue::Timestamp(1_700_000_000),
            ),
        ]);
        assert!(build_typed("anchored_vwap", &manual_with_timestamp).is_ok());

        let unknown_kind: TypedParams = HashMap::from([(
            "anchor_kind".to_string(),
            ParamValue::Enum("bogus".to_string()),
        )]);
        let err = match build_typed("anchored_vwap", &unknown_kind) {
            Err(e) => e,
            Ok(_) => panic!("Expected error for unknown anchor_kind"),
        };
        assert!(matches!(err, RegistryError::InvalidEnumValue { .. }));
    }

    #[test]
    fn test_build_typed_pivot_sets_native_enum_selection() {
        for kind in [
            "classic",
            "fibonacci",
            "camarilla",
            "woodie",
            "demark",
            "cpr",
        ] {
            let params: TypedParams =
                HashMap::from([("pivot_type".to_string(), ParamValue::Enum(kind.to_string()))]);
            assert!(
                build_typed("pivot_sets", &params).is_ok(),
                "expected {kind} to build"
            );
        }

        let unknown: TypedParams = HashMap::from([(
            "pivot_type".to_string(),
            ParamValue::Enum("bogus".to_string()),
        )]);
        let err = match build_typed("multi_pivots", &unknown) {
            Err(e) => e,
            Ok(_) => panic!("Expected error for unknown pivot_type"),
        };
        assert!(matches!(err, RegistryError::InvalidEnumValue { .. }));
    }

    #[test]
    fn test_build_typed_source_propagates_to_computation() {
        use crate::model::{Bar, Source};

        let bars = [
            Bar::new(0, 10.0, 12.0, 8.0, 11.0, 100.0),
            Bar::new(60, 20.0, 22.0, 18.0, 21.0, 100.0),
        ];

        let close_params: TypedParams = HashMap::from([("period".to_string(), ParamValue::Int(2))]);
        let mut close_sma = build_typed("sma", &close_params).unwrap();

        let open_params: TypedParams = HashMap::from([
            ("period".to_string(), ParamValue::Int(2)),
            ("source".to_string(), ParamValue::Source(Source::Open)),
        ]);
        let mut open_sma = build_typed("sma", &open_params).unwrap();

        let mut close_out = None;
        let mut open_out = None;
        for bar in &bars {
            close_out = close_sma.on_bar(bar);
            open_out = open_sma.on_bar(bar);
        }

        assert_eq!(close_out.unwrap().value, (11.0 + 21.0) / 2.0);
        assert_eq!(open_out.unwrap().value, (10.0 + 20.0) / 2.0);
    }

    #[test]
    fn test_build_typed_source_close_is_a_no_op() {
        let params: TypedParams = HashMap::from([(
            "source".to_string(),
            ParamValue::Source(crate::model::Source::Close),
        )]);
        assert!(build_typed("sma", &params).is_ok());
    }

    #[test]
    fn test_adx_with_defaults_matches_registry_default() {
        let mut via_struct = Adx::with_defaults();
        let mut via_registry = build_checked("adx", &HashMap::new()).unwrap();

        let bars = crate::model::Bar::new(0, 100.0, 101.0, 99.0, 100.5, 1000.0);
        let mut struct_out = None;
        let mut registry_out = None;
        for i in 0..60 {
            let price = 100.0 + (i as f64 * 0.3).sin() * 5.0;
            let bar =
                crate::model::Bar::new(i, price, price + 1.0, price - 1.0, price + 0.5, 1000.0);
            struct_out = via_struct.on_bar(&bar);
            registry_out = via_registry.on_bar(&bar);
        }
        let _ = bars;
        assert_eq!(
            struct_out.map(|o| o.value),
            registry_out.map(|o| o.value),
            "Adx::with_defaults() must produce identical output to the registry's \"adx\" default"
        );
    }

    #[test]
    fn test_atr_with_defaults_matches_registry_default() {
        let mut via_struct = Atr::with_defaults();
        let mut via_registry = build_checked("atr", &HashMap::new()).unwrap();

        let mut struct_out = None;
        let mut registry_out = None;
        for i in 0..40 {
            let price = 100.0 + (i as f64 * 0.3).sin() * 5.0;
            let bar =
                crate::model::Bar::new(i, price, price + 1.0, price - 1.0, price + 0.5, 1000.0);
            struct_out = via_struct.on_bar(&bar);
            registry_out = via_registry.on_bar(&bar);
        }
        assert_eq!(
            struct_out.map(|o| o.value),
            registry_out.map(|o| o.value),
            "Atr::with_defaults() must produce identical output to the registry's \"atr\" default"
        );
    }

    /// `efi` weighs a close-to-close change by the bar's volume; a derived price source would be
    /// a different series under the same name, so it is refused until that contract exists.
    #[test]
    fn test_build_typed_rejects_non_close_source_on_efi() {
        let params: TypedParams = HashMap::from([(
            "source".to_string(),
            ParamValue::Source(crate::model::Source::Hlc3),
        )]);
        let err = match build_typed("efi", &params) {
            Err(e) => e,
            Ok(_) => panic!("expected 'efi' to reject a non-Close source"),
        };
        assert!(
            matches!(err, RegistryError::IncompatibleParameter { .. }),
            "efi returned {err:?} instead of IncompatibleParameter"
        );

        let close: TypedParams = HashMap::from([(
            "source".to_string(),
            ParamValue::Source(crate::model::Source::Close),
        )]);
        assert!(build_typed("efi", &close).is_ok());
    }

    #[test]
    fn test_build_typed_rejects_non_close_source_on_range_dependent_indicators() {
        let params: TypedParams = HashMap::from([(
            "source".to_string(),
            ParamValue::Source(crate::model::Source::Open),
        )]);
        for name in [
            "atr",
            "wyckoff",
            "chandelier_exit",
            "ce",
            "extended_volume_profile",
            "zigzag_advanced",
            "keltner",
            "donchian",
            "garman_klass",
        ] {
            let err = match build_typed(name, &params) {
                Err(e) => e,
                Ok(_) => panic!("expected '{name}' to reject a non-Close source"),
            };
            assert!(
                matches!(err, RegistryError::IncompatibleParameter { .. }),
                "'{name}' returned {err:?} instead of IncompatibleParameter"
            );
        }

        // Close is always a no-op regardless of range-dependence, so it must still succeed.
        let close_params: TypedParams = HashMap::from([(
            "source".to_string(),
            ParamValue::Source(crate::model::Source::Close),
        )]);
        assert!(build_typed("atr", &close_params).is_ok());
    }

    #[test]
    fn test_build_typed_trend_relationship_native_smoother_kind_selection() {
        let params: TypedParams = HashMap::from([
            ("fast_kind".to_string(), ParamValue::Enum("jma".to_string())),
            (
                "slow_kind".to_string(),
                ParamValue::Enum("alma".to_string()),
            ),
            ("fast_len".to_string(), ParamValue::Int(5)),
            ("slow_len".to_string(), ParamValue::Int(20)),
        ]);
        assert!(build_typed("trend_relationship", &params).is_ok());

        let unknown: TypedParams = HashMap::from([(
            "fast_kind".to_string(),
            ParamValue::Enum("bogus".to_string()),
        )]);
        let err = match build_typed("trend_relationship", &unknown) {
            Err(e) => e,
            Ok(_) => panic!("Expected error for unknown fast_kind"),
        };
        assert!(matches!(err, RegistryError::InvalidEnumValue { .. }));
    }

    #[test]
    fn test_build_checked_trend_relationship_defaults_to_ema() {
        assert!(build_checked("trend_relationship", &HashMap::new()).is_ok());
    }

    #[test]
    fn test_build_typed_midas_native_mode_and_source_selection() {
        let params: TypedParams = HashMap::from([
            (
                "mode".to_string(),
                ParamValue::Enum("bottomfinder".to_string()),
            ),
            (
                "source".to_string(),
                ParamValue::Source(crate::model::Source::Close),
            ),
        ]);
        assert!(build_typed("midas", &params).is_ok());

        let unknown: TypedParams =
            HashMap::from([("mode".to_string(), ParamValue::Enum("bogus".to_string()))]);
        let err = match build_typed("midas", &unknown) {
            Err(e) => e,
            Ok(_) => panic!("Expected error for unknown mode"),
        };
        assert!(matches!(err, RegistryError::InvalidEnumValue { .. }));
    }

    #[test]
    fn test_build_checked_midas_defaults_to_topfinder() {
        assert!(build_checked("midas", &HashMap::new()).is_ok());
    }
}