mt5-quant 1.34.2

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

Full input/output schemas for MT5-Quant tools.

> **Documentation Status:** All 90 tools are documented.

---

## `run_backtest`

Run a complete backtest pipeline: compile → clean cache → backtest → extract → analyze.

**When to call:** Any time you need fresh backtest results. Always runs the full pipeline unless `skip_*` flags are set.

### Input schema

```typescript
{
  // Required
  expert: string;          // EA name without path or extension. e.g. "MyEA_v1.2"

  // Date range — use either preset OR from+to
  preset?: "last_month" | "last_3months" | "ytd" | "last_year";
  from?: string;           // "YYYY-MM-DD"
  to?: string;             // "YYYY-MM-DD"

  // Optional overrides
  symbol?: string;         // Default from config. e.g. "XAUUSD"
  timeframe?: "M1" | "M5" | "M15" | "M30" | "H1" | "H4" | "D1"; // Default: M5
  deposit?: number;        // Default from config. e.g. 10000
  currency?: string;       // Default: "USD"
  model?: 0 | 1 | 2;      // 0=every tick (default), 1=1min OHLC, 2=open price
  set_file?: string;       // Path to .set file. If omitted, uses EA defaults.
  leverage?: number;       // Default: 500

  // Pipeline flags
  skip_compile?: boolean;  // Skip EA compilation (use existing .ex5)
  skip_clean?: boolean;    // Skip cache clean (faster but risks stale cache)
  skip_analyze?: boolean;  // Extract only, skip deal analysis
  deep_analyze?: boolean;  // Add hourly_pnl and volume_profile to analysis.json
  strategy?: "grid" | "scalper" | "trend" | "hedge" | "generic";
                           // Analysis strategy profile (default: "grid").
                           // Controls depth tracking, exit keywords, and cycle grouping.
}
```

### Output schema

```typescript
{
  success: boolean;
  report_dir: string;       // "reports/20250619_143022_MyEA_XAUUSD_M5"
  duration_seconds: number;

  // Inline summary from metrics.json (always present on success)
  metrics: {
    net_profit: number;
    profit_factor: number;
    max_dd_pct: number;
    sharpe_ratio: number;
    total_trades: number;
    recovery_factor: number;
    expected_payoff: number;
    gross_profit: number;
    gross_loss: number;
    win_rate_pct: number;
    avg_profit: number;
    avg_loss: number;
  };

  // Deal analysis summary (present unless skip_analyze=true)
  analysis_summary: {
    green_months: number;
    total_months: number;
    worst_month: string;        // "2025-10"
    worst_month_pnl: number;
    worst_dd_event_pct: number;
    worst_dd_date: string;
    max_grid_depth: number;     // highest layer reached in any cycle
    l5_plus_count: number;      // cycles that reached L5+
  };

  // File paths for direct reading
  files: {
    metrics_json: string;
    analysis_json: string;
    // Note: deals are stored in SQLite DB, not on disk.
    // Call export_deals_csv(report_id) to generate a CSV file on demand.
  };

  error?: string;  // Present on failure
}
```

### Example

```json
// Input
{
  "expert": "MyEA_v1.2",
  "from": "2025-01-01",
  "to": "2025-06-30",
  "deposit": 10000,
  "model": 0
}

// Output
{
  "success": true,
  "report_dir": "reports/20250619_143022_MyEA_XAUUSD_M5",
  "duration_seconds": 287,
  "metrics": {
    "net_profit": 4832.10,
    "profit_factor": 1.54,
    "max_dd_pct": 12.3,
    "sharpe_ratio": 1.18,
    "total_trades": 891
  },
  "analysis_summary": {
    "green_months": 5,
    "total_months": 6,
    "worst_month": "2025-03",
    "worst_month_pnl": -412.80,
    "worst_dd_event_pct": 12.3,
    "worst_dd_date": "2025-03-14",
    "max_grid_depth": 6,
    "l5_plus_count": 8
  },
  "files": {
    "metrics_json": "reports/20250619_143022_MyEA_XAUUSD_M5/metrics.json",
    "analysis_json": "reports/20250619_143022_MyEA_XAUUSD_M5/analysis.json"
  }
}
```

---

## `run_backtest_quick`

Quick backtest using pre-compiled EA: clean cache → backtest → extract → analyze.

**When to call:** When EA code hasn't changed and you just want to test different parameters or date ranges. Faster than `run_backtest` because it skips compilation.

### Input schema

Same as `run_backtest`, but `skip_compile` is automatically set to `true`.

### Output schema

Same as `run_backtest`.

---

## `run_backtest_only`

Backtest only: clean cache → backtest → extract. No analysis phase.

**When to call:** When you just need raw trade data (stored in DB) and don't need analytics. Fastest option for batch processing. Use `export_deals_csv` afterwards if you need a CSV file.

### Input schema

Same as `run_backtest`, but `skip_compile` and `skip_analyze` are automatically set to `true`.

### Output schema

Same as `run_backtest` but without `analysis_summary`.

---

## `launch_backtest`

Fire-and-forget mode: compile → clean → launch MT5 backtest, return immediately with job info.

**When to call:** When you want to launch a backtest without waiting for completion. Use `get_backtest_status` to poll for completion.

### Input schema

```typescript
{
  expert: string;          // Required. EA name without path or extension
  symbol?: string;         // Trading symbol (default: from config or first available)
  from_date?: string;      // Start date YYYY.MM.DD (default: past complete month)
  to_date?: string;        // End date YYYY.MM.DD (default: past complete month)
  timeframe?: string;      // M1, M5, M15, M30, H1, H4, D1 (default: M5)
  deposit?: number;        // Initial deposit (default: 10000)
  model?: 0 | 1 | 2;      // Tick model (default: 0)
  set_file?: string;       // Path to .set parameter file
  skip_compile?: boolean;         // Skip compilation
  skip_clean?: boolean;           // Skip cache cleaning
  timeout?: number;               // Max time in seconds (default: 900)
  gui?: boolean;                  // Enable MT5 visualization
  shutdown?: boolean;             // Shut down MT5 after test (default: true).
                                  // NOTE: on Wine/macOS terminal64.exe may not exit naturally
                                  // even with ShutdownTerminal=1. Use inactivity_kill_secs too.
  inactivity_kill_secs?: number;  // Kill MT5 if tester log hasn't grown for N seconds
                                  // (default: disabled / not set). Recommended: 120.
                                  // After silence, pipeline polls for HTML report for 30s,
                                  // then kills MT5 unconditionally. If HTML present → extracted;
                                  // otherwise falls back to journal extraction (no P&L data).
}
```

### Output schema

```typescript
{
  success: true;
  message: string;         // "Backtest launched successfully..."
  report_id: string;       // e.g., "20250122_034455_MyEA_XAUUSD_M5"
  report_dir: string;      // Full path to report directory
  expert: string;
  symbol: string;
  timeframe: string;
  launched_at: string;     // ISO8601 timestamp
  timeout_seconds: number;
  poll_hint: string;       // "Call get_backtest_status with report_dir to check progress"
}
```

---

## `run_rolling_backtest`

Run N consecutive weekly backtests sequentially and return aggregated results. Compiles once, then each week runs with `skip_compile`. Kills and restarts MT5 between weeks for a clean state.

**When to call:** When you want to test EA stability across multiple weeks to detect performance degradation, regime change sensitivity, or parameter drift.

### Input schema

```typescript
{
  // Required
  expert: string;              // EA name without path or extension

  // Date range — specify both or omit for auto-calculation (N weeks back to last Sunday)
  from_date?: string;          // "YYYY.MM.DD" (default: auto-calculate N weeks back)
  to_date?: string;            // "YYYY.MM.DD" (default: auto-calculate to last Sunday)

  // Optional overrides
  symbol?: string;             // Trading symbol (default: from config or first available)
  timeframe?: "M1" | "M5" | "M15" | "M30" | "H1" | "H4" | "D1"; // Default: M5
  deposit?: number;            // Initial deposit (default: 10000)
  model?: 0 | 1 | 2;          // Tick model: 0=Every tick, 1=OHLC, 2=Open prices
  set_file?: string;           // Path to .set parameter file for EA inputs

  // Rolling options
  weeks?: number;              // Number of weekly backtests to run (default: 4, max: 52)

  // Pipeline flags
  skip_compile?: boolean;      // Skip initial compilation (default: false — compiles on first week)
  shutdown?: boolean;          // Close MT5 after backtest completes (default: true)
  kill_existing?: boolean;     // Kill any running MT5 instance first (default: true)
  timeout?: number;            // Max wait time per week in seconds (default: 900)
  gui?: boolean;               // Enable MT5 visualization window (default: false)
  startup_delay_secs?: number; // Seconds to wait for MT5 initialization (default: 10)
}
```

### Output schema

```typescript
{
  success: true;
  message: string;             // "Rolling backtest launched with N weeks. Use get_backtest_status to poll for completion."
  report_id: string;           // "ROLLING_MyEA_2026.06.24_2026.07.01"
  report_dir: string;          // Full path to report directory
  expert: string;
  weeks: Array<{
    label: string;             // "Week 1", "Week 2", etc.
    from_date: string;         // "2026.06.24"
    to_date: string;           // "2026.06.30"
  }>;
  poll_hint: string;           // "Call get_backtest_status with report_dir to check progress"
}
```

### Status polling

After launch, poll with `get_backtest_status(report_dir=<dir>)` to track progress. The rolling backtest runs all weeks in a background task — each week is a full backtest pipeline (clean → launch → poll → extract → analyze).

Once complete, the report directory contains:
- `rolling_results.json` — full summary with per-week metrics and totals
- `progress.log` — current week being processed
- `weeks.json` — the weekly schedule

### Example

```json
// Input
{
  "expert": "MyEA",
  "symbol": "XAUUSD",
  "weeks": 4,
  "deposit": 10000
}

// Output
{
  "success": true,
  "message": "Rolling backtest launched with 4 weeks. Use get_backtest_status to poll for completion.",
  "report_id": "ROLLING_MyEA_2026.06.03_2026.07.01",
  "report_dir": "reports/ROLLING_MyEA_2026.06.03_2026.07.01",
  "expert": "MyEA",
  "weeks": [
    { "label": "Jun 03 - Jun 07", "from_date": "2026.06.03", "to_date": "2026.06.07" },
    { "label": "Jun 10 - Jun 14", "from_date": "2026.06.10", "to_date": "2026.06.14" },
    { "label": "Jun 17 - Jun 21", "from_date": "2026.06.17", "to_date": "2026.06.21" },
    { "label": "Jun 24 - Jun 28", "from_date": "2026.06.24", "to_date": "2026.06.28" }
  ]
}
```

