qs-backtest-api 0.4.1

Provider-neutral request, response, event, and client contracts for the quant-system backtest service
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
//! Logical request, response, and event types for the backtest service.
//!
//! All structs use serde and remain independent of the selected transport/provider codec.
//! Enums are represented as strings at the service boundary for readability where retained compatibility requires it.

use std::collections::{BTreeMap, HashMap};

use serde::{Deserialize, Serialize, de::DeserializeOwned};

fn default_true() -> bool {
    true
}

fn default_target_source_info() -> String {
    "FromSignal".into()
}

/// Current format version for complete result JSON artifacts.
pub const RESULT_FORMAT_VERSION: u32 = 1;

// ── Ping ────────────────────────────────────────────────────────────────────

/// Health check response with server status.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PingResponse {
    pub status: String,
    pub uptime_secs: u64,
    pub data_dir: String,
}

// ── List Profiles ───────────────────────────────────────────────────────────

/// Summary of a management profile available on the server.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileInfo {
    pub name: String,
    pub use_targets: Vec<usize>,
    pub close_ratios: Vec<f64>,
    #[serde(default = "default_target_source_info")]
    pub target_source: String,
    pub stoploss_mode: String,
    pub rules_count: usize,
    pub let_remainder_run: bool,
}

/// Response listing all loaded management profiles.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListProfilesResponse {
    pub profiles: Vec<ProfileInfo>,
}

// ── List Symbols ────────────────────────────────────────────────────────────

/// Request to list available data, optionally filtered.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListSymbolsRequest {
    pub exchange: Option<String>,
    pub data_type: Option<String>,
}

/// One row of data availability info.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SymbolAvailability {
    pub exchange: String,
    pub symbol: String,
    pub data_type: String,
    pub timeframe: Option<String>,
    pub row_count: u64,
    pub earliest: String,
    pub latest: String,
}

/// Response listing available market data in the store.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListSymbolsResponse {
    pub symbols: Vec<SymbolAvailability>,
}

// ── Backtest Config ─────────────────────────────────────────────────────────

/// Serializable backtest configuration sent by the client.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BacktestConfigMsg {
    /// Starting account balance. Default: 10000.0
    pub initial_balance: Option<f64>,
    /// Whether to force-close open positions at end of data. Default: true
    pub close_on_finish: Option<bool>,
    /// Fill model: "BidAsk", "AskOnly", or "MidPrice". Default: "BidAsk"
    pub fill_model: Option<String>,
    /// Account sizing policy. Required when the request contains an Entry signal.
    #[serde(default)]
    pub sizing: Option<SizingPolicyMsg>,
    /// Per-symbol commission and swap, keyed by canonical symbol. Empty charges nothing and reproduces runs made before costs existed.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub costs: BTreeMap<String, InstrumentCostsMsg>,
}

/// Wire-safe commission and swap specification for one instrument.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InstrumentCostsMsg {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub commission: Option<CommissionModelMsg>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub swap: Option<SwapScheduleMsg>,
}

/// Wire-safe commission model.
///
/// The tag also accepts the snake_case spelling that `qs-core` writes into run metadata, so a stored specification round-trips back into a request.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", deny_unknown_fields)]
pub enum CommissionModelMsg {
    /// Fixed amount per lot per side, in the run's account currency.
    #[serde(alias = "per_lot_per_side")]
    PerLotPerSide { amount: f64, currency: String },
    /// Fraction of traded notional per side, with separate buy and sell rates.
    #[serde(alias = "notional_rate_per_side")]
    NotionalRatePerSide { buy_rate: f64, sell_rate: f64 },
}

/// Wire-safe nightly swap magnitude, where a negative value charges and a positive value credits.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "unit", deny_unknown_fields)]
pub enum SwapAmountMsg {
    /// Price points per lot per night, in the instrument's native currency.
    #[serde(alias = "points")]
    Points { long: f64, short: f64 },
    /// Amount per lot per night, in the run's account currency.
    #[serde(alias = "currency")]
    Currency {
        long: f64,
        short: f64,
        currency: String,
    },
}

/// Wire-safe nightly swap magnitude plus the rollover calendar that charges it.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SwapScheduleMsg {
    pub amount: SwapAmountMsg,
    /// Rollover time of day in the replay's timestamp zone, as `HH:MM:SS`.
    pub rollover: String,
    /// Weekday whose rollover charges three nights, as `Mon` through `Sun`.
    pub triple_weekday: String,
    /// Weekdays whose rollover charges nothing. Defaults to `Sat` and `Sun` when omitted.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub skipped_weekdays: Vec<String>,
}

/// Wire-safe in-place account sizing policy.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", deny_unknown_fields)]
pub enum SizingPolicyMsg {
    /// Use a fixed lot quantity scaled by the entry risk multiplier.
    FixedLot { lots: f64 },
    /// Risk a fixed amount in account currency.
    FixedRiskAmount { amount: f64 },
    /// Risk a percentage of the realized balance before the entry.
    BalanceRiskPercent { percent: f64 },
}

// ── Async Job API (Issue 2) ─────────────────────────────────────────────────

/// Response from submitting a backtest job.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubmitBacktestResponse {
    pub success: bool,
    pub job_id: Option<String>,
    pub error: Option<String>,
}

/// Request the current status of a backtest job.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetBacktestStatusRequest {
    pub job_id: String,
}

/// Subscribe to status snapshots for a retained backtest job.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WatchBacktestRequest {
    pub job_id: String,
}

/// Structured progress for an asynchronous backtest job.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct BacktestProgress {
    pub stage: String,
    pub processed_events: u64,
    pub total_events: u64,
    pub processed_signals: u64,
    pub total_signals: u64,
    pub processed_symbols: u64,
    pub total_symbols: u64,
}

/// Status of a backtest job.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BacktestStatusResponse {
    pub success: bool,
    pub job_id: String,
    pub status: String,
    pub error: Option<String>,
    pub elapsed_ms: Option<u64>,
    /// Missing in older responses; defaults to an empty progress snapshot.
    #[serde(default)]
    pub progress: BacktestProgress,
}

impl BacktestStatusResponse {
    /// Whether this snapshot represents a terminal retained-job state.
    pub fn is_terminal(&self) -> bool {
        matches!(self.status.as_str(), "Completed" | "Failed" | "Cancelled")
    }
}

/// Server-streamed retained-job status and liveness events.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum BacktestEvent {
    Snapshot { status: BacktestStatusResponse },
    Heartbeat { job_id: String, elapsed_ms: u64 },
}

/// Request the result of a completed backtest job.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetBacktestResultRequest {
    pub job_id: String,
}

/// Response containing the result of a completed backtest job.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetBacktestResultResponse {
    pub success: bool,
    pub job_id: String,
    pub result: Option<BacktestResultMsg>,
    pub error: Option<String>,
    #[serde(default)]
    pub artifact: Option<ResultArtifactRefMsg>,
    #[serde(default = "default_true")]
    pub inline_complete: bool,
    /// True when an async result artifact was deleted after delivery.
    #[serde(default)]
    pub artifact_consumed: bool,
}

/// Request cancellation of a backtest job.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CancelBacktestRequest {
    pub job_id: String,
}

/// Response from cancelling a backtest job.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CancelBacktestResponse {
    pub success: bool,
    pub job_id: String,
    pub error: Option<String>,
}

// ── FutureQuote execution ───────────────────────────────────────────────────

/// Requested delivery mode for a complete result JSON payload.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResultDeliveryMsg {
    #[default]
    Auto,
    Inline,
    Artifact,
}

/// Reference to a complete result JSON artifact.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResultArtifactRefMsg {
    pub format_version: u32,
    pub artifact_id: String,
    pub byte_len: u64,
    pub sha256: String,
    pub chunk_size: u64,
}

/// Request a raw byte chunk from a result artifact.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GetResultArtifactChunkRequest {
    pub artifact_id: String,
    pub offset: u64,
}

/// Base64-encoded raw artifact bytes at the requested offset.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetResultArtifactChunkResponse {
    pub success: bool,
    pub artifact_id: String,
    pub offset: u64,
    pub data_base64: String,
    pub eof: bool,
    pub error: Option<String>,
}

/// Delete a result artifact after a successful download.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DeleteResultArtifactRequest {
    pub artifact_id: String,
}

/// Response from deleting a result artifact.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeleteResultArtifactResponse {
    pub success: bool,
    pub artifact_id: String,
    pub error: Option<String>,
}

/// Wire-safe mark-to-market output retention policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum MtmOutputPolicyMsg {
    None,
    Bounded { max_points: usize },
    Full,
}

impl Default for MtmOutputPolicyMsg {
    fn default() -> Self {
        Self::Bounded { max_points: 4_096 }
    }
}

/// Price basis used to size market entries.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum MarketEntrySizingBasisMsg {
    #[default]
    FillPrice,
    SignalEntryPrice,
}

/// FutureQuoteV1 execution settings used by the backtest RPC methods.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct FutureQuoteConfigMsg {
    pub signal_latency_ms: i64,
    pub slippage_pips: f64,
    pub stale_quote_after_ms: Option<i64>,
    pub pnl_epsilon: f64,
    pub account_currency: String,
    pub conversion_stale_after_ms: i64,
    pub mtm_output: MtmOutputPolicyMsg,
    pub market_entry_sizing_basis: MarketEntrySizingBasisMsg,
}