### Rolling results format (rolling_results.json)

```json
{
  "success": true,
  "weeks_run": 4,
  "summary": {
    "total_net_profit": 12450.50,
    "max_drawdown_pct": 8.5,
    "total_trades": 342
  },
  "weekly_results": [
    {
      "label": "Jun 03 - Jun 07",
      "from_date": "2026.06.03",
      "to_date": "2026.06.07",
      "success": true,
      "net_profit": 3200.00,
      "max_dd_pct": 3.2,
      "total_trades": 85,
      "profit_factor": 1.45,
      "report_dir": "reports/20260701_120000_MyEA_XAUUSD_M5"
    },
    {
      "label": "Jun 10 - Jun 14",
      "from_date": "2026.06.10",
      "to_date": "2026.06.14",
      "success": true,
      "net_profit": -450.00,
      "max_dd_pct": 8.5,
      "total_trades": 92,
      "profit_factor": 0.92,
      "report_dir": "reports/20260701_123000_MyEA_XAUUSD_M5"
    }
  ]
}
```

---

## `get_backtest_status`

Check progress of a running backtest pipeline launched via `launch_backtest`.

**When to call:** Poll periodically after calling `launch_backtest` to check completion status.

### Input schema

```typescript
{
  report_dir: string;  // Report directory path from launch_backtest output
}
```

### Output schema

```typescript
{
  success: true;
  report_dir: string;
  status: "completed" | "running" | "failed" | "in_progress" | "not_started";
  stage: string;           // Current pipeline stage: COMPILE, CLEAN, BACKTEST, EXTRACT, ANALYZE, DONE
  is_complete: boolean;    // True if backtest finished successfully
  mt5_running: boolean;    // Whether MT5 process is active
  report_found: boolean;     // Whether report file exists
  metrics_extracted: boolean;
  deals_extracted: boolean;
  elapsed_seconds: number;   // Time since launch
  message: string;          // Human-readable status message
  job?: {
    report_id: string;
    expert: string;
    symbol: string;
    timeframe: string;
    launched_at: string;
    timeout_seconds: number;
  }
}
```

---

## `run_optimization`

Launch genetic parameter optimization as a detached background process.

**Important:** This tool returns immediately. MT5 runs for 2-6 hours. The AI agent must NOT poll for results — the user monitors MT5 and signals when done. Call `get_optimization_results` only after user confirmation.

**Uses Model=1 (1-min OHLC) for faster optimization.** Use a separate `run_backtest` with `model=0` to verify top optimization results — Model 1 optimization parameters may overfit grid/martingale EAs because intra-bar price movement is not simulated. The `get_optimization_status` tool now auto-parses results when optimization completes, returning top passes, best PF, and best profit.

### Input schema

```typescript
{
  expert: string;          // EA name
  set_file: string;        // Path to optimization .set file (with ||Y flags)
  from: string;            // "YYYY-MM-DD"
  to: string;              // "YYYY-MM-DD"
  symbol?: string;         // Default from config
  deposit?: number;        // Default from config
  max_passes?: number;     // Cap on genetic optimization passes (e.g. 5000 to run fewer)
  currency?: string;       // Default: "USD"
  leverage?: number;       // Default: 500
  log_file?: string;       // Where to write nohup output (default: /tmp/opt_<timestamp>.log)
}
```

### Output schema

```typescript
{
  success: boolean;
  job_id: string;          // "opt_20250619_143022"
  log_file: string;        // "/tmp/opt_20250619_143022.log"
  pid: number;             // Process ID (for user monitoring if needed)
  combinations: number;    // Estimated from set_file analysis (product of all ||Y ranges)
  message: string;         // "Optimization launched. Signal me when MT5 completes."
}
```

### Optimization set file format

```ini
; param=current_value||start||step||stop||Y   (Y = include in sweep)
; param=value||N                               (N = fixed, not swept)

Min_Entry_Confidence=0.610||0.580||0.010||0.650||Y   ; 8 values
TP_Pips_Layer1=400||300||50||500||Y                   ; 5 values
Max_DD_Percent=15.0||N                                ; fixed

; Total combinations: 8 × 5 = 40
```

**MT5-Quant handles automatically:**
- UTF-16LE encoding with BOM
- `chmod 444` (read-only) before launch
- `OptMode=0` reset in `terminal.ini`
- `LastOptimization` line removal from `terminal.ini`
- `ExpertParameters` = filename only (not full path) in launch INI

---

## `get_optimization_results`

Parse completed optimization results. Handles both HTML (`.htm`) and SpreadsheetML XML (`.htm.xml`) formats transparently.

### Input schema

```typescript
{
  job_id?: string;         // From run_optimization response. If omitted, uses latest _opt/ dir.
  report_dir?: string;     // Explicit path to *_opt/ directory
  top_n?: number;          // How many top results to return (default: 20)
  dd_threshold?: number;   // Flag results above this DD% as high-risk (default: 20)
  sort_by?: "profit" | "profit_factor" | "sharpe"; // Default: "profit"
}
```

### Output schema

```typescript
{
  success: boolean;
  total_passes: number;
  converged: boolean;         // True if passes stopped improving in last 10%
  report_format: "html" | "xml";

  results: Array<{
    rank: number;
    net_profit: number;
    profit_factor: number;
    max_dd_pct: number;
    total_trades: number;
    sharpe_ratio: number;
    high_risk: boolean;       // DD > dd_threshold
    params: Record<string, number | boolean>;  // All swept parameter values
  }>;

  convergence_analysis: {
    top_10_agreement: Record<string, string>;  // Params same across top 10 = strong signal
    high_variance_params: string[];             // Params that vary in top 10 = uncertain
  };

  recommendation: {
    best_params: Record<string, number | boolean>;
    reasoning: string;
    next_step: "verify_model0" | "auto_promote" | "investigate";
  };
}
```

### Convergence analysis

A parameter that appears with the same value across all top-10 results is a strong optimization signal — the genetic algorithm converged on it. A parameter that varies across top-10 means the optimizer couldn't distinguish between values — either the parameter doesn't matter much, or more passes are needed.

---

## `verify_setup`

Check all required paths, Wine version, and EA/set file inventory. Run this first if `run_backtest` or `run_optimization` fails with path errors.

### Input schema

```typescript
{}  // No parameters required
```

### Output schema

```typescript
{
  success: boolean;
  wine_path: string;
  wine_version: string;
  mt5_dir: string;
  terminal_exe: string;
  experts_dir: string;
  display_mode: "gui" | "headless";
  ea_count: number;           // .ex5 files found in Experts/
  set_count: number;          // .set files found
  missing: string[];          // List of paths/tools that couldn't be found
  hints: string[];            // Actionable fix hints for each missing item
}
```

---

## `get_backtest_status`

Check the current stage and elapsed time of a running backtest pipeline by reading its `progress.log`.

### Input schema

```typescript
{
  report_dir: string;    // Path to the report directory from run_backtest
}
```

### Output schema

```typescript
{
  success: boolean;
  report_dir: string;
  stage: "COMPILE" | "CLEAN" | "BACKTEST" | "EXTRACT" | "ANALYZE" | "DONE";
  elapsed_seconds: number;
  finished: boolean;
  log_lines: string[];   // Last 5 lines of progress.log
}
```

---

## `get_optimization_status`

Check the live state of a background optimization job (started by `run_optimization`).

### Input schema

```typescript
{
  job_id: string;        // From run_optimization response
}
```

### Output schema

```typescript
{
  success: boolean;
  status: "running" | "stopped" | "completed";
  job_id: string;
  pid: number;
  expert?: string;
  symbol?: string;
  from_date?: string;
  to_date?: string;
  started_at?: string;
  // Present when status is "completed":
  total_passes?: number;
  top_10?: Array<{ pass: number; profit: number; profit_factor: number; drawdown_pct: number; }>;
  best_pf?: { /* best pass by profit factor */ };
  best_profit?: { /* best pass by profit */ };
}
```

---

## `prune_reports`

Delete old report directories to reclaim disk space, keeping the most recent N runs. Optimization result directories (`*_opt/`) are always preserved.

### Input schema

```typescript
{
  keep_last?: number;    // How many recent reports to keep (default from config, usually 10)
  dry_run?: boolean;     // If true, list what would be deleted without deleting (default: false)
}
```

### Output schema

```typescript
{
  success: boolean;
  deleted: string[];     // Paths that were (or would be) deleted
  kept: string[];        // Paths that were kept
  freed_mb: number;      // Approximate disk space freed
}
```

---

## `analyze_report`

Read and summarize a completed backtest report without re-running MT5. Loads deals from the SQLite database.

### Input schema

```typescript
{
  report_id?: string;          // Preferred: report ID from list_reports
  report_dir?: string;         // Legacy: path to report directory (looks up DB entry)
                               // Omit both to use the latest report automatically
  strategy?: "grid" | "scalper" | "trend" | "hedge" | "generic";
                               // Strategy profile that was used (default: "grid").
                               // Only affects interpretation of analysis.json fields —
                               // does not re-run analysis.
  include_deals?: boolean;     // Include top 20 deals in output (default: false)
  include_monthly?: boolean;   // Include full monthly P/L table (default: true)
  include_dd_events?: boolean; // Include DD event reconstruction (default: true)
  deep?: boolean;              // Include hourly_pnl and volume_profile (default: false)
}
```

### Output schema