impl Default for FutureQuoteConfigMsg {
    fn default() -> Self {
        Self {
            signal_latency_ms: 0,
            slippage_pips: 0.0,
            stale_quote_after_ms: None,
            pnl_epsilon: 1.0e-9,
            account_currency: String::new(),
            conversion_stale_after_ms: 300_000,
            mtm_output: MtmOutputPolicyMsg::default(),
            market_entry_sizing_basis: MarketEntrySizingBasisMsg::default(),
        }
    }
}

/// Provider/source identifiers carried into the evaluation result.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct EvaluationContextMsg {
    pub provider_id: Option<String>,
    pub source_id: Option<String>,
}

/// Selectable provider-evaluation report sections.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EvaluationSectionMsg {
    Coverage,
    PositionPerformance,
    RMetrics,
    Excursions,
    Execution,
    Costs,
    Robustness,
    Breakdowns,
}

impl EvaluationSectionMsg {
    pub const ALL: [Self; 8] = [
        Self::Coverage,
        Self::PositionPerformance,
        Self::RMetrics,
        Self::Excursions,
        Self::Execution,
        Self::Costs,
        Self::Robustness,
        Self::Breakdowns,
    ];
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EvaluationPositionSideMsg {
    Long,
    Short,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EvaluationGroupFilterMsg {
    Named(String),
    Ungrouped,
}

/// Typed position filters. Values within a field are ORed; populated fields and
/// individual tag keys are ANDed.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct PositionFilterMsg {
    pub symbols: Vec<String>,
    pub sides: Vec<EvaluationPositionSideMsg>,
    pub groups: Vec<EvaluationGroupFilterMsg>,
    pub close_reasons: Vec<String>,
    pub tags: BTreeMap<String, Vec<String>>,
}

/// Typed deterministic breakdown selector.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BreakdownDimensionMsg {
    Symbol,
    Side,
    Group,
    CloseReason,
    Tag(String),
}

#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct BootstrapConfigMsg {
    pub samples: usize,
    pub confidence_level: f64,
    pub seed: u64,
    pub minimum_sample_size: usize,
}

impl Default for BootstrapConfigMsg {
    fn default() -> Self {
        Self {
            samples: 2_000,
            confidence_level: 0.95,
            seed: 0xA076_1D64_78BD_642F,
            minimum_sample_size: 5,
        }
    }
}

/// Typed parser/source coverage supplied by clients that retain parse outcomes.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct SourceCoverageCountsMsg {
    pub raw_messages: u64,
    pub parsed_messages: u64,
    pub skipped_messages: u64,
    pub failed_messages: u64,
    pub emitted_signals: u64,
    pub emitted_entry_signals: u64,
}

/// Typed provider-evaluation selection for canonical requests.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct ProviderEvaluationOptionsMsg {
    pub context: EvaluationContextMsg,
    pub source_coverage: Option<SourceCoverageCountsMsg>,
    /// Missing selectors request all sections; an explicit empty list requests none.
    pub sections: Vec<EvaluationSectionMsg>,
    pub filter: PositionFilterMsg,
    pub breakdowns: Vec<BreakdownDimensionMsg>,
    pub bootstrap: BootstrapConfigMsg,
    pub rolling_window: usize,
    pub minimum_breakdown_bucket_count: usize,
    pub maximum_breakdown_rows: Option<usize>,
    pub include_positions: bool,
    pub maximum_position_rows: Option<usize>,
}

impl Default for ProviderEvaluationOptionsMsg {
    fn default() -> Self {
        Self {
            context: EvaluationContextMsg::default(),
            source_coverage: None,
            sections: EvaluationSectionMsg::ALL.to_vec(),
            filter: PositionFilterMsg::default(),
            breakdowns: Vec::new(),
            bootstrap: BootstrapConfigMsg::default(),
            rolling_window: 20,
            minimum_breakdown_bucket_count: 1,
            maximum_breakdown_rows: None,
            include_positions: false,
            maximum_position_rows: None,
        }
    }
}

// ── Run Backtest ────────────────────────────────────────────────────────────

/// Handling of selected instruments that cannot be prepared for replay.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UnavailableInstrumentPolicyMsg {
    #[default]
    Skip,
    Error,
}

/// Why an instrument's signals were excluded before replay.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InstrumentExclusionReasonMsg {
    NotSelected,
    UnknownInstrument,
    UnsupportedEconomics,
    NoMarketData,
    NoConversionData,
    AmbiguousMapping,
}

/// Original input coordinates for one excluded signal.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ExcludedSignalRefMsg {
    pub input_index: usize,
    pub ts: String,
    pub action: String,
    pub trade_id: Option<String>,
}

/// Bounded evidence for an instrument excluded during preparation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ExcludedInstrumentMsg {
    pub symbol: String,
    pub reason: InstrumentExclusionReasonMsg,
    pub details: String,
    pub skipped_entries: usize,
    pub skipped_management: usize,
    pub signal_references: Vec<ExcludedSignalRefMsg>,
    pub omitted_signal_references: usize,
}

/// Preparation decisions, separate from parser outcomes and execution dispositions.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ReplayAdmissionReportMsg {
    #[serde(default)]
    pub omitted_instruments: usize,
    #[serde(default)]
    pub omitted_entries: usize,
    #[serde(default)]
    pub omitted_management: usize,
    pub policy: UnavailableInstrumentPolicyMsg,
    pub input_signals: usize,
    pub retained_signals: usize,
    pub excluded_instruments: Vec<ExcludedInstrumentMsg>,
}

/// Execution scope and inputs for one backtest run.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BacktestRunSpec {
    #[serde(default)]
    pub on_unavailable: UnavailableInstrumentPolicyMsg,
    pub symbol: String,
    #[serde(default)]
    pub symbols: Vec<String>,
    #[serde(default)]
    pub all_symbols: bool,
    pub exchange: String,
    pub data_type: String,
    pub timeframe: Option<String>,
    pub from: Option<String>,
    pub to: Option<String>,
    /// Full signal stream (entry + management).
    #[serde(default)]
    pub raw_signals: Vec<RawSignalMsg>,
    pub profile: Option<String>,
    #[serde(default)]
    pub profile_def: Option<ManagementProfileMsg>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub entry_profile_routes: Vec<EntryProfileRouteMsg>,
    pub config: BacktestConfigMsg,
}

/// Response from a single backtest run.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunBacktestResponse {
    pub success: bool,
    pub error: Option<String>,
    /// Complete inline result or compact summary when `inline_complete` is false.
    pub result: Option<BacktestResultMsg>,
    pub elapsed_ms: u64,
    #[serde(default)]
    pub artifact: Option<ResultArtifactRefMsg>,
    #[serde(default = "default_true")]
    pub inline_complete: bool,
}

/// Strict FutureQuoteV1 request accepted by `run_backtest`.
#[derive(Debug, Clone, Serialize)]
pub struct RunBacktestRequest {
    pub request: BacktestRunSpec,
    #[serde(default)]
    pub future: FutureQuoteConfigMsg,
    #[serde(default)]
    pub evaluation: ProviderEvaluationOptionsMsg,
    #[serde(default)]
    pub result_delivery: ResultDeliveryMsg,
}

/// Asynchronous FutureQuoteV1 submission.
#[derive(Debug, Clone, Serialize)]
pub struct SubmitBacktestRequest {
    pub request: RunBacktestRequest,
}

// ── Run Backtest Multi ──────────────────────────────────────────────────────

/// Execution scope and inputs for a multi-profile comparison.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BacktestMultiRunSpec {
    #[serde(default)]
    pub on_unavailable: UnavailableInstrumentPolicyMsg,
    pub symbol: String,
    #[serde(default)]
    pub symbols: Vec<String>,
    #[serde(default)]
    pub all_symbols: bool,
    pub exchange: String,
    pub data_type: String,
    pub timeframe: Option<String>,
    pub from: Option<String>,
    pub to: Option<String>,
    /// Full signal stream (entry + management).
    #[serde(default)]
    pub raw_signals: Vec<RawSignalMsg>,
    pub profiles: Vec<ProfileRef>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub entry_profile_routes: Vec<EntryProfileRouteMsg>,
    pub config: BacktestConfigMsg,
}

/// Result for one profile in a multi-profile comparison.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileResult {
    pub profile: String,
    pub success: bool,
    pub error: Option<String>,
    pub result: Option<BacktestResultMsg>,
}

/// Response from a multi-profile comparison run.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunBacktestMultiResponse {
    /// Defaults to true when decoding responses from older servers.
    #[serde(default = "default_true")]
    pub success: bool,
    #[serde(default)]
    pub error: Option<String>,
    /// Complete inline results or compact summaries when `inline_complete` is false.
    pub results: Vec<ProfileResult>,
    pub elapsed_ms: u64,
    #[serde(default)]
    pub artifact: Option<ResultArtifactRefMsg>,
    #[serde(default = "default_true")]
    pub inline_complete: bool,
}

#[derive(Debug, Clone, Serialize)]
pub struct RunBacktestMultiRequest {
    pub request: BacktestMultiRunSpec,
    #[serde(default)]
    pub future: FutureQuoteConfigMsg,
    #[serde(default)]
    pub evaluation: ProviderEvaluationOptionsMsg,
    #[serde(default)]
    pub result_delivery: ResultDeliveryMsg,
}

// ── Configured Strategy Runs ────────────────────────────────────────────────

/// Price basis the bars of a configured logical source are built on.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PriceBasisMsg {
    Bid,
    Ask,
    Mid,
}

/// Historical series geometry for one configured logical source; the source always reads the request symbol.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SourceBindingMsg {
    pub source: String,
    pub timeframe_seconds: u32,
    pub price_basis: PriceBasisMsg,
    #[serde(default)]
    pub alignment_offset_seconds: i32,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HistoricalInputsMsg {
    pub calendars: BTreeMap<String, TradingCalendarMsg>,
    pub inputs: Vec<CalendarInputMsg>,
    #[serde(default)]
    pub limits: Option<CalendarLimitsMsg>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TradingCalendarMsg {
    pub id: String,
    pub timezone: String,
    #[serde(default = "default_day_boundary")]
    pub day_boundary: String,
    #[serde(default)]
    pub sessions: SessionScheduleMsg,
    #[serde(default)]
    pub market: MarketScheduleMsg,
}

fn default_day_boundary() -> String {
    "00:00:00".into()
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
pub enum SessionScheduleMsg {
    #[default]
    FullDay,
    Custom {
        items: Vec<NamedSessionMsg>,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct NamedSessionMsg {
    pub id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timezone: Option<String>,
    pub span: SessionSpanMsg,
    #[serde(default)]
    pub weekdays: Vec<u8>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum SessionSpanMsg {
    FullDay,
    Timed {
        start: String,
        end: String,
        end_day_offset: u8,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(tag = "mode", rename_all = "snake_case", deny_unknown_fields)]
pub enum MarketScheduleMsg {
    #[default]
    Unspecified,
    Continuous,
    Weekly {
        intervals: Vec<WeeklyMarketIntervalMsg>,
        #[serde(default)]
        exceptions: BTreeMap<String, Vec<LocalMarketIntervalMsg>>,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WeeklyMarketIntervalMsg {
    pub weekday: u8,
    pub start: String,
    pub end: String,
    pub end_day_offset: u8,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LocalMarketIntervalMsg {
    pub start: String,
    pub end: String,
    pub end_day_offset: u8,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CalendarInputMsg {
    pub name: String,
    pub source: String,
    pub calendar: String,
    pub feature: CalendarFeatureMsg,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session: Option<String>,
    #[serde(default)]
    pub time_basis: CalendarTimeBasisMsg,
    #[serde(default = "default_opening_range_minutes")]
    pub opening_range_minutes: u32,
    pub child_seconds: u64,
    #[serde(default)]
    pub alignment_offset_seconds: i64,
    pub maximum_history: usize,
}

fn default_opening_range_minutes() -> u32 {
    5
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CalendarFeatureMsg {
    LocalSecondOfDay,
    SessionElapsedSeconds,
    SessionMembership,
    PreviousSessionHigh,
    PreviousSessionLow,
    PreviousDayHigh,
    PreviousDayLow,
    PreviousWeekHigh,
    PreviousWeekLow,
    OpeningRangeHighSoFar,
    OpeningRangeLowSoFar,
    OpeningRangeHighFinal,
    OpeningRangeLowFinal,
    PastSameSlotRangeRatio,
    PastSameSlotCount,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum CalendarTimeBasisMsg {
    #[default]
    SourceOpen,
    DecisionTime,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CalendarLimitsMsg {
    pub max_sessions: usize,
    pub max_market_intervals: usize,
    pub max_exceptions: usize,
    pub max_history_occurrences: usize,
    pub max_resolved_children: usize,
    pub max_owned_bytes: usize,
}

/// One fully bound configured strategy document and the series backing its sources.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ConfiguredStrategyRunMsg {
    /// Canonical strategy document as a JSON value; the server decodes it strictly and rejects unknown fields.
    pub document: serde_json::Value,
    pub sources: Vec<SourceBindingMsg>,
    /// Instance identifier used in generated campaign, trade, and command IDs; the server uses `instance` when omitted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub instance_id: Option<String>,
    /// Decision latency in milliseconds applied to generated signals.
    #[serde(default)]
    pub decision_latency_ms: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub historical_inputs: Option<HistoricalInputsMsg>,
}

/// Execution scope for one configured strategy run over one symbol.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ConfiguredStrategyRunSpec {
    pub symbol: String,
    pub exchange: String,
    /// `tick`, or `bar` together with `timeframe`.
    pub data_type: String,
    #[serde(default)]
    pub timeframe: Option<String>,
    #[serde(default)]
    pub from: Option<String>,
    #[serde(default)]
    pub to: Option<String>,
    pub strategy: ConfiguredStrategyRunMsg,
    #[serde(default)]
    pub profile: Option<String>,
    #[serde(default)]
    pub profile_def: Option<ManagementProfileMsg>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub entry_profile_routes: Vec<EntryProfileRouteMsg>,
    pub config: BacktestConfigMsg,
}

/// Synchronous configured strategy run.
#[derive(Debug, Clone, Serialize)]
pub struct RunConfiguredStrategyRequest {
    pub request: ConfiguredStrategyRunSpec,
    #[serde(default)]
    pub future: FutureQuoteConfigMsg,
    #[serde(default)]
    pub evaluation: ProviderEvaluationOptionsMsg,
    #[serde(default)]
    pub result_delivery: ResultDeliveryMsg,
}

/// Asynchronous configured strategy submission retained as a job.
#[derive(Debug, Clone, Serialize)]
pub struct SubmitConfiguredStrategyRequest {
    pub request: RunConfiguredStrategyRequest,
}

/// Strategy output returned with a configured run's economic result.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ConfiguredStrategyOutputMsg {
    /// The document the run compiled, as decoded.
    pub document: serde_json::Value,
    pub sources: Vec<SourceBindingMsg>,
    /// Compiled requirements the run was bound with: per-source completed-bar lookback, trade slots, Entry slots and classes, and stop-managed slots.
    pub requirements: serde_json::Value,
    /// `ticks` or `bars`; a bar run fills waiting orders at each bar's open and settles stops, targets, and pending orders against its range, meeting the adverse extreme first.
    pub data_mode: String,
    /// Retained configured decisions with the signals each emitted.
    pub decisions: serde_json::Value,
    /// Configured notes and research-only output.
    pub research: serde_json::Value,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub historical_inputs: Option<serde_json::Value>,
}

// ── Portfolio Runs ──────────────────────────────────────────────────────────

/// One configured strategy instance of a portfolio run, trading one symbol against the shared account.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PortfolioInstanceMsg {
    pub symbol: String,
    /// Strategy document and source bindings. `instance_id` is required here and must be unique in the run, because it labels the instance's positions, reviews, and output.
    pub strategy: ConfiguredStrategyRunMsg,
    #[serde(default)]
    pub profile: Option<String>,
    #[serde(default)]
    pub profile_def: Option<ManagementProfileMsg>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub entry_profile_routes: Vec<EntryProfileRouteMsg>,
}

/// Execution scope of a portfolio run: several configured instances, one account, and optional portfolio policies.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PortfolioRunSpec {
    pub instances: Vec<PortfolioInstanceMsg>,
    pub exchange: String,
    /// `tick`, or `bar` together with `timeframe`; every instance source declares the same bar duration.
    pub data_type: String,
    #[serde(default)]
    pub timeframe: Option<String>,
    #[serde(default)]
    pub from: Option<String>,
    #[serde(default)]
    pub to: Option<String>,
    pub config: BacktestConfigMsg,
    /// Portfolio policies as a JSON array, decoded strictly by the server; omitted or empty means the run has no supervisor.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub policies: Option<serde_json::Value>,
    /// Correlation groups the policies refer to, as a JSON array.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub groups: Option<serde_json::Value>,
}

/// Synchronous portfolio run.
#[derive(Debug, Clone, Serialize)]
pub struct RunPortfolioRequest {
    pub request: PortfolioRunSpec,
    #[serde(default)]
    pub future: FutureQuoteConfigMsg,
    #[serde(default)]
    pub evaluation: ProviderEvaluationOptionsMsg,
    #[serde(default)]
    pub result_delivery: ResultDeliveryMsg,
}

/// Asynchronous portfolio submission retained as a job.
#[derive(Debug, Clone, Serialize)]
pub struct SubmitPortfolioRequest {
    pub request: RunPortfolioRequest,
}

/// What one portfolio instance compiled, decided, and recorded.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PortfolioInstanceOutputMsg {
    pub instance_id: String,
    pub symbol: String,
    pub strategy: ConfiguredStrategyOutputMsg,
}

/// Instance and supervisor output returned with a portfolio run's shared economic result.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PortfolioOutputMsg {
    pub instances: Vec<PortfolioInstanceOutputMsg>,
    /// The decoded policies and groups the run was supervised with, when it had a supervisor.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub policies: Option<serde_json::Value>,
    /// Every review, halt action, and halt interval, when the run had a supervisor.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supervisor: Option<serde_json::Value>,
}

// ── Parameter Search ────────────────────────────────────────────────────────

/// One labelled half-open evaluation window.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SearchWindowMsg {
    pub label: String,
    pub from: String,
    pub to: String,
}

/// Evaluation windows of a parameter search.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case", deny_unknown_fields)]
pub enum SearchWindowsMsg {
    Fixed {
        in_sample: SearchWindowMsg,
        out_of_sample: SearchWindowMsg,
    },
    RollingWalkForward {
        start: String,
        end: String,
        train_seconds: i64,
        test_seconds: i64,
        step_seconds: i64,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SearchEvaluationRoleMsg {
    Search,
    Validation,
    Final,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SearchSelectedRerunMsg {
    pub experiment_recipe: serde_json::Value,
    pub candidate_recipe: serde_json::Value,
    pub run_recipe: serde_json::Value,
    pub role: SearchEvaluationRoleMsg,
    pub caller_revision: String,
    #[serde(default)]
    pub release_final: bool,
    #[serde(default)]
    pub future_horizon_millis: Option<u64>,
    #[serde(default)]
    pub embargo_millis: Option<u64>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SearchDirectPortfolioInstanceMsg {
    pub instance_id: String,
    pub symbol: String,
    pub factory: SearchDirectFactoryMsg,
    #[serde(default)]
    pub profile: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SearchPortfolioCandidateMsg {
    pub id: String,
    #[serde(default)]
    pub instances: Vec<PortfolioInstanceMsg>,
    #[serde(default)]
    pub direct_instances: Vec<SearchDirectPortfolioInstanceMsg>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub policies: Option<serde_json::Value>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub groups: Option<serde_json::Value>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum SearchFactoryParameterMsg {
    Integer(i64),
    Number(f64),
    Choice(String),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SearchDirectFactoryPointMsg {
    pub parameters: BTreeMap<String, SearchFactoryParameterMsg>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SearchDirectFactoryMsg {
    pub name: String,
    pub revision: String,
    pub points: Vec<SearchDirectFactoryPointMsg>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SearchExecutionVariantMsg {
    pub id: String,
    pub config: BacktestConfigMsg,
    #[serde(default)]
    pub future: FutureQuoteConfigMsg,
    #[serde(default)]
    pub profile: Option<String>,
}

/// Execution scope of a server-side parameter search over a strategy template and a space document.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SearchRunSpec {
    /// Strategy template document as a JSON value.
    pub template: serde_json::Value,
    /// Space document as a JSON value.
    pub space: serde_json::Value,
    pub symbols: Vec<String>,
    pub exchange: String,
    /// `tick`, or `bar` together with `timeframe`.
    pub data_type: String,
    #[serde(default)]
    pub timeframe: Option<String>,
    pub windows: SearchWindowsMsg,
    pub config: BacktestConfigMsg,
    /// Registered run default profile; inline profiles are not accepted for a search.
    #[serde(default)]
    pub profile: Option<String>,
    /// Entry-class routes to registered profiles only.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub entry_profile_routes: Vec<EntryProfileRouteMsg>,
    /// Requested worker threads, capped by the server's configured maximum.
    #[serde(default)]
    pub workers: Option<usize>,
    #[serde(default)]
    pub decision_latency_ms: u64,
    #[serde(default)]
    pub structural: Option<serde_json::Value>,
    #[serde(default)]
    pub resource_limits: Option<serde_json::Value>,
    #[serde(default)]
    pub variants: Vec<SearchExecutionVariantMsg>,
    /// Select a server-registered immutable direct Rust factory; arbitrary code is never accepted.
    #[serde(default)]
    pub direct_factory: Option<SearchDirectFactoryMsg>,
    /// A prior compatible checkpoint whose completed runs are retained and skipped.
    #[serde(default)]
    pub resume_checkpoint: Option<serde_json::Value>,
    /// Execute one downloaded frozen recipe instead of the declared candidate batch.
    #[serde(default)]
    pub selected_rerun: Option<SearchSelectedRerunMsg>,
    /// Explicit configured portfolio candidates evaluated under the request's windows and economics.
    #[serde(default)]
    pub portfolio_candidates: Vec<SearchPortfolioCandidateMsg>,
    /// Verified enhanced series descriptors for `price_bar` inputs.
    #[serde(default)]
    pub series_descriptors: Vec<serde_json::Value>,
}

/// Asynchronous search submission retained as a job.
#[derive(Debug, Clone, Serialize)]
pub struct SubmitSearchRequest {
    pub request: SearchRunSpec,
    #[serde(default)]
    pub future: FutureQuoteConfigMsg,
    #[serde(default)]
    pub evaluation: ProviderEvaluationOptionsMsg,
}

/// Request for the output of a completed search job.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GetSearchResultRequest {
    pub job_id: String,
}

/// Counts that describe a completed search without its full output.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SearchSummaryMsg {
    pub points_total: usize,
    pub rows: usize,
    pub completed_rows: usize,
    pub failed_rows: usize,
    /// `ticks` or `bars`.
    pub data_mode: String,
}

/// Complete search output, always delivered as the job's result artifact.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SearchResultMsg {
    pub summary: SearchSummaryMsg,
    /// Comparison table in the research CSV format, one row per run, ordered by parameter rather than result.
    pub table_csv: String,
    /// Pooled provider evaluation over every run's completed positions.
    pub evaluation: serde_json::Value,
    /// Bound strategy document of every configured point, in point order.
    pub bound_documents: Vec<serde_json::Value>,
    #[serde(default)]
    pub experiment_recipe: Option<serde_json::Value>,
    #[serde(default)]
    pub candidate_recipes: Vec<serde_json::Value>,
    #[serde(default)]
    pub run_recipes: Vec<serde_json::Value>,
    #[serde(default)]
    pub generation_dispositions: Option<serde_json::Value>,
    #[serde(default)]
    pub checkpoint: Option<serde_json::Value>,
    #[serde(default)]
    pub selected_evidence: Option<serde_json::Value>,
    #[serde(default)]
    pub trace: Option<serde_json::Value>,
}

/// Response carrying a search summary and the artifact holding its complete output.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetSearchResultResponse {
    pub success: bool,
    pub job_id: String,
    #[serde(default)]
    pub error: Option<String>,
    #[serde(default)]
    pub summary: Option<SearchSummaryMsg>,
    #[serde(default)]
    pub artifact: Option<ResultArtifactRefMsg>,
    /// Separately labeled resumable checkpoint produced by a cancelled retained search.
    #[serde(default)]
    pub checkpoint_artifact: Option<ResultArtifactRefMsg>,
}

// ── Backtest Result Message ─────────────────────────────────────────────────

/// Serializable mirror of `BacktestResult` for wire transport.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BacktestResultMsg {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub admission_report: Option<ReplayAdmissionReportMsg>,
    /// Strategy document, sources, decisions, and notes when the run executed a configured strategy.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub strategy: Option<ConfiguredStrategyOutputMsg>,
    /// Instance and supervisor output when the run executed a portfolio of configured strategies.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub portfolio: Option<PortfolioOutputMsg>,
    pub initial_balance: f64,
    pub final_balance: f64,
    pub total_pnl: f64,
    pub total_trades: usize,
    pub winning_trades: usize,
    pub losing_trades: usize,
    pub win_rate: f64,
    pub profit_factor: f64,
    pub max_drawdown: f64,
    pub max_drawdown_pct: f64,

    // Extended result breakdowns.
    pub summary: SubsetStatsMsg,
    pub per_symbol: HashMap<String, SubsetStatsMsg>,
    pub per_group: HashMap<String, SubsetStatsMsg>,
    pub long_stats: SubsetStatsMsg,
    pub short_stats: SubsetStatsMsg,
    pub per_close_reason: Vec<CloseReasonStatsMsg>,
    pub streaks: StreakStatsMsg,
    pub risk_metrics: RiskMetricsMsg,
    pub duration_stats: Option<DurationStatsMsg>,
    pub monthly_returns: Vec<MonthlyReturnMsg>,

    pub equity_curve: Vec<EquityPoint>,
    pub trade_log: Vec<TradeResultMsg>,

    // Position-level aggregation
    pub positions: Vec<PositionSummaryMsg>,
    pub total_positions: usize,
    pub winning_positions: usize,
    pub losing_positions: usize,
    pub position_win_rate: f64,

    /// Additive FutureQuoteV1 artifacts.
    #[serde(default)]
    pub future: Option<FutureBacktestResultMsg>,

    /// Total account-currency commission charged across every entry and exit fill.
    #[serde(default)]
    pub total_commission: f64,
    /// Total account-currency swap charged across every rollover.
    #[serde(default)]
    pub total_swap: f64,
    /// Realized profit and loss before commission and swap, present only when a cost was charged.
    #[serde(default)]
    pub gross_pnl: Option<f64>,
    /// Commission and swap charges in application order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub cost_events: Vec<CostEventMsg>,
}

/// Wire-safe mirror of one commission or swap charge.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CostEventMsg {
    pub id: String,
    pub position_id: String,
    pub symbol: String,
    pub side: String,
    pub ts: String,
    /// `entry_commission`, `exit_commission`, or `swap`.
    pub kind: String,
    /// Signed account-currency charge, where positive reduced the balance.
    pub amount: f64,
    #[serde(default)]
    pub native_amount: Option<f64>,
    #[serde(default)]
    pub native_currency: Option<String>,
    pub size: f64,
    #[serde(default)]
    pub nights: Option<u32>,
}

/// Wire-safe mark-to-market output counts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct MtmOutputSummaryMsg {
    pub policy: MtmOutputPolicyMsg,
    pub observed_points: u64,
    pub retained_points: u64,
    pub omitted_points: u64,
}

impl Default for MtmOutputSummaryMsg {
    fn default() -> Self {
        Self {
            policy: MtmOutputPolicyMsg::Full,
            observed_points: 0,
            retained_points: 0,
            omitted_points: 0,
        }
    }
}

/// Format-versioned execution/accounting payload. Complex internal records remain
/// JSON values so new additive fields do not require synchronized positional
/// wire changes; the transport itself uses JsonCodec.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FutureBacktestResultMsg {
    pub format_version: u32,
    pub execution_metadata: serde_json::Value,
    pub recorded_fills: serde_json::Value,
    pub action_dispositions: serde_json::Value,
    pub close_events: serde_json::Value,
    pub completed_positions: serde_json::Value,
    pub open_positions: serde_json::Value,
    pub pending_orders: serde_json::Value,
    /// Typed FutureQuote pending-order transition stream.
    #[serde(default)]
    pub pending_order_lifecycle: Vec<PendingOrderLifecycleEventMsg>,
    pub mtm_equity_curve: serde_json::Value,
    #[serde(default)]
    pub mtm_output_summary: MtmOutputSummaryMsg,
    pub mtm_max_drawdown: Option<f64>,
    pub mtm_max_drawdown_pct: Option<f64>,
    pub provider_evaluation: serde_json::Value,
}

/// Wire-safe state for one pending-order lifecycle transition.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum PendingOrderLifecycleStateMsg {
    #[default]
    Placed,
    Filled,
    Cancelled,
    UnfilledAtEnd,
}

/// Typed wire mirror of a FutureQuote pending-order lifecycle event.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct PendingOrderLifecycleEventMsg {
    pub id: String,
    pub sequence: u64,
    pub position_id: String,
    pub placement_action_id: Option<String>,
    pub terminal_action_id: Option<String>,
    pub state: PendingOrderLifecycleStateMsg,
    pub symbol: String,
    pub side: String,
    pub order_type: String,
    pub requested_size: f64,
    pub filled_size: Option<f64>,
    pub requested_price: Option<f64>,
    pub fill_price: Option<f64>,
    pub signal_ts: Option<String>,
    pub placed_ts: Option<String>,
    pub effective_ts: Option<String>,
    pub terminal_ts: Option<String>,
    pub wait_latency_ms: Option<i64>,
    pub fill_ratio: Option<f64>,
}

// ── Sub-message types ───────────────────────────────────────────────────────

/// Wire-safe mirror of `SubsetStats`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubsetStatsMsg {
    pub total_trades: usize,
    pub winning_trades: usize,
    pub losing_trades: usize,
    pub breakeven_trades: usize,
    pub total_pnl: f64,
    pub gross_profit: f64,
    pub gross_loss: f64,
    pub win_rate: f64,
    pub profit_factor: f64,
    pub avg_win: f64,
    pub avg_loss: f64,
    pub win_loss_ratio: f64,
    pub expectancy: f64,
    pub largest_win: f64,
    pub largest_loss: f64,
    /// Commission settled on this subset's rows.
    #[serde(default)]
    pub commission: f64,
    /// Swap settled on this subset's rows.
    #[serde(default)]
    pub swap: f64,
    /// Subset profit and loss before `commission` and `swap`, present only when either was settled.
    #[serde(default)]
    pub gross_pnl: Option<f64>,
}

/// Wire-safe mirror of `StreakStats`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StreakStatsMsg {
    pub max_consecutive_wins: u32,
    pub max_consecutive_losses: u32,
    pub current_streak: i32,
}

/// Wire-safe mirror of `RiskMetrics`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RiskMetricsMsg {
    pub sharpe_ratio: Option<f64>,
    pub sortino_ratio: Option<f64>,
    pub calmar_ratio: Option<f64>,
    pub return_on_max_drawdown: Option<f64>,
    pub max_drawdown: f64,
    pub max_drawdown_pct: f64,
    pub max_drawdown_duration_secs: Option<i64>,
}