```typescript
{
  success: boolean;
  report_dir: string;
  strategy: string;           // Active profile: "grid" | "scalper" | "trend" | "hedge" | "generic"

  metrics: { /* same as run_backtest metrics */ };

  // ── Always present (strategy-agnostic) ─────────────────────────────────────

  monthly_pnl: Array<{
    month: string;          // "2025-01"
    pnl: number;
    trades: number;
    green: boolean;
  }>;

  dd_events: Array<{
    peak_dd_pct: number;
    start_date: string;
    end_date: string;
    duration_days: number;
    recovery_date: string | null;
    recovery_days: number | null;
    cause: string;          // Profile-driven: e.g. "locking_cascade" (grid) or "whipsaw" (trend)
                            // Falls back to "unknown" when no keyword matched
  }>;

  top_losses: Array<{
    date: string;
    loss_usd: number;
    grid_depth_at_close: number;  // 0 for non-grid strategies
    volume: number;
    comment: string;
  }>;

  loss_sequences: Array<{
    length: number;
    total_loss: number;
    start: string;
    end: string;
  }>;

  position_pairs: Array<{
    time: string;
    type: "buy" | "sell";
    profit: number;
    volume: number;
    layer: number;
    hold_minutes: number | null;
    comment: string;
    magic: string;
    order: string;
  }>;

  // ── Strategy-driven (content varies by profile) ────────────────────────────

  depth_histogram: Record<string, number>;
                            // grid:    { L1: n, L2: n, …, "L8+": n }
                            // others:  {} (empty — no depth_re in profile)

  grid_depth_histogram: Record<string, number>;
                            // Backward-compat alias for depth_histogram (grid only)

  cycle_stats: {
    total_cycles: number;
    win_rate: number;       // percent
    avg_profit: number;
    win_rate_by_depth: Record<string, { total: number; win_rate: number }>;
    // win_rate_by_depth populated for grid; keys = "L?" for non-depth profiles
  };

  exit_reason_breakdown: Record<
    string,                 // Keys depend on strategy profile exit_keywords
                            // grid:    "locking" | "cutloss" | "zombie" | "timeout" | "tp" | "sl"
                            // scalper: "manual" | "trailing" | "tp" | "sl"
                            // trend:   "breakeven" | "trailing" | "partial" | "tp" | "sl"
                            // generic: "tp" | "sl"
    { count: number; total_pnl: number; avg_pnl: number }
  >;

  direction_bias: {
    buy?: { trades: number; win_rate: number; total_pnl: number; avg_pnl: number };
    sell?: { trades: number; win_rate: number; total_pnl: number; avg_pnl: number };
  };

  streak_analysis: {
    max_win_streak: number;
    max_win_start: string;
    max_win_end: string;
    max_loss_streak: number;
    max_loss_start: string;
    max_loss_end: string;
    current_streak: number;
    current_streak_type: "win" | "loss";
  };

  session_breakdown: Record<
    "asian" | "london" | "london_ny_overlap" | "new_york" | "off_hours",
    { trades: number; win_rate: number; total_pnl: number }
  >;

  weekday_pnl: Array<{
    day: string;            // "Monday" … "Sunday"
    pnl: number;
    trades: number;
    win_rate: number;
  }>;

  concurrent_peak: {
    peak_open: number;
    peak_time: string;
  };

  // ── Deep mode only (deep=true) ──────────────────────────────────────────────

  hourly_pnl?: Array<{
    hour: number;           // 0–23
    pnl: number;
    trades: number;
    win_rate: number;
  }>;

  volume_profile?: Array<{
    lot_tier: string;       // "0.01" | "0.02-0.04" | "0.05-0.09" | "0.10-0.49" | …
    pnl: number;
    trades: number;
    win_rate: number;
  }>;

  // ── Optional raw deals ──────────────────────────────────────────────────────

  deals?: Array<{ /* all 13 deal columns */ }>; // Only if include_deals=true
}
```

---

## `compare_baseline`

Compare a report against a baseline and return a structured verdict.

### Input schema

```typescript
{
  report_dir: string;       // Report to evaluate
  baseline: {
    net_profit: number;
    max_dd_pct: number;
    total_trades?: number;
    label?: string;         // e.g. "v1.2 production"
  };
  promote_threshold?: {
    profit_gt: number;      // Auto-promote if profit > this (default: baseline profit)
    dd_lt: number;          // AND DD < this (default: 20)
  };
}
```

### Output schema

```typescript
{
  verdict: "winner" | "loser" | "marginal";
  auto_promote: boolean;

  delta: {
    profit_usd: number;     // positive = improvement
    profit_pct: number;     // relative to baseline
    dd_pp: number;          // positive = DD got worse
    trades_delta: number;
  };

  summary: string;          // Human-readable one-liner

  details: {
    candidate: { net_profit: number; max_dd_pct: number; total_trades: number; };
    baseline: { net_profit: number; max_dd_pct: number; label: string; };
  };
}
```

### Example

```json
// Input
{
  "report_dir": "reports/20250619_143022_MyEA_v1.3_XAUUSD_M5",
  "baseline": {
    "net_profit": 8660,
    "max_dd_pct": 15.66,
    "label": "v1.2 production"
  }
}

// Output
{
  "verdict": "winner",
  "auto_promote": true,
  "delta": {
    "profit_usd": 3186.32,
    "profit_pct": 36.8,
    "dd_pp": -7.27,
    "trades_delta": -3
  },
  "summary": "+$3,186 (+37%) profit vs v1.2. DD dropped from 15.66% to 8.39%. Auto-promoting.",
  "details": {
    "candidate": { "net_profit": 11846.32, "max_dd_pct": 8.39, "total_trades": 1963 },
    "baseline": { "net_profit": 8660.00, "max_dd_pct": 15.66, "label": "v1.2 production" }
  }
}
```

---

## `compile_ea`

Compile an MQL5 Expert Advisor via MetaEditor (Wine/CrossOver).

### Input schema

```typescript
{
  expert_path: string;     // e.g. "src/MyEA_v1.2.mq5"
  include_dirs?: string[]; // Additional include search paths
}
```

### Output schema

```typescript
{
  success: boolean;
  binary_path: string;     // Path where .ex5 was written
  binary_size_bytes: number;
  warnings: number;
  errors: number;
  error_list: Array<{
    file: string;
    line: number;
    message: string;
  }>;
  compile_time_ms: number;
}
```

---

## Error Handling

All tools return `success: false` with an `error` field on failure. Pipeline failures are non-fatal by default — the tool returns partial results if any stages completed.

```typescript
{
  success: false,
  error: "COMPILE_FAILED",
  error_detail: "2 errors in src/MyEA_v1.2.mq5: line 847: undeclared identifier 'Max_New_Param'",
  completed_stages: ["COMPILE"],
  failed_stage: "COMPILE"
}
```

**Error codes:**

| Code | Stage | Cause |
|------|-------|-------|
| `COMPILE_FAILED` | COMPILE | MQL5 syntax errors |
| `WINE_NOT_FOUND` | Any | Wine/CrossOver not installed or wrong path |
| `MT5_TIMEOUT` | BACKTEST | MT5 didn't exit within timeout (default: 15min) |
| `REPORT_NOT_FOUND` | EXTRACT | MT5 produced no report (usually parameter error) |
| `EXTRACT_FAILED` | EXTRACT | Report parse error (format change?) |
| `NO_DEALS` | ANALYZE | Report has 0 trades (check date range, symbol) |
| `OPT_NOT_FINISHED` | get_opt_results | Optimization still running |

---

## `list_reports`

List all backtest report directories with compact key metrics. Use this to survey what runs exist before deciding which to analyze — much cheaper than calling `analyze_report` repeatedly.

### Input schema

```typescript
{
  include_opt?: boolean;   // Include _opt dirs (default: false)
  limit?: number;          // Max reports, newest first (default: 30)
}
```

### Output schema

```typescript
{
  success: boolean;
  count: number;
  reports: Array<{
    name: string;           // "20250619_143022_MyEA_XAUUSD_M5"
    is_opt: boolean;
    net_profit?: number;
    max_dd_pct?: number;
    total_trades?: number;
    symbol?: string;
    timeframe?: string;
    from_date?: string;
    to_date?: string;
    metrics?: "missing";    // Present only if metrics.json is absent
  }>;
}
```

---

## `tail_log`

Read the last N lines of a log file. Supports `filter=errors` to return only lines containing error/fail keywords — avoids streaming full logs into context.

### Input schema

```typescript
{
  // Provide one of: report_dir, job_id, or log_file
  report_dir?: string;     // Reads progress.log from this dir (omit for latest)
  job_id?: string;         // Reads the nohup log for this optimization job
  log_file?: string;       // Absolute path to any log file

  n?: number;              // Lines to return (default: 50)
  filter?: "all" | "errors" | "warnings";  // Default: "all"
}
```

### Output schema

```typescript
{
  success: boolean;
  log_file: string;        // Resolved path of the file that was read
  total_lines: number;     // Lines matched after filter applied
  lines: string[];         // Last n of the matched lines
}
```

---

## `cache_status`

Show the MT5 tester cache directory size broken down by symbol. Use before `clean_cache` to see what's there.

### Input schema

```typescript
{}  // No parameters
```

### Output schema

```typescript
{
  success: boolean;
  cache_dir: string;
  total_size_mb: number;
  symbols: Array<{
    symbol: string;        // Subdirectory name (broker symbol)
    size_mb: number;
  }>;
}
```

---

## `clean_cache`

Delete MT5 tester cache files. Forces MT5 to regenerate tick data on the next backtest (slower first run after clean). Supports dry-run preview and per-symbol targeting.

### Input schema

```typescript
{
  symbol?: string;         // Delete only this symbol's cache. Omit to delete all.
  dry_run?: boolean;       // Report what would be deleted without deleting (default: false)
}
```

### Output schema

```typescript
{
  success: boolean;
  dry_run: boolean;
  deleted_symbols: string[];
  freed_mb: number;
  hint: string;            // Reminder that next backtest will be slower
}
```

---

## `read_set_file`

Parse an MT5 `.set` parameter file (UTF-16LE or UTF-8) into structured JSON. Handles BOM detection automatically. Use this instead of reading raw `.set` files.

### Input schema

```typescript
{
  path: string;            // Path to .set file
}
```

### Output schema

```typescript
{
  success: boolean;
  path: string;
  param_count: number;
  comments: string[];      // Header comment lines (stripped of semicolons)
  params: Record<string, {
    value: string;          // Current / default value
    from?: string;          // Sweep start (present for optimization params)
    to?: string;            // Sweep end
    step?: string;          // Sweep step
    optimize?: boolean;     // True if ||Y flag is set
  }>;
}
```

### Example

```json
// Input
{ "path": "config/MyEA_opt.set" }

// Output
{
  "success": true,
  "path": "config/MyEA_opt.set",
  "param_count": 5,
  "comments": ["MyEA optimization set — XAUUSD M5"],
  "params": {
    "Min_Entry_Confidence": { "value": "0.610", "from": "0.580", "to": "0.650", "step": "0.010", "optimize": true },
    "TP_Pips": { "value": "400", "from": "300", "to": "500", "step": "50", "optimize": true },
    "Max_DD_Percent": { "value": "15.0" }
  }
}
```

---

## `write_set_file`

Write an MT5 `.set` parameter file with correct UTF-16LE encoding and `chmod 444`. Overwrites any existing file at the path.

### Input schema