/// Wire-safe mirror of `DurationStats`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DurationStatsMsg {
    pub avg_duration_secs: i64,
    pub min_duration_secs: i64,
    pub max_duration_secs: i64,
    pub avg_winner_duration_secs: i64,
    pub avg_loser_duration_secs: i64,
}

/// Wire-safe mirror of `MonthlyReturn`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MonthlyReturnMsg {
    pub year: i32,
    pub month: u32,
    pub pnl: f64,
    pub trade_count: usize,
    pub ending_balance: f64,
}

/// Wire-safe mirror of `CloseReasonStats`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CloseReasonStatsMsg {
    pub reason: String,
    pub count: usize,
    pub total_pnl: f64,
    pub avg_pnl: f64,
    pub percentage: f64,
}

/// Wire-safe mirror of `PositionSummary`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PositionSummaryMsg {
    pub position_id: String,
    pub symbol: String,
    pub side: String,
    pub group: Option<String>,
    pub entry_price: f64,
    pub avg_exit_price: f64,
    pub original_size: f64,
    pub close_count: usize,
    pub net_pnl: f64,
    pub close_reasons: Vec<String>,
    pub open_ts: String,
    pub final_close_ts: Option<String>,
    pub duration_seconds: i64,
}

/// A single point on the equity curve.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EquityPoint {
    pub ts: String,
    pub balance: f64,
}