```typescript
{
  path: string;            // Output path for .set file

  params: Record<string,
    | string | number      // Simple fixed value
    | {
        value: string | number;
        from?: string | number;   // Include for optimization sweep
        to?: string | number;
        step?: string | number;
        optimize?: boolean;       // true → ||Y, false → ||N (default: false)
      }
  >;
}
```

### Output schema

```typescript
{
  success: boolean;
  path: string;
  param_count: number;
  encoding: "utf-16-le";
  permissions: string;     // "444 (read-only, required by MT5)"
}
```

### Example

```json
// Input
{
  "path": "config/MyEA_opt.set",
  "params": {
    "Min_Entry_Confidence": { "value": 0.61, "from": 0.58, "to": 0.65, "step": 0.01, "optimize": true },
    "TP_Pips": { "value": 400, "from": 300, "to": 500, "step": 50, "optimize": true },
    "Max_DD_Percent": 15.0
  }
}

// Output
{
  "success": true,
  "path": "config/MyEA_opt.set",
  "param_count": 3,
  "encoding": "utf-16-le",
  "permissions": "444 (read-only, required by MT5)"
}
```

---

## `list_jobs`

List all optimization jobs tracked in `.mt5mcp_jobs/` with compact status. Cheaper than calling `get_optimization_status` per job.

### Input schema

```typescript
{
  include_done?: boolean;  // Include completed/failed jobs (default: true)
}
```

### Output schema

```typescript
{
  success: boolean;
  count: number;
  jobs: Array<{
    job_id: string;          // "opt_20250619_143022"
    status: "running" | "done" | "failed";
    elapsed_seconds: number | null;
    expert: string;
    started_at: string;      // ISO timestamp
    log_file: string;
  }>;
}
```

---

## `patch_set_file`

Modify specific parameters in an existing `.set` file in-place. Preserves all other params, comments, and sweep config untouched. Returns a diff of what changed. **Use instead of `read_set_file` → edit → `write_set_file`** — saves two round-trips.

### Input schema

```typescript
{
  path: string;            // .set file to modify (must exist)
  patches: Record<string,
    | string | number      // scalar → only updates value, keeps existing sweep config
    | {
        value?: string | number;
        from?: string | number;
        to?: string | number;
        step?: string | number;
        optimize?: boolean;
      }
  >;
}
```

### Output schema

```typescript
{
  success: boolean;
  path: string;
  changed_count: number;
  param_count: number;
  changed: Array<{ name: string; old: string; new: string; }>;
}
```

### Example

```json
// Input — change two params without touching the rest of the file
{
  "path": "config/MyEA_opt.set",
  "patches": {
    "TP_Pips": 350,
    "Min_Entry_Confidence": { "value": 0.62, "from": 0.60, "to": 0.65, "optimize": true }
  }
}

// Output
{
  "success": true,
  "path": "config/MyEA_opt.set",
  "changed_count": 2,
  "param_count": 12,
  "changed": [
    { "name": "TP_Pips", "old": "400", "new": "350" },
    { "name": "Min_Entry_Confidence", "old": "0.610", "new": "0.62" }
  ]
}
```

---

## `clone_set_file`

Copy a `.set` file to a new path, applying optional param overrides. One call instead of read → modify → write. Preserves header comments.

### Input schema

```typescript
{
  source: string;          // Source .set file
  destination: string;     // Output path (created if needed)
  overrides?: Record<string, string | number | { value; from?; to?; step?; optimize? }>;
}
```

### Output schema

```typescript
{
  success: boolean;
  source: string;
  destination: string;
  param_count: number;
  overridden_count: number;
  overridden: Array<{ name: string; old: string | null; new: string; }>;
}
```

---

## `set_from_optimization`

Generate a clean backtest `.set` file directly from an optimization result's params dict. Strips all sweep flags (`||Y`) so the file is ready for `run_backtest`. Optionally fills params not in the optimization result from a template `.set`, and optionally re-adds sweep ranges to selected params for a narrowed follow-on optimization.

**Typical call**: immediately after `get_optimization_results`, use `results[0].params` as the `params` argument.

### Input schema

```typescript
{
  path: string;            // Output .set file path

  params: Record<string, string | number>;
                           // Flat param→value dict from optimization result.
                           // e.g. { "TP_Pips": 400, "Min_Confidence": 0.61 }

  template?: string;       // Path to existing .set. Params NOT in 'params' are
                           // copied from here as fixed values.

  sweep?: Record<string, { from: number; to: number; step: number; optimize?: boolean }>;
                           // Re-add sweep ranges to specific params after applying opt values.
                           // Used to create a narrowed follow-on optimization .set.
}
```

### Output schema

```typescript
{
  success: boolean;
  path: string;
  param_count: number;
  from_template: boolean;
  opt_params_applied: number;
  swept_params: number;        // > 0 if sweep was provided
  total_combinations: number;  // 0 for pure backtest .set
}
```

### Example

```json
// After get_optimization_results returned:
// results[0].params = { "TP_Pips": 400, "Min_Entry_Confidence": 0.62, "Max_DD_Percent": 15.0 }

{
  "path": "config/MyEA_v1.3.set",
  "params": { "TP_Pips": 400, "Min_Entry_Confidence": 0.62, "Max_DD_Percent": 15.0 },
  "template": "config/MyEA_base.set"
}

// Output
{
  "success": true,
  "path": "config/MyEA_v1.3.set",
  "param_count": 12,
  "from_template": true,
  "opt_params_applied": 3,
  "swept_params": 0,
  "total_combinations": 0
}
```

---

## `diff_set_files`

Compare two `.set` files and return only the differences. Use instead of reading both files and comparing manually.

### Input schema

```typescript
{
  path_a: string;   // Baseline / old file
  path_b: string;   // Candidate / new file
}
```

### Output schema

```typescript
{
  success: boolean;
  path_a: string;
  path_b: string;
  identical: boolean;
  added_count: number;    // Params in b but not a
  removed_count: number;  // Params in a but not b
  changed_count: number;  // Params in both but with different value or sweep flag

  added:   Array<{ name: string; value: string; }>;
  removed: Array<{ name: string; value: string; }>;
  changed: Array<{
    name: string;
    a: string;           // value in path_a
    b: string;           // value in path_b
    sweep_a?: boolean;   // Present only if sweep flag differs
    sweep_b?: boolean;
  }>;
}
```

### Example

```json
{
  "path_a": "config/MyEA_v1.2.set",
  "path_b": "config/MyEA_v1.3.set"
}

// Output
{
  "success": true,
  "identical": false,
  "added_count": 1,
  "removed_count": 0,
  "changed_count": 2,
  "added":   [{ "name": "Trailing_Activation", "value": "50" }],
  "removed":  [],
  "changed": [
    { "name": "TP_Pips", "a": "400", "b": "350" },
    { "name": "Min_Entry_Confidence", "a": "0.610", "b": "0.620", "sweep_a": true, "sweep_b": false }
  ]
}
```

---

## `describe_sweep`

Show a `.set` file's sweep configuration: which params are swept, their ranges, per-param value counts, and total combinations. Use before `run_optimization` to verify scope.

### Input schema

```typescript
{
  path: string;
}
```

### Output schema

```typescript
{
  success: boolean;
  path: string;
  total_params: number;
  swept_count: number;
  fixed_count: number;
  total_combinations: number;
  swept_params: Array<{
    name: string;
    from: string;
    to: string;
    step: string;
    count: number;      // Number of distinct values in this param's range
  }>;
  hint: string;         // e.g. "240 combinations. Typical range: 1–8h depending on EA tick speed."
}
```

### Example

```json
// Input
{ "path": "config/MyEA_opt.set" }

// Output
{
  "success": true,
  "total_params": 12,
  "swept_count": 3,
  "fixed_count": 9,
  "total_combinations": 240,
  "swept_params": [
    { "name": "TP_Pips",              "from": "300", "to": "500", "step": "50",   "count": 5 },
    { "name": "Min_Entry_Confidence", "from": "0.58","to": "0.65","step": "0.01", "count": 8 },
    { "name": "Max_DD_Percent",       "from": "12",  "to": "20",  "step": "2",    "count": 5 }
  ],
  "hint": "240 combinations. Typical range: 1–8h depending on EA tick speed."
}
```

---

## `list_set_files`

List all `.set` files in the MT5 tester profiles directory with param counts, swept param counts, and total combinations per file. Use to find the right `.set` without reading each one.

### Input schema

```typescript
{
  ea?: string;    // Filter by EA name substring (case-insensitive)
}
```

### Output schema

```typescript
{
  success: boolean;
  profiles_dir: string;
  count: number;
  files: Array<{
    name: string;               // filename only
    param_count: number;
    swept_count: number;
    total_combinations: number; // 0 for backtest-only .set files
    modified: string;           // "YYYY-MM-DD HH:MM"
    error?: string;             // Present only if file is unreadable
  }>;
}
```

---

## `get_active_account`

Get current MT5 account session information: login, server, and available symbols. This is essential for pre-flight checks to ensure symbol availability before backtesting.

### Input schema

```typescript
{}  // No parameters
```

### Output schema

```typescript
{
  success: boolean;
  ready_for_backtest: boolean;    // true if account exists and symbols available
  account: {
    login: string;
    server: string;
  } | null;
  server: string;                   // Active server name
  available_servers: string[];      // All servers with history data
  symbols: string[];                // Symbols available for active server
  symbol_count: number;
  hint: string;                     // "Ready for backtesting" or instructions
}
```

---

## `check_symbol_data_status`

Validate if a symbol has sufficient historical tick data for a specified date range before running backtest. Prevents failed backtests due to missing history data.

### Input schema

```typescript
{
  symbol: string;        // e.g., "XAUUSDc"
  from_date: string;     // "YYYY.MM.DD"
  to_date: string;       // "YYYY.MM.DD"
}
```

### Output schema

```typescript
{
  success: boolean;
  symbol: string;
  server: string;
  has_sufficient_data: boolean;
  requested_range: { from: string; to: string };
  data_range: string;           // "YYYY.MM.DD - YYYY.MM.DD" or "unknown"
  years_available: number;      // Count of years with data
  hcc_files_count: number;      // Number of history cache files
  warnings: string[] | null;    // Data range issues
  suggestion: string;           // Action recommendation
}
```

---

## `check_mt5_status`

Check if MT5 terminal is properly installed and configured. Returns comprehensive status of all required components.

### Input schema

```typescript
{}  // No parameters
```

### Output schema