/// Wire-safe mirror of `TradeResult`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TradeResultMsg {
    pub position_id: String,
    pub symbol: String,
    pub side: String,
    pub entry_price: f64,
    pub exit_price: f64,
    pub size: f64,
    /// Realized profit and loss for this close, already net of `commission` and `swap`.
    pub pnl: f64,
    /// Account-currency commission settled on this row and already subtracted from `pnl`.
    ///
    /// The row that fully closes a position also settles that position's entry commission, because entry commission belongs to the position rather than to any one close.
    #[serde(default)]
    pub commission: f64,
    /// Account-currency swap settled on this row, which is non-zero only on the row that fully closes a position.
    #[serde(default)]
    pub swap: f64,
    /// Profit and loss before `commission` and `swap`, present only when either was settled.
    #[serde(default)]
    pub gross_pnl: Option<f64>,
    pub open_ts: String,
    pub close_ts: String,
    pub close_reason: String,
    pub group: Option<String>,
}

// Dynamic management profile messages.

/// Wire-safe strict target selection.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TargetSelectionMsg {
    /// Use every target supplied by the entry signal, in signal order.
    All,
    /// Do not attach any targets.
    None,
    /// Use the listed 1-based signal target indices, in the listed order.
    Selected(Vec<usize>),
}

/// Wire-safe source used to select or generate targets.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", deny_unknown_fields)]
pub enum TargetSourceMsg {
    #[default]
    FromSignal,
    StopDistanceMultiples {
        multiples: Vec<f64>,
    },
}

/// Wire-safe entry geometry policy.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EntryGeometryPolicyMsg {
    /// Reject entry resolution when a signal level sits on the wrong side
    /// of the entry price.
    #[default]
    Strict,
    /// Attach signal levels unchanged; already-crossed levels close at
    /// market on the first tick evaluation.
    Permissive,
}

/// Wire-safe management profile definition sent inline with a request.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManagementProfileMsg {
    pub name: String,
    /// Explicit strict selection. This wins over `use_targets` when present;
    /// omission preserves the legacy `use_targets`-derived default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_selection: Option<TargetSelectionMsg>,
    /// Compatibility selection retained for older serialized profiles.
    pub use_targets: Vec<usize>,
    pub close_ratios: Vec<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_source: Option<TargetSourceMsg>,
    #[serde(default)]
    pub stoploss_mode: Option<StoplossModeMsg>,
    #[serde(default)]
    pub rules: Vec<RuleConfigDefMsg>,
    #[serde(default)]
    pub group_override: Option<String>,
    #[serde(default)]
    pub let_remainder_run: bool,
    /// Directional geometry policy for signal stoploss/targets vs the
    /// execution price. Omission preserves the Strict default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub entry_geometry: Option<EntryGeometryPolicyMsg>,
}

/// Wire-safe stoploss mode enum.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum StoplossModeMsg {
    FromSignal,
    None,
    FixedDistance { distance: f64 },
    FixedPrice { price: f64 },
    FromSignalDistance { multiplier: f64 },
}

/// Wire-safe rule configuration definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum RuleConfigDefMsg {
    FixedStoploss { price: f64 },
    TrailingStop { distance: f64 },
    TakeProfit { price: f64, close_ratio: f64 },
    BreakevenWhen { trigger_price: f64 },
    BreakevenWhenOffset { trigger_price_offset: f64 },
    BreakevenAfterTargets { after_n: u32 },
    TimeExit { max_seconds: u64 },
}

/// A profile reference: either by name or inline definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ProfileRef {
    Named(String),
    Inline(ManagementProfileMsg),
}

/// One exact entry-class route to a named or inline management profile.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EntryProfileRouteMsg {
    pub entry_class: String,
    pub profile: ProfileRef,
}

// Full raw-signal action messages.