```typescript
{
  success: boolean;
  terminal_ready: boolean;      // true if all components present
  checks: {
    mt5_dir_exists: boolean;
    terminal64_exe: boolean;
    metaeditor64_exe: boolean;
    metatester64_exe: boolean;
    wine_executable: boolean;
    wine_path: string | null;
  };
  mt5_version: string | null;
  current_account: {
    login: string;
    server: string;
  } | null;
  hint: string;
}
```

---

## `get_backtest_history`

List all backtests previously run for a specific EA and/or symbol with summary metrics. Use for tracking performance over time.

### Input schema

```typescript
{
  expert?: string;       // Filter by EA name
  symbol?: string;       // Filter by symbol
  limit?: number;        // Max results (default: 10)
}
```

### Output schema

```typescript
{
  success: boolean;
  count: number;
  total: number;
  filters: {
    expert: string | null;
    symbol: string | null;
  };
  history: Array<{
    report_dir: string;
    date: string | null;
    expert: string | null;
    symbol: string | null;
    period: string | null;
    profit: number | null;
    profit_factor: number | null;
    expected_payoff: number | null;
    drawdown_pct: number | null;
    total_trades: number | null;
    win_rate: number | null;
  }>;
  hint: string;
}
```

---

## `compare_backtests`

Compare two or more backtest results side-by-side with key metrics analysis. Includes profit/drawdown differences and verdict on which performed better.

### Input schema

```typescript
{
  report_dirs: string[];  // List of report directory paths to compare
}
```

### Output schema

```typescript
{
  success: boolean;
  count: number;
  comparisons: Array<{
    report_dir: string;
    expert: string | null;
    symbol: string | null;
    net_profit: number | null;
    profit_factor: number | null;
    drawdown_pct: number | null;
    total_trades: number | null;
    win_rate: number | null;
    expected_payoff: number | null;
    recovery_factor: number | null;
    sharpe_ratio: number | null;
  }>;
  analysis: Array<{
    compare_to: string | null;
    report: string | null;
    profit_diff: number;
    profit_pct_change: number;
    drawdown_diff: number;
    profit_factor_diff: number;
    verdict: "better" | "worse" | "mixed";
  }> | null;
  verdict: string | null;  // "Best: <report_dir>"
}
```

---

## `init_project`

Create a new MQL5 project with standard directory structure and template files. Supports scalper, swing, grid, and basic templates.

### Input schema

```typescript
{
  name: string;                    // Project name (used for EA filename)
  template?: "scalper" | "swing" | "grid" | "basic";  // Default: "basic"
}
```

### Output schema

```typescript
{
  success: boolean;
  project_name: string;
  template: string;
  created_files: string[];  // Paths to created files
  hint: string;
}
```

---

## `validate_ea_syntax`

Perform pre-compile syntax check on MQL5 source file without running full compilation. Detects common issues before expensive MetaEditor compilation.

### Input schema

```typescript
{
  path: string;  // Path to .mq5 source file
}
```

### Output schema

```typescript
{
  success: boolean;
  valid: boolean;
  path: string;
  checks: {
    has_on_init: boolean;
    has_on_tick: boolean;
    has_on_deinit: boolean;
    lines: number;
  };
  errors: Array<{
    line: number;
    message: string;
    severity: "error";
  }> | null;
  warnings: Array<{
    line: number;
    message: string;
    severity: "warning";
  }> | null;
  hint: string;
}
```

---

## `create_set_template`

Generate a .set parameter file template based on an EA's input variables. Automatically parses input declarations from source code.

### Input schema

```typescript
{
  ea: string;              // EA name or path to .mq5/.ex5 file
  output_path?: string;    // Optional custom output path
}
```

### Output schema

```typescript
{
  success: boolean;
  ea: string;
  inputs_found: number;
  inputs: Array<{
    name: string;
    type: string;
    default: string;
    description: string | null;
  }>;
  set_file: string;  // Path to generated file
  hint: string;
}
```

---

## `export_report`

Export backtest report to various formats (CSV, JSON, Markdown) for external analysis or sharing.

### Input schema

```typescript
{
  report_dir: string;        // Path to backtest report directory
  format?: "csv" | "json" | "md";  // Default: "csv"
  output_path?: string;      // Optional custom output file path
}
```

### Output schema

```typescript
{
  success: boolean;
  format: string;
  output_file: string;
  source: string;
  hint: string;
}
```

---

## `archive_report`

Convert a backtest report directory into a compact JSON entry appended to `config/backtest_history.json`. Idempotent — re-archiving the same report is a no-op. Optionally deletes the source directory to reclaim disk space.

### Input schema

```typescript
{
  report_dir?: string;     // Directory to archive. Omit for latest.
  delete_after?: boolean;  // Delete source dir after archiving (default: false)
  verdict?: "winner" | "loser" | "marginal" | "reference";
  notes?: string;          // Free-text notes for the entry
  tags?: string[];         // Tags e.g. ["tight-sl", "new-filter"]
}
```

### Output schema

```typescript
{
  success: boolean;
  id: string;              // Report dir basename used as history entry id
  already_existed: boolean;
  deleted_source: boolean;
  history_file: string;    // Absolute path to backtest_history.json
  entry_summary: {
    ea: string;
    symbol: string;
    metrics: { net_profit: number; profit_factor: number; max_dd_pct: number; sharpe_ratio: number; total_trades: number; };
    verdict: string | null;
  };
}
```

---

## `archive_all_reports`

Bulk-archive all backtest report directories into `config/backtest_history.json`. Entries already in history are skipped. Use `delete_after=true` to reclaim disk space while preserving all results as JSON. Optimization dirs (`_opt` suffix) are never deleted.

### Input schema

```typescript
{
  delete_after?: boolean;  // Delete source dirs after archiving (default: false)
  keep_last?: number;      // Protect newest N dirs from deletion even with delete_after=true (default: 5)
  dry_run?: boolean;       // Preview without making changes (default: false)
}
```

### Output schema

```typescript
{
  success: boolean;
  dry_run: boolean;
  archived_count: number;
  skipped_count: number;   // Already in history
  deleted_count: number;
  failed_count: number;    // Dirs with no parseable metrics
  archived: string[];
  skipped: string[];
  deleted: string[];
  failed: string[];
  history_file: string;
}
```

---

## `get_history`

Query `config/backtest_history.json` with filters and sorting. Strips `monthly_pnl` arrays by default — set `include_monthly=true` when you need the full breakdown.

### Input schema

```typescript
{
  ea?: string;               // Substring match on EA name
  symbol?: string;           // Exact match (uppercase)
  verdict?: "winner" | "loser" | "marginal" | "reference";
  tag?: string;              // Entry must contain this tag
  min_profit?: number;       // net_profit >= this
  max_dd_pct?: number;       // max_dd_pct <= this
  sort_by?: "date" | "profit" | "dd" | "sharpe";  // Default: date, newest first
  limit?: number;            // Default: 20
  include_monthly?: boolean; // Include monthly_pnl arrays (default: false)
}
```

### Output schema

```typescript
{
  success: boolean;
  count: number;
  entries: Array<{
    id: string;                    // Report dir basename
    archived_at: string;           // ISO timestamp
    report_dir_deleted: boolean;
    ea: string;
    symbol: string;
    timeframe: string;
    from_date: string;
    to_date: string;
    metrics: {
      net_profit: number;
      profit_factor: number;
      max_dd_pct: number;
      sharpe_ratio: number;
      total_trades: number;
      recovery_factor: number;
      win_rate_pct: number;
      expected_payoff: number;
    };
    summary?: {
      green_months: number;
      total_months: number;
      worst_month: string;
      worst_month_pnl: number;
      dominant_exit?: string;
      max_win_streak?: number;
      max_loss_streak?: number;
    };
    worst_dd_event?: {
      peak_dd_pct: number;
      start_date: string;
      end_date: string;
      duration_days: number;
      cause: string;
    };
    monthly_pnl?: Array<{ month: string; pnl: number; trades: number; green: boolean; }>;
    verdict: string | null;
    notes: string;
    tags: string[];
    promoted_to_baseline: boolean;
  }>;
}
```

---

## `promote_to_baseline`

Write a backtest result to `config/baseline.json` — the production reference used by `compare_baseline` and the Claude Code baseline hook. Also marks the source history entry as `promoted_to_baseline: true`.

### Input schema

```typescript
{
  // Provide one: history_id, report_dir, or neither (uses latest report)
  history_id?: string;     // Entry id from get_history
  report_dir?: string;     // Direct path to report directory
  notes?: string;          // Written to baseline.json notes field
}
```

### Output schema

```typescript
{
  success: boolean;
  baseline_file: string;
  baseline: {
    ea: string;
    symbol: string;
    period: string;            // "YYYY-MM-DD/YYYY-MM-DD"
    net_profit: number;
    profit_factor: number;
    max_drawdown_pct: number;
    sharpe_ratio: number;
    total_trades: number;
    recovery_factor: number;
    promoted_from: string;     // History entry id
    promoted_at: string;       // Date promoted (YYYY-MM-DD)
    notes: string;
  };
}
```

### Example

```json
// Input
{ "history_id": "20250619_143022_MyEA_XAUUSD_M5", "notes": "v1.3 after walk-forward validation" }

// Output
{
  "success": true,
  "baseline_file": "/path/to/config/baseline.json",
  "baseline": {
    "ea": "MyEA",
    "symbol": "XAUUSD",
    "period": "2025-01-01/2025-06-30",
    "net_profit": 4832.10,
    "profit_factor": 1.54,
    "max_drawdown_pct": 12.3,
    "sharpe_ratio": 1.18,
    "total_trades": 891,
    "recovery_from": "20250619_143022_MyEA_XAUUSD_M5",
    "promoted_at": "2025-06-20",
    "notes": "v1.3 after walk-forward validation"
  }
}
```

---

## `annotate_history`

Update the verdict, notes, or tags on an existing history entry. Use this after `compare_baseline` to record the decision, or to tag runs for later retrieval.

### Input schema

```typescript
{
  history_id: string;      // Required — entry id to update
  verdict?: "winner" | "loser" | "marginal" | "reference";
  notes?: string;          // Replaces existing notes
  tags?: string[];         // Replaces existing tags
  add_tags?: string[];     // Appends to existing tags without overwriting
}
```

### Output schema

```typescript
{
  success: boolean;
  id: string;
  verdict: string | null;
  notes: string;
  tags: string[];
}
```

---

## Token-efficient usage patterns

### Surveying past runs

```
list_reports(limit=10)          → see what's there (live dirs)
get_history(ea="MyEA", limit=10) → see what's been archived
analyze_report(report_dir=X)    → drill into one specific run
```

Never call `analyze_report` on multiple directories to find the best run — use `list_reports` or `get_history` first.

### Checking logs without noise

```
tail_log(job_id=X, filter=errors)   → only failures
tail_log(report_dir=X, n=20)        → last 20 lines of backtest progress
```

### Managing disk space

```
archive_all_reports(dry_run=true)               → preview what would be archived
archive_all_reports(delete_after=true, keep_last=3)  → archive all, delete old, keep 3 newest
get_history(sort_by=profit, limit=5)            → find best archived runs
```

### Labelling experiments

```
annotate_history(history_id=X, verdict="loser", notes="SL too tight, reversed at L3")
annotate_history(history_id=X, add_tags=["walk-forward-fail"])
get_history(verdict="winner")                   → all winners across all sessions
```

### Promoting a new production config

```
run_backtest(...)
compare_baseline(...)                           → get verdict
archive_report(delete_after=true, verdict="winner")
promote_to_baseline(notes="v1.4 after WF")     → update baseline.json
```

### Managing cache

```
cache_status()                                  → see symbol breakdown and total size
clean_cache(symbol=XAUUSD, dry_run=true)        → preview
clean_cache(symbol=XAUUSD)                      → execute
```

### Pre-flight validation

```
get_active_account()                            → current login, server, available symbols
check_symbol_data_status(symbol=XAUUSD, from=2025.01.01, to=2025.03.31)
                                                → verify data availability before backtest
check_mt5_status()                              → verify MT5 installation and readiness
validate_ea_syntax(path=MyEA.mq5)               → pre-compile syntax check
```

### Project management

```
init_project(name=MyStrategy, template=scalper)  → scaffold new EA with template
create_set_template(ea=MyEA)                     → generate .set from EA inputs
export_report(report_dir=..., format=csv)         → export to CSV/JSON/Markdown
```

### History and comparison

```
get_backtest_history(expert=MyEA, limit=10)       → list past backtests with metrics
compare_backtests(report_dirs=["dir1", "dir2"])   → side-by-side comparison
```

### Working with set files

```
# Inspect
list_set_files(ea="MyEA")               → all variants, swept param counts, combinations
describe_sweep(path=MyEA_opt.set)       → verify 240 combinations before launching opt
diff_set_files(a=v1.2.set, b=v1.3.set) → only changed params, not full file content

# Edit (never read+write manually)
patch_set_file(path, {TP_Pips: 350})    → change one param, keep everything else intact
clone_set_file(src, dest, overrides)    → create variant from base in one call

# Generate after optimization
set_from_optimization(                  → map results[0].params → clean backtest .set
  path=MyEA_v1.3.set,
  params=results[0].params,
  template=MyEA_base.set                → fills non-swept params from existing file
)
```

---

## `list_symbols`

List all available symbols in the MT5 terminal.

**When to call:** To verify a symbol is available before running backtests, or to discover available symbols.

### Input schema

```typescript
{
  // No inputs required
}
```

### Output schema

```typescript
{
  success: boolean;
  symbols: Array<{
    name: string;          // e.g. "XAUUSD", "EURUSD"
    description?: string;   // Symbol description
    visible: boolean;       // Whether symbol is visible in Market Watch
  }>;
  error?: string;
}
```

---

## `check_update`

Check if a newer version of MT5-Quant is available on GitHub.

**When to call:** Periodically to stay up to date with the latest features and fixes.

### Input schema

```typescript
{
  // No inputs required
}
```

### Output schema

```typescript
{
  success: boolean;
  current_version: string;  // Current version, e.g. "1.31.5"
  latest_version: string;   // Latest version from GitHub releases
  update_available: boolean;
  download_url?: string;    // URL to latest release if update available
  release_notes?: string;   // Release notes from latest version
  error?: string;
}
```

---

## `update`

Update MT5-Quant to the latest version from GitHub releases.

**When to call:** After `check_update` indicates a newer version is available.

### Input schema

```typescript
{
  // No inputs required
}
```

### Output schema

```typescript
{
  success: boolean;
  message: string;          // Update status message
  new_version: string;      // Version installed
  error?: string;
}
```

---

## `healthcheck`

Quick server health check to verify the MCP server is running.

**When to call:** To verify the server is responsive after installation or configuration changes.

### Input schema

```typescript
{
  // No inputs required
}
```

### Output schema

```typescript
{
  success: boolean;
  version: string;          // MT5-Quant version
  status: "healthy" | "unhealthy";
  uptime_seconds: number;
  error?: string;
}
```

---

## `list_experts`

List all Expert Advisors (EAs) in the MQL5/Experts directory.

**When to call:** To discover available EAs before running backtests.

### Input schema

```typescript
{
  // No inputs required
}
```

### Output schema

```typescript
{
  success: boolean;
  experts: Array<{
    name: string;           // EA name without extension
    path: string;           // Full path to .mq5 file
    has_ex5: boolean;      // Whether compiled .ex5 exists
    modified: string;       // Last modified timestamp
  }>;
  error?: string;
}
```

---

## `list_indicators`

List all indicators in the MQL5/Indicators directory.

**When to call:** To discover available indicators for use in projects.

### Input schema

```typescript
{
  // No inputs required
}
```

### Output schema

```typescript
{
  success: boolean;
  indicators: Array<{
    name: string;           // Indicator name without extension
    path: string;           // Full path to .mq5 file
    has_ex5: boolean;      // Whether compiled .ex5 exists
    modified: string;       // Last modified timestamp
  }>;
  error?: string;
}
```

---

## `list_scripts`

List all scripts in the MQL5/Scripts directory.

**When to call:** To discover available scripts for one-time execution.

### Input schema

```typescript
{
  // No inputs required
}
```

### Output schema

```typescript
{
  success: boolean;
  scripts: Array<{
    name: string;           // Script name without extension
    path: string;           // Full path to .mq5 file
    has_ex5: boolean;      // Whether compiled .ex5 exists
    modified: string;       // Last modified timestamp
  }>;
  error?: string;
}
```

---

## `search_experts`

Search EAs by name pattern across all directories.

**When to call:** To find EAs matching a specific pattern when the exact name is unknown.

### Input schema

```typescript
{
  pattern: string;          // Search pattern, e.g. "Grid" or "v1."
}
```

### Output schema

```typescript
{
  success: boolean;
  matches: Array<{
    name: string;           // EA name without extension
    path: string;           // Full path to .mq5 file
    has_ex5: boolean;      // Whether compiled .ex5 exists
    modified: string;       // Last modified timestamp
  }>;
  error?: string;
}
```

---

## `search_indicators`

Search indicators by name pattern.

**When to call:** To find indicators matching a specific pattern.

### Input schema

```typescript
{
  pattern: string;          // Search pattern
}
```

### Output schema

```typescript
{
  success: boolean;
  matches: Array<{
    name: string;           // Indicator name without extension
    path: string;           // Full path to .mq5 file
    has_ex5: boolean;      // Whether compiled .ex5 exists
    modified: string;       // Last modified timestamp
  }>;
  error?: string;
}
```

---

## `search_scripts`

Search scripts by name pattern.

**When to call:** To find scripts matching a specific pattern.

### Input schema

```typescript
{
  pattern: string;          // Search pattern
}
```

### Output schema

```typescript
{
  success: boolean;
  matches: Array<{
    name: string;           // Script name without extension
    path: string;           // Full path to .mq5 file
    has_ex5: boolean;      // Whether compiled .ex5 exists
    modified: string;       // Last modified timestamp
  }>;
  error?: string;
}
```

---

## `copy_indicator_to_project`

Copy indicator to project directory.

**When to call:** To include an indicator in your EA project.

### Input schema

```typescript
{
  indicator_name: string;   // Name of indicator to copy
  project_dir: string;     // Target project directory path
}
```

### Output schema

```typescript
{
  success: boolean;
  source_path: string;     // Original indicator path
  target_path: string;     // Copied indicator path
  error?: string;
}
```

---

## `copy_script_to_project`

Copy script to project directory.

**When to call:** To include a script in your EA project.

### Input schema

```typescript
{
  script_name: string;      // Name of script to copy
  project_dir: string;     // Target project directory path
}
```

### Output schema

```typescript
{
  success: boolean;
  source_path: string;     // Original script path
  target_path: string;     // Copied script path
  error?: string;
}
```

---

## `diagnose_wine`

Check Wine installation, version, and prefix health.

**When to call:** When experiencing Wine-related issues or to verify Wine setup.

### Input schema

```typescript
{
  // No inputs required
}
```

### Output schema

```typescript
{
  success: boolean;
  wine_found: boolean;
  wine_path?: string;
  wine_version?: string;
  prefix_path?: string;
  prefix_health: "healthy" | "corrupted" | "missing";
  error?: string;
}
```

---

## `get_mt5_logs`

Get MT5 terminal, tester, or MetaEditor logs with filtering.

**When to call:** To diagnose backtest failures or compile errors.

### Input schema

```typescript
{
  log_type: "terminal" | "tester" | "metaeditor";
  lines?: number;           // Number of lines to retrieve (default: 100)
  filter?: "all" | "errors" | "warnings"; // Default: "all"
}
```

### Output schema

```typescript
{
  success: boolean;
  log_path: string;
  lines: Array<{
    timestamp: string;
    level: "info" | "warning" | "error";
    message: string;
  }>;
  error?: string;
}
```

---

## `search_mt5_errors`

Search logs for error patterns (crash, exception, access violation).

**When to call:** To quickly find crash causes in logs.

### Input schema

```typescript
{
  log_type: "terminal" | "tester" | "metaeditor" | "all";
  patterns?: string[];      // Custom error patterns (default: common MT5 errors)
  max_results?: number;     // Maximum error entries to return (default: 50)
}
```

### Output schema

```typescript
{
  success: boolean;
  errors: Array<{
    timestamp: string;
    log_type: string;
    message: string;
    context?: string;      // Surrounding lines for context
  }>;
  total_found: number;
  error?: string;
}
```

---

## `check_mt5_process`

Check if MT5 processes are running, get PID, CPU, memory usage.

**When to call:** To verify MT5 is running or to check for stuck processes.

### Input schema

```typescript
{
  // No inputs required
}
```

### Output schema

```typescript
{
  success: boolean;
  processes: Array<{
    pid: number;
    name: string;           // "terminal64.exe" or "metatester64.exe"
    cpu_percent: number;
    memory_mb: number;
    uptime_seconds: number;
    status: "running" | "zombie" | "stopped";
  }>;
  error?: string;
}
```

---

## `kill_mt5_process`

Kill stuck MT5 processes.