/// Wire-safe signal that can represent any action, not just entries.
///
/// Uses `#[serde(tag = "action")]` so each variant is distinguished by an
/// `"action"` field in the JSON/Bincode representation.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "action", deny_unknown_fields)]
pub enum RawSignalMsg {
    /// Open a new position (same semantics as `RawSignalEntryMsg`).
    Entry {
        ts: String,
        symbol: String,
        side: String,
        order_type: String,
        price: Option<f64>,
        risk: f64,
        stoploss: Option<f64>,
        #[serde(default)]
        targets: Vec<f64>,
        #[serde(default)]
        group: Option<String>,
        /// Application-defined trade id. Required for `ByTradeId` resolution.
        #[serde(default)]
        trade_id: Option<String>,
        /// Optional semantic class used for per-entry profile routing.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        entry_class: Option<String>,
    },
    /// Close position(s) at market.
    Close {
        ts: String,
        position: PositionRefMsg,
    },
    /// Close a fraction of position(s).
    ClosePartial {
        ts: String,
        position: PositionRefMsg,
        ratio: f64,
    },
    /// Set or replace the stoploss price.
    ModifyStoploss {
        ts: String,
        position: PositionRefMsg,
        price: f64,
    },
    /// Move stoploss to the average entry price.
    MoveStoplossToEntry {
        ts: String,
        position: PositionRefMsg,
    },
    /// Add a take-profit level.
    AddTarget {
        ts: String,
        position: PositionRefMsg,
        price: f64,
        close_ratio: f64,
    },
    /// Remove a take-profit level at a specific price.
    RemoveTarget {
        ts: String,
        position: PositionRefMsg,
        price: f64,
    },
    /// Atomically change an existing take-profit price while retaining its ratio.
    ModifyTarget {
        ts: String,
        position: PositionRefMsg,
        old_price: f64,
        new_price: f64,
    },
    /// Attach a management rule.
    AddRule {
        ts: String,
        position: PositionRefMsg,
        rule: RuleConfigDefMsg,
    },
    /// Remove a management rule by name.
    RemoveRule {
        ts: String,
        position: PositionRefMsg,
        rule_name: String,
    },
    /// Scale into an existing position.
    ScaleIn {
        ts: String,
        position: PositionRefMsg,
        price: Option<f64>,
        size: f64,
    },
    /// Cancel a pending order.
    CancelPending {
        ts: String,
        position: PositionRefMsg,
    },
    /// Close all open positions on a symbol.
    CloseAllOf { ts: String, symbol: String },
    /// Close all open positions.
    CloseAll { ts: String },
    /// Cancel all pending orders.
    CancelAllPending { ts: String },
    /// Modify stoploss for all open positions on a symbol.
    ModifyAllStoploss {
        ts: String,
        symbol: String,
        price: f64,
    },
    /// Close all open positions in a group.
    CloseAllInGroup { ts: String, group_id: String },
    /// Modify stoploss for all open positions in a group.
    ModifyAllStoplossInGroup {
        ts: String,
        group_id: String,
        price: f64,
    },
}

impl RawSignalMsg {
    /// Extract the timestamp string from any variant.
    pub fn ts(&self) -> &str {
        match self {
            RawSignalMsg::Entry { ts, .. }
            | RawSignalMsg::Close { ts, .. }
            | RawSignalMsg::ClosePartial { ts, .. }
            | RawSignalMsg::ModifyStoploss { ts, .. }
            | RawSignalMsg::MoveStoplossToEntry { ts, .. }
            | RawSignalMsg::AddTarget { ts, .. }
            | RawSignalMsg::RemoveTarget { ts, .. }
            | RawSignalMsg::ModifyTarget { ts, .. }
            | RawSignalMsg::AddRule { ts, .. }
            | RawSignalMsg::RemoveRule { ts, .. }
            | RawSignalMsg::ScaleIn { ts, .. }
            | RawSignalMsg::CancelPending { ts, .. }
            | RawSignalMsg::CloseAllOf { ts, .. }
            | RawSignalMsg::CloseAll { ts }
            | RawSignalMsg::CancelAllPending { ts }
            | RawSignalMsg::ModifyAllStoploss { ts, .. }
            | RawSignalMsg::CloseAllInGroup { ts, .. }
            | RawSignalMsg::ModifyAllStoplossInGroup { ts, .. } => ts,
        }
    }
}

/// Wire-safe position reference.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum PositionRefMsg {
    /// Target the position with the given application-defined trade id.
    ByTradeId { trade_id: String },
    /// All open positions on this symbol.
    AllOnSymbol { symbol: String },
    /// All open positions in this group.
    AllInGroup { group_id: String },
}

// ── Strict request decoding ──────────────────────────────────────────────────

#[derive(Serialize, Deserialize)]
#[serde(tag = "type", deny_unknown_fields)]
enum StrictSizingPolicyMsg {
    FixedLot { lots: f64 },
    FixedRiskAmount { amount: f64 },
    BalanceRiskPercent { percent: f64 },
}

#[derive(Serialize, Deserialize)]
#[serde(tag = "type", deny_unknown_fields)]
enum StrictCommissionModelMsg {
    #[serde(alias = "per_lot_per_side")]
    PerLotPerSide { amount: f64, currency: String },
    #[serde(alias = "notional_rate_per_side")]
    NotionalRatePerSide { buy_rate: f64, sell_rate: f64 },
}