**When to call:** When MT5 is stuck or hung and needs to be terminated.

### Input schema

```typescript
{
  pid?: number;            // Specific PID to kill (optional, kills all if omitted)
  force?: boolean;         // Force kill wineserver too (default: false)
}
```

### Output schema

```typescript
{
  success: boolean;
  killed_pids: number[];
  message: string;
  error?: string;
}
```

---

## `check_system_resources`

Check disk space, memory, CPU availability.

**When to call:** Before running long optimizations to ensure sufficient resources.

### Input schema

```typescript
{
  // No inputs required
}
```

### Output schema

```typescript
{
  success: boolean;
  disk: {
    path: string;
    total_gb: number;
    free_gb: number;
    used_percent: number;
  };
  memory: {
    total_mb: number;
    free_mb: number;
    used_percent: number;
  };
  cpu: {
    cores: number;
    usage_percent: number;
  };
  error?: string;
}
```

---

## `validate_mt5_config`

Validate terminal.ini and tester configuration files.

**When to call:** When experiencing configuration-related backtest failures.

### Input schema

```typescript
{
  // No inputs required (auto-detects config paths)
}
```

### Output schema

```typescript
{
  success: boolean;
  terminal_ini: {
    path: string;
    valid: boolean;
    issues?: string[];
  };
  tester_ini?: {
    path: string;
    valid: boolean;
    issues?: string[];
  };
  error?: string;
}
```

---

## `get_wine_prefix_info`

Get Wine prefix details: Windows version, installed programs, registry.

**When to call:** To diagnose Wine prefix issues or verify Wine setup.

### Input schema

```typescript
{
  // No inputs required
}
```

### Output schema

```typescript
{
  success: boolean;
  prefix_path: string;
  windows_version: string;
  installed_programs: string[];
  registry_keys?: Array<{
    key: string;
    value: string;
  }>;
  error?: string;
}
```

---

## `get_backtest_crash_info`

Investigate backtest failures: incomplete markers, missing metrics.json, Wine/MT5 errors.

**When to call:** When a backtest fails unexpectedly.

### Input schema

```typescript
{
  report_dir: string;       // Path to the failed backtest report directory
}
```

### Output schema

```typescript
{
  success: boolean;
  status: "complete" | "incomplete" | "crashed" | "missing";
  issues: Array<{
    type: string;
    message: string;
    severity: "error" | "warning";
  }>;
  error_log?: string;
  error?: string;
}
```

---

## `get_latest_report`

Get most recent report with optional equity chart.

**When to call:** To quickly access the latest backtest results.

### Input schema

```typescript
{
  include_chart?: boolean;  // Include equity chart data (default: false)
}
```

### Output schema

```typescript
{
  success: boolean;
  report: {
    id: string;
    report_dir: string;
    ea: string;
    symbol: string;
    timeframe: string;
    from_date: string;
    to_date: string;
    metrics: {
      net_profit: number;
      profit_factor: number;
      max_dd_pct: number;
      total_trades: number;
    };
    equity_chart?: Array<{date: string; equity: number}>;
  };
  error?: string;
}
```

---

## `search_reports`

Find reports by EA, symbol, date range, or profit criteria.

**When to call:** To find specific reports matching criteria.

### Input schema

```typescript
{
  ea?: string;
  symbol?: string;
  from_date?: string;      // "YYYY-MM-DD"
  to_date?: string;        // "YYYY-MM-DD"
  min_profit?: number;
  max_profit?: number;
  min_profit_factor?: number;
  max_dd_pct?: number;
  limit?: number;          // Max results (default: 50)
}
```

### Output schema

```typescript
{
  success: boolean;
  reports: Array<{
    id: string;
    report_dir: string;
    ea: string;
    symbol: string;
    timeframe: string;
    from_date: string;
    to_date: string;
    metrics: {
      net_profit: number;
      profit_factor: number;
      max_dd_pct: number;
      total_trades: number;
    };
  }>;
  total: number;
  error?: string;
}
```

---

## `get_report_by_id`

Get specific report by ID with equity chart.

**When to call:** To retrieve a specific report's full details.

### Input schema

```typescript
{
  report_id: string;       // Report directory basename
  include_chart?: boolean;  // Include equity chart data (default: false)
}
```

### Output schema

```typescript
{
  success: boolean;
  report: {
    id: string;
    report_dir: string;
    ea: string;
    symbol: string;
    timeframe: string;
    from_date: string;
    to_date: string;
    metrics: {
      net_profit: number;
      profit_factor: number;
      max_dd_pct: number;
      total_trades: number;
      sharpe_ratio: number;
      recovery_factor: number;
      win_rate_pct: number;
    };
    equity_chart?: Array<{date: string; equity: number}>;
  };
  error?: string;
}
```

---

## `get_reports_summary`

Aggregate stats: counts, averages, pass rates.

**When to call:** To get overview statistics across all reports.

### Input schema

```typescript
{
  ea?: string;             // Filter by EA
  symbol?: string;         // Filter by symbol
  from_date?: string;      // Filter by date range
  to_date?: string;
}
```

### Output schema

```typescript
{
  success: boolean;
  summary: {
    total_reports: number;
    avg_profit: number;
    avg_profit_factor: number;
    avg_dd_pct: number;
    profitable_count: number;
    pass_rate_pct: number;
  };
  error?: string;
}
```

---

## `get_best_reports`

Top N reports sorted by any metric (profit factor, drawdown, etc.).

**When to call:** To find the best performing reports.

### Input schema

```typescript
{
  sort_by: "net_profit" | "profit_factor" | "sharpe_ratio" | "recovery_factor" | "win_rate_pct";
  order: "desc" | "asc";  // Default: "desc"
  limit?: number;          // Max results (default: 10)
  ea?: string;
  symbol?: string;
}
```

### Output schema

```typescript
{
  success: boolean;
  reports: Array<{
    id: string;
    report_dir: string;
    ea: string;
    symbol: string;
    metrics: {
      net_profit: number;
      profit_factor: number;
      max_dd_pct: number;
      sharpe_ratio: number;
      recovery_factor: number;
      win_rate_pct: number;
    };
  }>;
  error?: string;
}
```

---

## `search_reports_by_tags`

Find reports by tags.

**When to call:** To find reports tagged with specific keywords.

### Input schema

```typescript
{
  tags: string[];          // Tags to search for
  match_all?: boolean;     // Require all tags (default: false)
  limit?: number;
}
```

### Output schema

```typescript
{
  success: boolean;
  reports: Array<{
    id: string;
    report_dir: string;
    tags: string[];
    metrics: {
      net_profit: number;
      profit_factor: number;
      max_dd_pct: number;
    };
  }>;
  error?: string;
}
```

---

## `search_reports_by_date_range`

Query by backtest date range.

**When to call:** To find reports from a specific time period.

### Input schema

```typescript
{
  from_date: string;       // "YYYY-MM-DD"
  to_date: string;         // "YYYY-MM-DD"
  limit?: number;
}
```

### Output schema

```typescript
{
  success: boolean;
  reports: Array<{
    id: string;
    report_dir: string;
    timestamp: string;
    metrics: {
      net_profit: number;
      profit_factor: number;
      max_dd_pct: number;
    };
  }>;
  error?: string;
}
```

---

## `search_reports_by_notes`

Full-text search in report notes.

**When to call:** To find reports with specific notes.

### Input schema

```typescript
{
  query: string;           // Search query
  limit?: number;
}
```

### Output schema

```typescript
{
  success: boolean;
  reports: Array<{
    id: string;
    report_dir: string;
    notes: string;
    metrics: {
      net_profit: number;
      profit_factor: number;
      max_dd_pct: number;
    };
  }>;
  error?: string;
}
```

---

## `get_reports_by_set_file`

Find all reports using a specific .set file.

**When to call:** To see all backtests run with a specific parameter set.

### Input schema

```typescript
{
  set_file: string;        // .set file name (without path)
}
```

### Output schema

```typescript
{
  success: boolean;
  reports: Array<{
    id: string;
    report_dir: string;
    set_file: string;
    metrics: {
      net_profit: number;
      profit_factor: number;
      max_dd_pct: number;
    };
  }>;
  error?: string;
}
```

---

## `get_comparable_reports`

Find comparable reports (same EA/symbol/timeframe).

**When to call:** To find reports for comparison/analysis.

### Input schema

```typescript
{
  ea: string;
  symbol: string;
  timeframe?: string;     // Optional, uses default if omitted
}
```

### Output schema

```typescript
{
  success: boolean;
  reports: Array<{
    id: string;
    report_dir: string;
    from_date: string;
    to_date: string;
    metrics: {
      net_profit: number;
      profit_factor: number;
      max_dd_pct: number;
      total_trades: number;
    };
  }>;
  error?: string;
}
```

---

## `export_deals_csv`

Export deals for a report to a CSV file on demand. Deals are stored in the database — use this when you need a CSV file for external tools (Excel, pandas, etc.).

**When to call:** When you need a `deals.csv` file. CSV is not written automatically after backtests anymore.

### Input schema

```typescript
{
  report_id?: string;       // Report ID to export (default: latest report)
  output_path?: string;     // File path for CSV output (default: <report_dir>/deals.csv)
}
```

### Output schema

```typescript
{
  success: boolean;
  report_id: string;
  deals_count: number;
  output_path: string;      // Absolute path to the written CSV file
}
```

### Example

```json
// Input — export latest report to default path
{}

// Input — export specific report to custom path
{
  "report_id": "20260422_051041_DPS21_XAUUSDc_M5_1",
  "output_path": "/tmp/dps21_deals.csv"
}

// Output
{
  "success": true,
  "report_id": "20260422_051041_DPS21_XAUUSDc_M5_1",
  "deals_count": 891,
  "output_path": "/Users/…/reports/20260422_051041_DPS21_XAUUSDc_M5_1/deals.csv"
}
```

---

## Granular Analytics — Common Input Pattern

All granular analytics tools below (`analyze_monthly_pnl` through `analyze_efficiency`, plus `list_deals` and `search_deals_*`) share the same report resolution logic:

```typescript
{
  report_id?: string;   // Preferred: ID from list_reports
  report_dir?: string;  // Legacy: filesystem path (looks up DB entry)
  // Omit both → uses the latest report automatically
}
```

Deals are loaded from **SQLite DB**, not from CSV files. The `report_dir` parameter is kept for backward compatibility — if your report is in the DB, passing `report_dir` will resolve to its `report_id` automatically.

---

## `analyze_monthly_pnl`

Monthly P/L breakdown only.

**When to call:** To analyze performance by month without full analysis.