#[derive(Serialize, Deserialize)]
#[serde(tag = "unit", deny_unknown_fields)]
enum StrictSwapAmountMsg {
    #[serde(alias = "points")]
    Points { long: f64, short: f64 },
    #[serde(alias = "currency")]
    Currency {
        long: f64,
        short: f64,
        currency: String,
    },
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictSwapScheduleMsg {
    amount: StrictSwapAmountMsg,
    rollover: String,
    triple_weekday: String,
    #[serde(default)]
    skipped_weekdays: Vec<String>,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictInstrumentCostsMsg {
    #[serde(default)]
    commission: Option<StrictCommissionModelMsg>,
    #[serde(default)]
    swap: Option<StrictSwapScheduleMsg>,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictBacktestConfigMsg {
    initial_balance: Option<f64>,
    close_on_finish: Option<bool>,
    fill_model: Option<String>,
    #[serde(default)]
    sizing: Option<StrictSizingPolicyMsg>,
    #[serde(default)]
    costs: BTreeMap<String, StrictInstrumentCostsMsg>,
}

#[derive(Serialize, Deserialize)]
#[serde(tag = "type", deny_unknown_fields)]
enum StrictStoplossModeMsg {
    FromSignal,
    None,
    FixedDistance { distance: f64 },
    FixedPrice { price: f64 },
    FromSignalDistance { multiplier: f64 },
}

#[derive(Serialize, Deserialize)]
#[serde(tag = "type", deny_unknown_fields)]
enum StrictTargetSourceMsg {
    FromSignal,
    StopDistanceMultiples { multiples: Vec<f64> },
}

#[derive(Serialize, Deserialize)]
#[serde(tag = "type", deny_unknown_fields)]
enum StrictRuleConfigDefMsg {
    FixedStoploss { price: f64 },
    TrailingStop { distance: f64 },
    TakeProfit { price: f64, close_ratio: f64 },
    BreakevenWhen { trigger_price: f64 },
    BreakevenWhenOffset { trigger_price_offset: f64 },
    BreakevenAfterTargets { after_n: u32 },
    TimeExit { max_seconds: u64 },
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictManagementProfileMsg {
    name: String,
    #[serde(default)]
    target_selection: Option<TargetSelectionMsg>,
    use_targets: Vec<usize>,
    close_ratios: Vec<f64>,
    #[serde(default)]
    target_source: Option<StrictTargetSourceMsg>,
    #[serde(default)]
    stoploss_mode: Option<StrictStoplossModeMsg>,
    #[serde(default)]
    rules: Vec<StrictRuleConfigDefMsg>,
    #[serde(default)]
    group_override: Option<String>,
    #[serde(default)]
    let_remainder_run: bool,
    #[serde(default)]
    entry_geometry: Option<EntryGeometryPolicyMsg>,
}

#[derive(Serialize, Deserialize)]
#[serde(tag = "type", deny_unknown_fields)]
enum StrictPositionRefMsg {
    ByTradeId { trade_id: String },
    AllOnSymbol { symbol: String },
    AllInGroup { group_id: String },
}

#[derive(Serialize, Deserialize)]
#[serde(tag = "action", deny_unknown_fields)]
enum StrictRawSignalMsg {
    Entry {
        ts: String,
        symbol: String,
        side: String,
        order_type: String,
        price: Option<f64>,
        risk: f64,
        stoploss: Option<f64>,
        #[serde(default)]
        targets: Vec<f64>,
        #[serde(default)]
        group: Option<String>,
        #[serde(default)]
        trade_id: Option<String>,
        #[serde(default)]
        entry_class: Option<String>,
    },
    Close {
        ts: String,
        position: StrictPositionRefMsg,
    },
    ClosePartial {
        ts: String,
        position: StrictPositionRefMsg,
        ratio: f64,
    },
    ModifyStoploss {
        ts: String,
        position: StrictPositionRefMsg,
        price: f64,
    },
    MoveStoplossToEntry {
        ts: String,
        position: StrictPositionRefMsg,
    },
    AddTarget {
        ts: String,
        position: StrictPositionRefMsg,
        price: f64,
        close_ratio: f64,
    },
    RemoveTarget {
        ts: String,
        position: StrictPositionRefMsg,
        price: f64,
    },
    ModifyTarget {
        ts: String,
        position: StrictPositionRefMsg,
        old_price: f64,
        new_price: f64,
    },
    AddRule {
        ts: String,
        position: StrictPositionRefMsg,
        rule: StrictRuleConfigDefMsg,
    },
    RemoveRule {
        ts: String,
        position: StrictPositionRefMsg,
        rule_name: String,
    },
    ScaleIn {
        ts: String,
        position: StrictPositionRefMsg,
        price: Option<f64>,
        size: f64,
    },
    CancelPending {
        ts: String,
        position: StrictPositionRefMsg,
    },
    CloseAllOf {
        ts: String,
        symbol: String,
    },
    CloseAll {
        ts: String,
    },
    CancelAllPending {
        ts: String,
    },
    ModifyAllStoploss {
        ts: String,
        symbol: String,
        price: f64,
    },
    CloseAllInGroup {
        ts: String,
        group_id: String,
    },
    ModifyAllStoplossInGroup {
        ts: String,
        group_id: String,
        price: f64,
    },
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictBacktestRunSpec {
    #[serde(default)]
    on_unavailable: UnavailableInstrumentPolicyMsg,
    symbol: String,
    #[serde(default)]
    symbols: Vec<String>,
    #[serde(default)]
    all_symbols: bool,
    exchange: String,
    data_type: String,
    timeframe: Option<String>,
    from: Option<String>,
    to: Option<String>,
    #[serde(default)]
    raw_signals: Vec<StrictRawSignalMsg>,
    profile: Option<String>,
    #[serde(default)]
    profile_def: Option<StrictManagementProfileMsg>,
    #[serde(default)]
    entry_profile_routes: Vec<StrictEntryProfileRouteMsg>,
    config: StrictBacktestConfigMsg,
}

#[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum StrictProfileRef {
    Named(String),
    Inline(StrictManagementProfileMsg),
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictEntryProfileRouteMsg {
    entry_class: String,
    profile: StrictProfileRef,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictBacktestMultiRunSpec {
    #[serde(default)]
    on_unavailable: UnavailableInstrumentPolicyMsg,
    symbol: String,
    #[serde(default)]
    symbols: Vec<String>,
    #[serde(default)]
    all_symbols: bool,
    exchange: String,
    data_type: String,
    timeframe: Option<String>,
    from: Option<String>,
    to: Option<String>,
    #[serde(default)]
    raw_signals: Vec<StrictRawSignalMsg>,
    profiles: Vec<StrictProfileRef>,
    #[serde(default)]
    entry_profile_routes: Vec<StrictEntryProfileRouteMsg>,
    config: StrictBacktestConfigMsg,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictRunBacktestRequest {
    request: StrictBacktestRunSpec,
    #[serde(default)]
    future: FutureQuoteConfigMsg,
    #[serde(default)]
    evaluation: ProviderEvaluationOptionsMsg,
    #[serde(default)]
    result_delivery: ResultDeliveryMsg,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictSubmitBacktestRequest {
    request: RunBacktestRequest,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictRunBacktestMultiRequest {
    request: StrictBacktestMultiRunSpec,
    #[serde(default)]
    future: FutureQuoteConfigMsg,
    #[serde(default)]
    evaluation: ProviderEvaluationOptionsMsg,
    #[serde(default)]
    result_delivery: ResultDeliveryMsg,
}

fn strict_into_wire<T>(value: impl Serialize) -> Result<T, serde_json::Error>
where
    T: DeserializeOwned,
{
    serde_json::from_value(serde_json::to_value(value)?)
}

impl<'de> Deserialize<'de> for RunBacktestRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let strict = StrictRunBacktestRequest::deserialize(deserializer)?;
        Ok(Self {
            request: strict_into_wire(strict.request).map_err(serde::de::Error::custom)?,
            future: strict.future,
            evaluation: strict.evaluation,
            result_delivery: strict.result_delivery,
        })
    }
}

impl<'de> Deserialize<'de> for SubmitBacktestRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let strict = StrictSubmitBacktestRequest::deserialize(deserializer)?;
        Ok(Self {
            request: strict.request,
        })
    }
}

impl<'de> Deserialize<'de> for RunBacktestMultiRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let strict = StrictRunBacktestMultiRequest::deserialize(deserializer)?;
        Ok(Self {
            request: strict_into_wire(strict.request).map_err(serde::de::Error::custom)?,
            future: strict.future,
            evaluation: strict.evaluation,
            result_delivery: strict.result_delivery,
        })
    }
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictConfiguredStrategyRunSpec {
    symbol: String,
    exchange: String,
    data_type: String,
    #[serde(default)]
    timeframe: Option<String>,
    #[serde(default)]
    from: Option<String>,
    #[serde(default)]
    to: Option<String>,
    strategy: ConfiguredStrategyRunMsg,
    #[serde(default)]
    profile: Option<String>,
    #[serde(default)]
    profile_def: Option<StrictManagementProfileMsg>,
    #[serde(default)]
    entry_profile_routes: Vec<StrictEntryProfileRouteMsg>,
    config: StrictBacktestConfigMsg,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictRunConfiguredStrategyRequest {
    request: StrictConfiguredStrategyRunSpec,
    #[serde(default)]
    future: FutureQuoteConfigMsg,
    #[serde(default)]
    evaluation: ProviderEvaluationOptionsMsg,
    #[serde(default)]
    result_delivery: ResultDeliveryMsg,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictSubmitConfiguredStrategyRequest {
    request: RunConfiguredStrategyRequest,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictSearchExecutionVariantMsg {
    id: String,
    config: StrictBacktestConfigMsg,
    #[serde(default)]
    future: FutureQuoteConfigMsg,
    #[serde(default)]
    profile: Option<String>,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictSearchPortfolioCandidateMsg {
    id: String,
    #[serde(default)]
    instances: Vec<StrictPortfolioInstanceMsg>,
    #[serde(default)]
    direct_instances: Vec<SearchDirectPortfolioInstanceMsg>,
    #[serde(default)]
    policies: Option<serde_json::Value>,
    #[serde(default)]
    groups: Option<serde_json::Value>,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictSearchRunSpec {
    template: serde_json::Value,
    space: serde_json::Value,
    symbols: Vec<String>,
    exchange: String,
    data_type: String,
    #[serde(default)]
    timeframe: Option<String>,
    windows: SearchWindowsMsg,
    config: StrictBacktestConfigMsg,
    #[serde(default)]
    profile: Option<String>,
    #[serde(default)]
    entry_profile_routes: Vec<StrictEntryProfileRouteMsg>,
    #[serde(default)]
    workers: Option<usize>,
    #[serde(default)]
    decision_latency_ms: u64,
    #[serde(default)]
    structural: Option<serde_json::Value>,
    #[serde(default)]
    resource_limits: Option<serde_json::Value>,
    #[serde(default)]
    variants: Vec<StrictSearchExecutionVariantMsg>,
    #[serde(default)]
    direct_factory: Option<SearchDirectFactoryMsg>,
    #[serde(default)]
    resume_checkpoint: Option<serde_json::Value>,
    #[serde(default)]
    selected_rerun: Option<SearchSelectedRerunMsg>,
    #[serde(default)]
    portfolio_candidates: Vec<StrictSearchPortfolioCandidateMsg>,
    #[serde(default)]
    series_descriptors: Vec<serde_json::Value>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictSubmitSearchRequest {
    request: StrictSearchRunSpec,
    #[serde(default)]
    future: FutureQuoteConfigMsg,
    #[serde(default)]
    evaluation: ProviderEvaluationOptionsMsg,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictPortfolioInstanceMsg {
    symbol: String,
    strategy: ConfiguredStrategyRunMsg,
    #[serde(default)]
    profile: Option<String>,
    #[serde(default)]
    profile_def: Option<StrictManagementProfileMsg>,
    #[serde(default)]
    entry_profile_routes: Vec<StrictEntryProfileRouteMsg>,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictPortfolioRunSpec {
    instances: Vec<StrictPortfolioInstanceMsg>,
    exchange: String,
    data_type: String,
    #[serde(default)]
    timeframe: Option<String>,
    #[serde(default)]
    from: Option<String>,
    #[serde(default)]
    to: Option<String>,
    config: StrictBacktestConfigMsg,
    #[serde(default)]
    policies: Option<serde_json::Value>,
    #[serde(default)]
    groups: Option<serde_json::Value>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictRunPortfolioRequest {
    request: StrictPortfolioRunSpec,
    #[serde(default)]
    future: FutureQuoteConfigMsg,
    #[serde(default)]
    evaluation: ProviderEvaluationOptionsMsg,
    #[serde(default)]
    result_delivery: ResultDeliveryMsg,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct StrictSubmitPortfolioRequest {
    request: RunPortfolioRequest,
}

impl<'de> Deserialize<'de> for RunPortfolioRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let strict = StrictRunPortfolioRequest::deserialize(deserializer)?;
        Ok(Self {
            request: strict_into_wire(strict.request).map_err(serde::de::Error::custom)?,
            future: strict.future,
            evaluation: strict.evaluation,
            result_delivery: strict.result_delivery,
        })
    }
}

impl<'de> Deserialize<'de> for SubmitPortfolioRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let strict = StrictSubmitPortfolioRequest::deserialize(deserializer)?;
        Ok(Self {
            request: strict.request,
        })
    }
}

impl<'de> Deserialize<'de> for RunConfiguredStrategyRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let strict = StrictRunConfiguredStrategyRequest::deserialize(deserializer)?;
        Ok(Self {
            request: strict_into_wire(strict.request).map_err(serde::de::Error::custom)?,
            future: strict.future,
            evaluation: strict.evaluation,
            result_delivery: strict.result_delivery,
        })
    }
}

impl<'de> Deserialize<'de> for SubmitConfiguredStrategyRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let strict = StrictSubmitConfiguredStrategyRequest::deserialize(deserializer)?;
        Ok(Self {
            request: strict.request,
        })
    }
}

impl<'de> Deserialize<'de> for SubmitSearchRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let strict = StrictSubmitSearchRequest::deserialize(deserializer)?;
        Ok(Self {
            request: strict_into_wire(strict.request).map_err(serde::de::Error::custom)?,
            future: strict.future,
            evaluation: strict.evaluation,
        })
    }
}

// ── Phase 2: Profile Management ─────────────────────────────────────────────

/// Request to add (or overwrite) a management profile at runtime.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AddProfileRequest {
    pub profile: ManagementProfileMsg,
    #[serde(default)]
    pub overwrite: bool,
}

/// Response from adding a profile.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AddProfileResponse {
    pub success: bool,
    pub error: Option<String>,
    pub profile_count: usize,
}

/// Request to remove a management profile by name.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RemoveProfileRequest {
    pub name: String,
}

/// Response from removing a profile.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RemoveProfileResponse {
    pub success: bool,
    pub error: Option<String>,
    pub profile_count: usize,
}