### Input schema

```typescript
{
  report_id?: string;       // Preferred: from list_reports
  report_dir?: string;      // Legacy: path to report directory
}
// Omit all args to use the latest report
```

### Output schema

```typescript
{
  success: boolean;
  monthly_data: Array<{
    month: string;          // "2025-01"
    profit: number;
    trades: number;
    win_rate: number;
  }>;
  green_months: number;
  total_months: number;
  error?: string;
}
```

---

## `analyze_drawdown_events`

Drawdown events and causes only.

**When to call:** To identify and analyze drawdown periods.

### Input schema

```typescript
{
  report_dir: string;
}
```

### Output schema

```typescript
{
  success: boolean;
  drawdowns: Array<{
    start_date: string;
    end_date: string;
    depth_pct: number;
    duration_days: number;
    recovery_days: number;
    cause?: string;
  }>;
  worst_dd_event: {
    depth_pct: number;
    date: string;
  };
  error?: string;
}
```

---

## `analyze_top_losses`

Worst losing deals only.

**When to call:** To identify the biggest losing trades for analysis.

### Input schema

```typescript
{
  report_dir: string;
  top_n?: number;          // Number of worst deals to return (default: 10)
}
```

### Output schema

```typescript
{
  success: boolean;
  worst_deals: Array<{
    entry_time: string;
    exit_time: string;
    profit: number;
    profit_pct: number;
    volume: number;
    comment?: string;
  }>;
  error?: string;
}
```

---

## `analyze_loss_sequences`

Consecutive loss patterns only.

**When to call:** To analyze losing streak patterns.

### Input schema

```typescript
{
  report_dir: string;
}
```

### Output schema

```typescript
{
  success: boolean;
  loss_streaks: Array<{
    start_index: number;
    end_index: number;
    length: number;
    total_loss: number;
    avg_loss: number;
  }>;
  max_loss_streak: {
    length: number;
    total_loss: number;
  };
  error?: string;
}
```

---

## `analyze_position_pairs`

Position hold time and P/L pairs.

**When to call:** To analyze relationship between hold time and profit.

### Input schema

```typescript
{
  report_dir: string;
}
```

### Output schema

```typescript
{
  success: boolean;
  pairs: Array<{
    hold_time_minutes: number;
    profit: number;
    profit_pct: number;
    count: number;
  }>;
  correlation: number;
  error?: string;
}
```

---

## `analyze_direction_bias`

Buy vs Sell performance.

**When to call:** To analyze directional bias in trading.

### Input schema

```typescript
{
  report_dir: string;
}
```

### Output schema

```typescript
{
  success: boolean;
  buy_trades: {
    count: number;
    profit: number;
    win_rate: number;
  };
  sell_trades: {
    count: number;
    profit: number;
    win_rate: number;
  };
  bias: "buy" | "sell" | "neutral";
  error?: string;
}
```

---

## `analyze_streaks`

Win/loss streak analysis.

**When to call:** To analyze winning and losing streak patterns.

### Input schema

```typescript
{
  report_dir: string;
}
```

### Output schema

```typescript
{
  success: boolean;
  win_streaks: Array<{
    length: number;
    total_profit: number;
  }>;
  loss_streaks: Array<{
    length: number;
    total_loss: number;
  }>;
  max_win_streak: number;
  max_loss_streak: number;
  error?: string;
}
```

---

## `analyze_concurrent_peak`

Peak simultaneous positions.

**When to call:** To analyze maximum position concurrency.

### Input schema

```typescript
{
  report_dir: string;
}
```

### Output schema

```typescript
{
  success: boolean;
  max_concurrent: number;
  avg_concurrent: number;
  distribution: Array<{
    concurrent_count: number;
    occurrences: number;
  }>;
  error?: string;
}
```

---

## `list_deals`

List individual deals with filters (type, profit range, volume, dates). Loads from SQLite DB.

**When to call:** To query individual trades with specific criteria.

### Input schema

```typescript
{
  report_id?: string;       // Preferred: from list_reports
  report_dir?: string;      // Legacy: path to report directory
  // Omit all to use latest report
  deal_type?: "buy" | "sell" | "all";
  min_profit?: number;
  max_profit?: number;
  min_volume?: number;
  max_volume?: number;
  from_date?: string;      // "YYYY-MM-DD"
  to_date?: string;        // "YYYY-MM-DD"
  limit?: number;
}
```

### Output schema

```typescript
{
  success: boolean;
  deals: Array<{
    entry_time: string;
    exit_time: string;
    type: "buy" | "sell";
    profit: number;
    profit_pct: number;
    volume: number;
    comment?: string;
    magic?: number;
  }>;
  total: number;
  error?: string;
}
```

---

## `search_deals_by_comment`

Full-text search in deal comments (e.g., "Layer #3"). Loads from SQLite DB.

**When to call:** To find deals with specific comment patterns.

### Input schema

```typescript
{
  report_id?: string;      // Preferred: from list_reports
  report_dir?: string;     // Legacy: path to report directory
  query: string;           // Search pattern in comment field (required)
  limit?: number;
}
```

### Output schema

```typescript
{
  success: boolean;
  deals: Array<{
    entry_time: string;
    exit_time: string;
    type: "buy" | "sell";
    profit: number;
    profit_pct: number;
    volume: number;
    comment: string;
    magic?: number;
  }>;
  total: number;
  error?: string;
}
```

---

## `search_deals_by_magic`

Filter deals by EA magic number.

**When to call:** To find trades from a specific EA (by magic number).

### Input schema

```typescript
{
  report_dir: string;
  magic: number;           // EA magic number to filter by
  limit?: number;
}
```

### Output schema

```typescript
{
  success: boolean;
  deals: Array<{
    entry_time: string;
    exit_time: string;
    type: "buy" | "sell";
    profit: number;
    profit_pct: number;
    volume: number;
    comment?: string;
    magic: number;
  }>;
  total: number;
  error?: string;
}
```

---

## `analyze_profit_distribution`

Profit histogram: small/medium/large wins and losses.

**When to call:** To understand profit distribution across trade sizes.

### Input schema

```typescript
{
  report_dir: string;
}
```

### Output schema

```typescript
{
  success: boolean;
  distribution: {
    small_wins: {count: number; avg_profit: number};
    medium_wins: {count: number; avg_profit: number};
    large_wins: {count: number; avg_profit: number};
    small_losses: {count: number; avg_loss: number};
    medium_losses: {count: number; avg_loss: number};
    large_losses: {count: number; avg_loss: number};
  };
  error?: string;
}
```

---

## `analyze_time_performance`

Performance by hour of day and day of week.

**When to call:** To identify best/worst trading times.

### Input schema

```typescript
{
  report_dir: string;
}
```

### Output schema

```typescript
{
  success: boolean;
  hourly_performance: Array<{
    hour: number;
    profit: number;
    trades: number;
    win_rate: number;
  }>;
  daily_performance: Array<{
    day: "Mon" | "Tue" | "Wed" | "Thu" | "Fri";
    profit: number;
    trades: number;
    win_rate: number;
  }>;
  error?: string;
}
```

---

## `analyze_hold_time_distribution`

Hold time buckets + correlation with profit.

**When to call:** To analyze relationship between position duration and profit.

### Input schema

```typescript
{
  report_dir: string;
}
```

### Output schema

```typescript
{
  success: boolean;
  buckets: Array<{
    label: string;        // e.g. "<5m", "5-15m", "15-60m", ">1h"
    min_minutes: number;
    max_minutes: number;
    count: number;
    avg_profit: number;
    win_rate: number;
  }>;
  correlation: number;
  error?: string;
}
```

---

## `analyze_layer_performance`

Grid/martingale layer analysis from comments.

**When to call:** To analyze performance by grid layer (for grid/martingale strategies).

### Input schema

```typescript
{
  report_dir: string;
}
```

### Output schema

```typescript
{
  success: boolean;
  layers: Array<{
    layer: number;        // e.g. "L1", "L2", "L3"
    count: number;
    profit: number;
    win_rate: number;
    avg_profit: number;
  }>;
  max_layer: number;
  l5_plus_count: number;
  error?: string;
}
```

---

## `analyze_volume_vs_profit`

Volume correlation + performance by lot size.

**When to call:** To analyze relationship between position size and profit.

### Input schema

```typescript
{
  report_dir: string;
}
```

### Output schema

```typescript
{
  success: boolean;
  by_volume: Array<{
    volume: number;
    count: number;
    avg_profit: number;
    win_rate: number;
  }>;
  correlation: number;
  optimal_volume: number;
  error?: string;
}
```

---

## `analyze_costs`

Commission and swap impact on profitability.

**When to call:** To understand the impact of trading costs.

### Input schema

```typescript
{
  report_dir: string;
}
```

### Output schema

```typescript
{
  success: boolean;
  costs: {
    total_commission: number;
    total_swap: number;
    total_spread: number;
    avg_commission_per_trade: number;
    avg_swap_per_trade: number;
  };
  cost_impact_pct: number; // Costs as % of gross profit
  error?: string;
}
```

---

## `analyze_efficiency`

Profit per hour/day, annualized return, trade frequency.

**When to call:** To measure overall trading efficiency.

### Input schema

```typescript
{
  report_dir: string;
}
```

### Output schema

```typescript
{
  success: boolean;
  efficiency: {
    profit_per_hour: number;
    profit_per_day: number;
    profit_per_trade: number;
    trades_per_day: number;
    annualized_return_pct: number;
  };
  error?: string;
}
```

---

## Autonomous Loop Pattern

The tools are designed to support a fully autonomous experiment → evaluate → promote → optimize loop:

```
1.  run_backtest(new_params)
2.  compare_baseline(result, current_production)
3a. if winner:
     - archive_report(delete_after=true, verdict="winner")
     - promote_to_baseline(notes="...")
     - write_set_file(new_production.set)
     - run_optimization(new_production_set)
     - [wait for user signal]
     - get_optimization_results()
     - set_from_optimization(path=verify.set, params=results[0].params, template=prod.set)
     - verify top result: run_backtest(expert, set_file=verify.set, skip_compile=true)
     - if still beats baseline → goto step 1
3b. if loser:
     - archive_report(delete_after=true, verdict="loser", notes="root cause")
     - analyze_report(result) → find root cause
     - read_set_file() → inspect current params
     - propose parameter or code change → goto step 1
```

No user confirmation needed between steps 1→2→3. The AI agent drives the full loop; the user monitors and signals when optimization completes (since that runs for hours). Every run is archived before the directory is deleted, so nothing is lost.