/// Response from reloading profiles from disk.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReloadProfilesResponse {
    pub success: bool,
    pub error: Option<String>,
    pub profile_count: usize,
    pub loaded_from: String,
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn entry_fields() -> serde_json::Value {
        json!({
            "action": "Entry",
            "ts": "2026-01-02T10:00:00",
            "symbol": "eurusd",
            "side": "Buy",
            "order_type": "Market",
            "price": null,
            "risk": 1.5,
            "stoploss": 1.08
        })
    }

    #[test]
    fn entry_requires_risk_and_rejects_size() {
        let entry: RawSignalMsg = serde_json::from_value(entry_fields()).unwrap();
        assert!(matches!(entry, RawSignalMsg::Entry { risk, .. } if risk == 1.5));

        let mut with_size = entry_fields();
        with_size.as_object_mut().unwrap().remove("risk");
        with_size["size"] = json!(0.1);
        let error = serde_json::from_value::<RawSignalMsg>(with_size).unwrap_err();
        assert!(error.to_string().contains("unknown field `size`"));

        let mut missing_risk = entry_fields();
        missing_risk.as_object_mut().unwrap().remove("risk");
        let error = serde_json::from_value::<RawSignalMsg>(missing_risk).unwrap_err();
        assert!(error.to_string().contains("missing field `risk`"));
    }

    #[test]
    fn scale_in_keeps_size_field() {
        let signal: RawSignalMsg = serde_json::from_value(json!({
            "action": "ScaleIn",
            "ts": "2026-01-02T10:01:00",
            "position": { "type": "ByTradeId", "trade_id": "trade-1" },
            "price": null,
            "size": 0.25
        }))
        .unwrap();
        assert!(matches!(signal, RawSignalMsg::ScaleIn { size, .. } if size == 0.25));
    }

    #[test]
    fn current_sizing_and_future_fields_are_strict() {
        let sizing: SizingPolicyMsg = serde_json::from_value(json!({
            "type": "FixedRiskAmount",
            "amount": 100.0
        }))
        .unwrap();
        assert!(matches!(
            sizing,
            SizingPolicyMsg::FixedRiskAmount { amount } if amount == 100.0
        ));
        assert!(
            serde_json::from_value::<SizingPolicyMsg>(json!({
                "type": "FixedLot",
                "qty": "all=0.01"
            }))
            .is_err()
        );

        let future: FutureQuoteConfigMsg = serde_json::from_value(json!({
            "account_currency": "USD",
            "conversion_stale_after_ms": 15_000
        }))
        .unwrap();
        assert_eq!(future.account_currency, "USD");
        assert_eq!(future.conversion_stale_after_ms, 15_000);
        assert_eq!(
            future.mtm_output,
            MtmOutputPolicyMsg::Bounded { max_points: 4_096 }
        );
        assert_eq!(
            future.market_entry_sizing_basis,
            MarketEntrySizingBasisMsg::FillPrice
        );
        assert!(
            serde_json::from_value::<FutureQuoteConfigMsg>(json!({
                "account_currency": "USD",
                "conversion_rates": {}
            }))
            .is_err()
        );
    }

    #[test]
    fn market_entry_sizing_basis_uses_strict_snake_case_wire_values() {
        for (value, expected) in [
            (json!("fill_price"), MarketEntrySizingBasisMsg::FillPrice),
            (
                json!("signal_entry_price"),
                MarketEntrySizingBasisMsg::SignalEntryPrice,
            ),
        ] {
            let basis: MarketEntrySizingBasisMsg = serde_json::from_value(value.clone()).unwrap();
            assert_eq!(basis, expected);
            assert_eq!(serde_json::to_value(basis).unwrap(), value);
        }

        assert!(serde_json::from_value::<MarketEntrySizingBasisMsg>(json!("mark_price")).is_err());
        assert!(
            serde_json::from_value::<FutureQuoteConfigMsg>(json!({
                "market_entry_sizing_basis": "mark_price"
            }))
            .is_err()
        );
    }

    #[test]
    fn mtm_output_policy_uses_strict_snake_case_wire_values() {
        for (value, expected) in [
            (json!("none"), MtmOutputPolicyMsg::None),
            (
                json!({ "bounded": { "max_points": 512 } }),
                MtmOutputPolicyMsg::Bounded { max_points: 512 },
            ),
            (json!("full"), MtmOutputPolicyMsg::Full),
        ] {
            let policy: MtmOutputPolicyMsg = serde_json::from_value(value.clone()).unwrap();
            assert_eq!(policy, expected);
            assert_eq!(serde_json::to_value(policy).unwrap(), value);
        }

        assert!(
            serde_json::from_value::<MtmOutputPolicyMsg>(json!({
                "bounded": { "max_points": 512, "unexpected": true }
            }))
            .is_err()
        );
    }

    #[test]
    fn future_result_defaults_missing_mtm_output_summary() {
        let result: FutureBacktestResultMsg = serde_json::from_value(json!({
            "format_version": 1,
            "execution_metadata": null,
            "recorded_fills": null,
            "action_dispositions": null,
            "close_events": null,
            "completed_positions": null,
            "open_positions": null,
            "pending_orders": null,
            "pending_order_lifecycle": [],
            "mtm_equity_curve": null,
            "mtm_max_drawdown": null,
            "mtm_max_drawdown_pct": null,
            "provider_evaluation": null
        }))
        .unwrap();

        assert_eq!(result.mtm_output_summary, MtmOutputSummaryMsg::default());
        assert_eq!(result.mtm_output_summary.policy, MtmOutputPolicyMsg::Full);

        let summary: MtmOutputSummaryMsg = serde_json::from_value(json!({
            "policy": "full",
            "observed_points": 4,
            "retained_points": 4,
            "omitted_points": 0,
            "future_addition": true
        }))
        .unwrap();
        assert_eq!(summary.policy, MtmOutputPolicyMsg::Full);
    }

    fn minimal_request_json() -> serde_json::Value {
        json!({
            "request": {
                "symbol": "EURUSD",
                "exchange": "fixture",
                "data_type": "tick",
                "timeframe": null,
                "from": null,
                "to": null,
                "raw_signals": [],
                "profile": null,
                "config": {
                    "initial_balance": null,
                    "close_on_finish": null,
                    "fill_model": null
                }
            },
            "future": {
                "account_currency": "USD"
            }
        })
    }

    #[test]
    fn omitted_delivery_and_mtm_fields_use_current_defaults() {
        let request: RunBacktestRequest = serde_json::from_value(minimal_request_json()).unwrap();
        assert_eq!(request.result_delivery, ResultDeliveryMsg::Auto);
        assert_eq!(
            request.future.mtm_output,
            MtmOutputPolicyMsg::Bounded { max_points: 4_096 }
        );
        assert_eq!(
            request.future.market_entry_sizing_basis,
            MarketEntrySizingBasisMsg::FillPrice
        );

        let submitted: SubmitBacktestRequest = serde_json::from_value(json!({
            "request": minimal_request_json()
        }))
        .unwrap();
        assert_eq!(submitted.request.result_delivery, ResultDeliveryMsg::Auto);
        assert_eq!(
            submitted.request.future.mtm_output,
            MtmOutputPolicyMsg::Bounded { max_points: 4_096 }
        );

        let mut explicit = minimal_request_json();
        explicit["result_delivery"] = json!("auto");
        explicit["future"]["mtm_output"] = json!({
            "bounded": { "max_points": 4_096 }
        });
        let explicit: RunBacktestRequest = serde_json::from_value(explicit).unwrap();
        assert_eq!(explicit.result_delivery, ResultDeliveryMsg::Auto);
        assert_eq!(
            explicit.future.mtm_output,
            MtmOutputPolicyMsg::Bounded { max_points: 4_096 }
        );

        let mut multi_request = minimal_request_json()["request"].clone();
        let fields = multi_request.as_object_mut().unwrap();
        fields.remove("profile");
        fields.insert("profiles".into(), json!([]));
        let multi: RunBacktestMultiRequest = serde_json::from_value(json!({
            "request": multi_request,
            "future": { "account_currency": "USD" }
        }))
        .unwrap();
        assert_eq!(multi.result_delivery, ResultDeliveryMsg::Auto);
        assert_eq!(
            multi.future.mtm_output,
            MtmOutputPolicyMsg::Bounded { max_points: 4_096 }
        );
    }

    #[test]
    fn older_async_result_responses_default_artifact_consumption_state() {
        let response: GetBacktestResultResponse = serde_json::from_value(json!({
            "success": true,
            "job_id": "job-old",
            "result": null,
            "error": null,
            "inline_complete": true
        }))
        .unwrap();
        assert!(!response.artifact_consumed);
    }
}