quant-system-core 0.2.7

Core trading domain — execution, normalized intent, management policy, sizing, and currency conversion
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
//! Management profiles — decouple entry signals from trade management.
//!
//! A [`ManagementProfile`] resolves [`RawSignal::Entry`] fields before sizing.
//! Resolved entries can be finalized into [`Action::Open`] calls after a concrete lot size is known.
//! Profile definitions are loaded by an application-owned registry for comparison without recompilation.

use std::collections::HashSet;

use chrono::NaiveDateTime;
use serde::{Deserialize, Serialize};

use crate::TradeEngine;
use crate::types::{
    Action, GroupId, OrderType, PositionId, PositionStatus, RuleConfig, Side, TargetSpec, TradeId,
};

// ─── Errors ─────────────────────────────────────────────────────────────────

/// Errors returned while validating a management profile definition.
#[derive(Debug, thiserror::Error)]
pub enum ProfileValidationError {
    #[error(
        "Profile '{profile}': selected target count ({targets}) does not match close_ratios length ({ratios})"
    )]
    TargetRatioMismatch {
        profile: String,
        targets: usize,
        ratios: usize,
    },

    #[error("Profile '{profile}': close_ratios sum to {sum:.4}, which exceeds 1.0")]
    RatioSumExceeded { profile: String, sum: f64 },

    #[error(
        "Profile '{profile}': close_ratios sum to {sum:.4}; they must sum to 1.0 when let_remainder_run is false"
    )]
    RatioSumIncomplete { profile: String, sum: f64 },

    #[error("Profile '{profile}': close_ratios contains a non-finite or non-positive value")]
    ZeroRatio { profile: String },

    #[error("Profile '{profile}': target selection contains a 0 index (must be 1-indexed)")]
    ZeroTargetIndex { profile: String },

    #[error("Profile '{profile}': target index {index} is selected more than once")]
    DuplicateTargetIndex { profile: String, index: usize },

    #[error("Profile '{profile}': {reason}")]
    InvalidConfiguration { profile: String, reason: String },
}

/// Strict validation failures returned by the canonical entry resolvers.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum ProfileApplicationError {
    #[error("{field} must be finite and greater than zero, got {value}")]
    InvalidNumericInput { field: String, value: f64 },

    #[error("target indices are 1-based; index 0 is invalid")]
    ZeroTargetIndex,

    #[error("target index {index} is selected more than once")]
    DuplicateTargetIndex { index: usize },

    #[error("target price {price} is selected more than once")]
    DuplicateTargetPrice { price: f64 },

    #[error("target index {index} is missing; signal provides {available} target(s)")]
    MissingTargetIndex { index: usize, available: usize },

    #[error("selected target count ({targets}) does not match explicit weight count ({weights})")]
    TargetWeightCountMismatch { targets: usize, weights: usize },

    #[error("target weight {position} must be finite and greater than zero, got {weight}")]
    InvalidTargetWeight { position: usize, weight: f64 },

    #[error("target weights sum to {sum}, which exceeds 1.0")]
    TargetWeightSumExceeded { sum: f64 },

    #[error("target weights sum to {sum}; they must sum to 1.0 when no remainder runs")]
    TargetWeightSumIncomplete { sum: f64 },

    #[error(
        "target {index} at {target} is invalid for {side} entry at {entry}: buy targets must be above entry and sell targets below entry"
    )]
    InvalidTargetGeometry {
        index: usize,
        side: Side,
        entry: f64,
        target: f64,
    },

    #[error(
        "stop {stoploss} is invalid for {side} entry at {entry}: buy stops must be below entry and sell stops above entry"
    )]
    InvalidStopGeometry {
        side: Side,
        entry: f64,
        stoploss: f64,
    },

    #[error("size {size} is not an integer multiple of lot_step {lot_step}")]
    SizeNotMultipleOfLotStep { size: f64, lot_step: f64 },

    #[error("size {size} and lot_step {lot_step} produce a lot count outside u64 range")]
    LotUnitCountOverflow { size: f64, lot_step: f64 },

    #[error("target allocation {position} rounds to zero lot units")]
    ZeroUnitAllocation { position: usize },

    #[error("allocation remainder must be finite and non-negative, got {remainder}")]
    InvalidRemainder { remainder: f64 },

    #[error(
        "target weights sum to {sum}, but allocation remainder is {remainder}; together they must equal 1.0"
    )]
    TargetWeightRemainderMismatch { sum: f64, remainder: f64 },

    #[error("{field} must be greater than zero, got {value}")]
    InvalidCountInput { field: String, value: u64 },
}

// ─── PositionRef ────────────────────────────────────────────────────────────

/// How a management signal references its target position(s).
///
/// Resolved at runtime by the backtest runner, which has access to
/// engine state for lookup.
///
/// The minimal set is:
/// - `ByTradeId`: the canonical parser path. Each entry carries an
///   application-defined `trade_id`; management signals reference it.
/// - `AllOnSymbol`: bulk close by symbol.
/// - `AllInGroup`: bulk close by group.
///
/// `group` is a reporting tag (channel-level), while `trade_id` is the
/// per-trade identity used for addressing.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum PositionRef {
    /// Target the position with the given application-defined trade id.
    ByTradeId { trade_id: TradeId },
    /// All open positions on a symbol.
    AllOnSymbol { symbol: String },
    /// All open positions in a group.
    AllInGroup { group_id: GroupId },
}

// ─── RawSignal ──────────────────────────────────────────────────────────────

fn deserialize_risk_multiplier<'de, D>(deserializer: D) -> Result<f64, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = f64::deserialize(deserializer)?;
    if value.is_finite() && value > 0.0 {
        Ok(value)
    } else {
        Err(serde::de::Error::custom(format!(
            "risk must be finite and greater than zero, got {value}"
        )))
    }
}

/// A raw signal from an external source — entry or management.
///
/// Covers both entry signals (which can be profile-transformed) and
/// management signals (which pass through to the engine as-is after
/// position resolution).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "action", deny_unknown_fields)]
pub enum RawSignal {
    // ── Entry (profile-transformable) ───────────────────────────────
    Entry {
        ts: NaiveDateTime,
        symbol: String,
        side: Side,
        order_type: OrderType,
        price: Option<f64>,
        #[serde(rename = "risk", deserialize_with = "deserialize_risk_multiplier")]
        risk_multiplier: f64,
        stoploss: Option<f64>,
        #[serde(default)]
        targets: Vec<f64>,
        #[serde(default)]
        group: Option<String>,
        /// Application-defined trade identity. Required for `ByTradeId`
        /// resolution. Older JSONL without this field is still accepted.
        #[serde(default)]
        trade_id: Option<TradeId>,
    },

    // ── Per-position management ─────────────────────────────────────
    Close {
        ts: NaiveDateTime,
        position: PositionRef,
    },
    ClosePartial {
        ts: NaiveDateTime,
        position: PositionRef,
        ratio: f64,
    },
    ModifyStoploss {
        ts: NaiveDateTime,
        position: PositionRef,
        price: f64,
    },
    MoveStoplossToEntry {
        ts: NaiveDateTime,
        position: PositionRef,
    },
    AddTarget {
        ts: NaiveDateTime,
        position: PositionRef,
        price: f64,
        close_ratio: f64,
    },
    RemoveTarget {
        ts: NaiveDateTime,
        position: PositionRef,
        price: f64,
    },
    ModifyTarget {
        ts: NaiveDateTime,
        position: PositionRef,
        old_price: f64,
        new_price: f64,
    },
    AddRule {
        ts: NaiveDateTime,
        position: PositionRef,
        rule: RuleConfigDef,
    },
    RemoveRule {
        ts: NaiveDateTime,
        position: PositionRef,
        rule_name: String,
    },
    ScaleIn {
        ts: NaiveDateTime,
        position: PositionRef,
        price: Option<f64>,
        size: f64,
    },
    CancelPending {
        ts: NaiveDateTime,
        position: PositionRef,
    },

    // ── Bulk actions ────────────────────────────────────────────────
    CloseAllOf {
        ts: NaiveDateTime,
        symbol: String,
    },
    CloseAll {
        ts: NaiveDateTime,
    },
    CancelAllPending {
        ts: NaiveDateTime,
    },
    ModifyAllStoploss {
        ts: NaiveDateTime,
        symbol: String,
        price: f64,
    },
    CloseAllInGroup {
        ts: NaiveDateTime,
        group_id: GroupId,
    },
    ModifyAllStoplossInGroup {
        ts: NaiveDateTime,
        group_id: GroupId,
        price: f64,
    },
}

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

    /// Returns `true` if this is an `Entry` variant.
    pub fn is_entry(&self) -> bool {
        matches!(self, Self::Entry { .. })
    }
}

// ─── Position Resolution ────────────────────────────────────────────────────

/// Resolves a `PositionRef` to concrete position ID(s) using engine state.
pub trait PositionResolver {
    /// Resolve a position reference to zero or more concrete position IDs.
    fn resolve(&self, pr: &PositionRef) -> Vec<PositionId>;
    /// Get entry info (average_entry, side) for a position.
    fn position_entry_info(&self, id: &PositionId) -> Option<(f64, Side)>;
}

impl PositionResolver for TradeEngine {
    fn resolve(&self, position: &PositionRef) -> Vec<PositionId> {
        match position {
            PositionRef::ByTradeId { trade_id } => {
                self.manager.id_by_trade_id(trade_id).into_iter().collect()
            }
            PositionRef::AllOnSymbol { symbol } => self.manager.open_ids_by_symbol_sorted(symbol),
            PositionRef::AllInGroup { group_id } => {
                let mut ids = self.manager.open_ids_by_group(group_id);
                ids.sort();
                ids
            }
        }
    }

    fn position_entry_info(&self, id: &PositionId) -> Option<(f64, Side)> {
        self.get_position(id).and_then(|position| {
            if position.data.status == PositionStatus::Open {
                Some((position.data.average_entry(), position.data.side))
            } else {
                None
            }
        })
    }
}

/// Resolve a non-entry `RawSignal` into concrete `Action`(s).
///
/// Entry signals are not handled here — they go through the profile path.
/// Returns an empty vec for `Entry` variants.
pub fn resolve_signal(signal: &RawSignal, resolver: &impl PositionResolver) -> Vec<Action> {
    match signal {
        RawSignal::Entry { .. } => vec![],

        RawSignal::Close { position, .. } => resolver
            .resolve(position)
            .into_iter()
            .map(|id| Action::ClosePosition { position_id: id })
            .collect(),

        RawSignal::ClosePartial {
            position, ratio, ..
        } => resolver
            .resolve(position)
            .into_iter()
            .map(|id| Action::ClosePartial {
                position_id: id,
                ratio: *ratio,
            })
            .collect(),

        RawSignal::ModifyStoploss {
            position, price, ..
        } => resolver
            .resolve(position)
            .into_iter()
            .map(|id| Action::ModifyStoploss {
                position_id: id,
                price: *price,
            })
            .collect(),

        RawSignal::MoveStoplossToEntry { position, .. } => resolver
            .resolve(position)
            .into_iter()
            .map(|id| Action::MoveStoplossToEntry { position_id: id })
            .collect(),

        RawSignal::AddTarget {
            position,
            price,
            close_ratio,
            ..
        } => resolver
            .resolve(position)
            .into_iter()
            .map(|id| Action::AddTarget {
                position_id: id,
                price: *price,
                close_ratio: *close_ratio,
            })
            .collect(),

        RawSignal::RemoveTarget {
            position, price, ..
        } => resolver
            .resolve(position)
            .into_iter()
            .map(|id| Action::RemoveTarget {
                position_id: id,
                price: *price,
            })
            .collect(),

        RawSignal::ModifyTarget {
            position,
            old_price,
            new_price,
            ..
        } => resolver
            .resolve(position)
            .into_iter()
            .map(|id| Action::ModifyTarget {
                position_id: id,
                old_price: *old_price,
                new_price: *new_price,
            })
            .collect(),

        RawSignal::AddRule { position, rule, .. } => {
            resolver
                .resolve(position)
                .into_iter()
                .filter_map(|id| {
                    let info = resolver.position_entry_info(&id);
                    let (entry_price, side) = match info {
                        Some((ep, s)) => (Some(ep), s),
                        None => (None, Side::Buy), // fallback side; resolve may return None
                    };
                    rule.resolve(entry_price, side)
                        .map(|resolved_rule| Action::AddRule {
                            position_id: id,
                            rule: resolved_rule,
                        })
                })
                .collect()
        }

        RawSignal::RemoveRule {
            position,
            rule_name,
            ..
        } => resolver
            .resolve(position)
            .into_iter()
            .map(|id| Action::RemoveRule {
                position_id: id,
                rule_name: rule_name.clone(),
            })
            .collect(),

        RawSignal::ScaleIn {
            position,
            price,
            size,
            ..
        } => resolver
            .resolve(position)
            .into_iter()
            .map(|id| Action::ScaleIn {
                position_id: id,
                price: *price,
                size: *size,
                trade_id: None,
            })
            .collect(),

        RawSignal::CancelPending { position, .. } => resolver
            .resolve(position)
            .into_iter()
            .map(|id| Action::CancelPending { position_id: id })
            .collect(),

        // ── Bulk actions — no resolution needed ─────────────────────
        RawSignal::CloseAllOf { symbol, .. } => {
            vec![Action::CloseAllOf {
                symbol: symbol.clone(),
            }]
        }
        RawSignal::CloseAll { .. } => {
            vec![Action::CloseAll]
        }
        RawSignal::CancelAllPending { .. } => {
            vec![Action::CancelAllPending]
        }
        RawSignal::ModifyAllStoploss { symbol, price, .. } => {
            vec![Action::ModifyAllStoploss {
                symbol: symbol.clone(),
                price: *price,
            }]
        }
        RawSignal::CloseAllInGroup { group_id, .. } => {
            vec![Action::CloseAllInGroup {
                group_id: group_id.clone(),
            }]
        }
        RawSignal::ModifyAllStoplossInGroup {
            group_id, price, ..
        } => {
            vec![Action::ModifyAllStoplossInGroup {
                group_id: group_id.clone(),
                price: *price,
            }]
        }
    }
}

// ─── StoplossMode ───────────────────────────────────────────────────────────

/// How the profile handles the stoploss from the raw signal.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum StoplossMode {
    /// Use the stoploss price from the signal as-is.
    FromSignal,
    /// No fixed stoploss (rely on trailing stop or time exit instead).
    None,
    /// Override with a fixed distance from entry price.
    FixedDistance { distance: f64 },
    /// Override with a specific absolute price.
    FixedPrice { price: f64 },
}

// ─── TOML-friendly rule definition ──────────────────────────────────────────

/// Profile-specific rule definition with `#[serde(tag = "type")]` for TOML.
///
/// Converts to the core `RuleConfig` enum. Includes an offset-based
/// `BreakevenWhenOffset` variant that computes the absolute trigger price
/// from the signal's entry price at apply time.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum RuleConfigDef {
    /// Fixed stoploss at an absolute price.
    FixedStoploss { price: f64 },
    /// Trailing stop with a fixed distance.
    TrailingStop { distance: f64 },
    /// Take profit at an absolute price with a close ratio.
    TakeProfit { price: f64, close_ratio: f64 },
    /// Breakeven trigger at an absolute price.
    BreakevenWhen { trigger_price: f64 },
    /// Breakeven trigger as an offset from the entry price (profile-specific).
    BreakevenWhenOffset { trigger_price_offset: f64 },
    /// Breakeven after N targets have been hit.
    BreakevenAfterTargets { after_n: u32 },
    /// Time-based exit after N seconds.
    TimeExit { max_seconds: u64 },
}

impl RuleConfigDef {
    /// Resolve this definition into a core `RuleConfig`.
    ///
    /// For offset-based variants, `entry_price` and `side` are needed
    /// to compute the absolute trigger price. Returns `None` when the
    /// offset variant is used but no entry price is available.
    pub fn resolve(&self, entry_price: Option<f64>, side: Side) -> Option<RuleConfig> {
        match self {
            Self::FixedStoploss { price } => Some(RuleConfig::FixedStoploss { price: *price }),
            Self::TrailingStop { distance } => Some(RuleConfig::TrailingStop {
                distance: *distance,
            }),
            Self::TakeProfit { price, close_ratio } => Some(RuleConfig::TakeProfit {
                price: *price,
                close_ratio: *close_ratio,
            }),
            Self::BreakevenWhen { trigger_price } => Some(RuleConfig::BreakevenWhen {
                trigger_price: *trigger_price,
            }),
            Self::BreakevenWhenOffset {
                trigger_price_offset,
            } => {
                let entry = entry_price?;
                let trigger = match side {
                    Side::Buy => entry + trigger_price_offset,
                    Side::Sell => entry - trigger_price_offset,
                };
                Some(RuleConfig::BreakevenWhen {
                    trigger_price: trigger,
                })
            }
            Self::BreakevenAfterTargets { after_n } => {
                Some(RuleConfig::BreakevenAfterTargets { after_n: *after_n })
            }
            Self::TimeExit { max_seconds } => Some(RuleConfig::TimeExit {
                max_seconds: *max_seconds,
            }),
        }
    }
}

// ─── Strict target resolution ────────────────────────────────────────────────

/// Which 1-based target indices participate in strict target resolution.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TargetSelection {
    /// 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>),
}

/// Metadata describing how signal targets were selected and weighted.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TargetResolution {
    pub selection: TargetSelection,
    /// Resolved 1-based indices in output order.
    pub selected_indices: Vec<usize>,
    /// Close weights corresponding one-to-one with `selected_indices`.
    pub weights: Vec<f64>,
    /// Fraction of the original position not assigned to a target.
    pub remainder: f64,
}

/// A resolved entry that retains risk intent without assigning concrete lots.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResolvedEntry {
    pub risk_multiplier: f64,
    pub symbol: String,
    pub side: Side,
    pub order_type: OrderType,
    pub price: Option<f64>,
    pub stoploss: Option<f64>,
    pub targets: Vec<TargetSpec>,
    pub rules: Vec<RuleConfig>,
    pub group: Option<GroupId>,
    pub trade_id: Option<TradeId>,
    pub target_resolution: TargetResolution,
}

impl ResolvedEntry {
    /// Finalize the resolved entry with a concrete lot size.
    pub fn into_action(self, lot_size: f64) -> Action {
        Action::Open {
            symbol: self.symbol,
            side: self.side,
            order_type: self.order_type,
            price: self.price,
            size: lot_size,
            stoploss: self.stoploss,
            targets: self.targets,
            rules: self.rules,
            group: self.group,
            trade_id: self.trade_id,
        }
    }
}

// ─── ManagementProfile ──────────────────────────────────────────────────────

/// A named management profile that resolves raw entry signals before sizing.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManagementProfile {
    /// Profile name (e.g. "conservative", "aggressive", "runner").
    pub name: String,

    /// Explicit current target selection. When present, this takes precedence
    /// over `use_targets` for [`Self::apply_entry_signal`]. When omitted,
    /// compatibility decoding derives the prior behavior from `use_targets`: an empty vector means
    /// [`TargetSelection::None`], otherwise it means [`TargetSelection::Selected`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target_selection: Option<TargetSelection>,

    /// Compatibility target selection (1-indexed), retained so existing serialized
    /// profiles remain readable.
    pub use_targets: Vec<usize>,

    /// Close ratio for each selected target. In current application, an empty
    /// vector assigns equal weights to all selected targets; otherwise its
    /// length must match the effective target selection.
    pub close_ratios: Vec<f64>,

    /// How to handle the stoploss from the signal.
    #[serde(default = "default_stoploss_mode")]
    pub stoploss_mode: StoplossMode,

    /// Additional rules to attach to every position opened with this profile.
    #[serde(default)]
    pub rules: Vec<RuleConfigDef>,

    /// If set, override the signal's group tag with this value.
    #[serde(default)]
    pub group_override: Option<String>,

    /// When true and ratios sum < 1.0, the remainder rides with just SL/rules.
    #[serde(default)]
    pub let_remainder_run: bool,
}

fn default_stoploss_mode() -> StoplossMode {
    StoplossMode::FromSignal
}

impl ManagementProfile {
    /// Return the target selection used by current application.
    ///
    /// The explicit `target_selection` field wins when present. Otherwise this
    /// preserves existing profile behavior by deriving `None`/`Selected` from
    /// `use_targets`.
    pub fn effective_target_selection(&self) -> TargetSelection {
        self.target_selection.clone().unwrap_or_else(|| {
            if self.use_targets.is_empty() {
                TargetSelection::None
            } else {
                TargetSelection::Selected(self.use_targets.clone())
            }
        })
    }

    /// Validate this profile's configuration.
    pub fn validate(&self) -> Result<(), ProfileValidationError> {
        validate_profile(self)
    }

    /// Transform a `RawSignal::Entry` while retaining target-resolution metadata.
    ///
    /// This canonical path rejects malformed numeric values, target selections,
    /// geometry, and weights. An explicit `target_selection` takes precedence; when it is
    /// omitted, an empty `use_targets` means [`TargetSelection::None`] and non-empty
    /// `use_targets` means [`TargetSelection::Selected`]. When targets are selected and
    /// `close_ratios` is empty, equal `1 / N` weights are synthesized.
    pub fn apply_entry_signal(
        &self,
        signal: &RawSignal,
    ) -> Result<Option<ResolvedEntry>, ProfileApplicationError> {
        let (
            symbol,
            side,
            order_type,
            price,
            risk_multiplier,
            signal_stoploss,
            signal_targets,
            group,
            trade_id,
        ) = match signal {
            RawSignal::Entry {
                symbol,
                side,
                order_type,
                price,
                risk_multiplier,
                stoploss,
                targets,
                group,
                trade_id,
                ..
            } => (
                symbol,
                side,
                order_type,
                price,
                risk_multiplier,
                stoploss,
                targets,
                group,
                trade_id,
            ),
            _ => return Ok(None),
        };

        validate_entry_numbers(*price, *risk_multiplier, *signal_stoploss, signal_targets)?;

        let selection = self.effective_target_selection();
        let (targets, target_resolution) = resolve_targets(
            signal_targets,
            *side,
            *price,
            selection,
            &self.close_ratios,
            self.let_remainder_run,
        )?;
        let stoploss = resolve_stoploss(&self.stoploss_mode, *signal_stoploss, *price, *side)?;
        let rules = resolve_rules(&self.rules, *price, *side)?;

        Ok(Some(ResolvedEntry {
            risk_multiplier: *risk_multiplier,
            symbol: symbol.clone(),
            side: *side,
            order_type: *order_type,
            price: *price,
            stoploss,
            targets,
            rules,
            group: self.group_override.clone().or(group.clone()),
            trade_id: trade_id.clone(),
            target_resolution,
        }))
    }
}

const WEIGHT_TOLERANCE: f64 = 1e-12;
const LOT_ALIGNMENT_TOLERANCE: f64 = 1e-9;

fn require_positive_finite(
    field: impl Into<String>,
    value: f64,
) -> Result<(), ProfileApplicationError> {
    if value.is_finite() && value > 0.0 {
        Ok(())
    } else {
        Err(ProfileApplicationError::InvalidNumericInput {
            field: field.into(),
            value,
        })
    }
}

fn validate_entry_numbers(
    price: Option<f64>,
    risk_multiplier: f64,
    stoploss: Option<f64>,
    targets: &[f64],
) -> Result<(), ProfileApplicationError> {
    require_positive_finite("risk_multiplier", risk_multiplier)?;
    if let Some(price) = price {
        require_positive_finite("price", price)?;
    }
    if let Some(stoploss) = stoploss {
        require_positive_finite("stoploss", stoploss)?;
    }
    for (offset, &target) in targets.iter().enumerate() {
        require_positive_finite(format!("target {}", offset + 1), target)?;
    }
    Ok(())
}

fn weights_sum_to_one(sum: f64) -> bool {
    (sum - 1.0).abs() <= WEIGHT_TOLERANCE
}

fn validate_weights(
    weights: &[f64],
    let_remainder_run: bool,
) -> Result<f64, ProfileApplicationError> {
    for (offset, &weight) in weights.iter().enumerate() {
        if !weight.is_finite() || weight <= 0.0 {
            return Err(ProfileApplicationError::InvalidTargetWeight {
                position: offset + 1,
                weight,
            });
        }
    }

    let sum: f64 = weights.iter().sum();
    if !sum.is_finite() || sum > 1.0 + WEIGHT_TOLERANCE {
        return Err(ProfileApplicationError::TargetWeightSumExceeded { sum });
    }
    if !let_remainder_run && !weights_sum_to_one(sum) {
        return Err(ProfileApplicationError::TargetWeightSumIncomplete { sum });
    }

    Ok(if weights_sum_to_one(sum) {
        0.0
    } else {
        1.0 - sum
    })
}

fn resolve_targets(
    signal_targets: &[f64],
    side: Side,
    entry_price: Option<f64>,
    selection: TargetSelection,
    explicit_weights: &[f64],
    let_remainder_run: bool,
) -> Result<(Vec<TargetSpec>, TargetResolution), ProfileApplicationError> {
    let selected_indices = match &selection {
        TargetSelection::All => (1..=signal_targets.len()).collect(),
        TargetSelection::None => Vec::new(),
        TargetSelection::Selected(indices) => {
            let mut seen = HashSet::with_capacity(indices.len());
            for &index in indices {
                if index == 0 {
                    return Err(ProfileApplicationError::ZeroTargetIndex);
                }
                if !seen.insert(index) {
                    return Err(ProfileApplicationError::DuplicateTargetIndex { index });
                }
                if index > signal_targets.len() {
                    return Err(ProfileApplicationError::MissingTargetIndex {
                        index,
                        available: signal_targets.len(),
                    });
                }
            }
            indices.clone()
        }
    };

    if selected_indices.is_empty() {
        if !explicit_weights.is_empty() {
            return Err(ProfileApplicationError::TargetWeightCountMismatch {
                targets: 0,
                weights: explicit_weights.len(),
            });
        }
        return Ok((
            Vec::new(),
            TargetResolution {
                selection,
                selected_indices,
                weights: Vec::new(),
                remainder: 1.0,
            },
        ));
    }

    let weights = if explicit_weights.is_empty() {
        vec![1.0 / selected_indices.len() as f64; selected_indices.len()]
    } else {
        if explicit_weights.len() != selected_indices.len() {
            return Err(ProfileApplicationError::TargetWeightCountMismatch {
                targets: selected_indices.len(),
                weights: explicit_weights.len(),
            });
        }
        explicit_weights.to_vec()
    };
    let remainder = validate_weights(&weights, let_remainder_run)?;

    let mut targets = Vec::with_capacity(selected_indices.len());
    let mut target_price_keys = HashSet::with_capacity(selected_indices.len());
    for (&index, &weight) in selected_indices.iter().zip(&weights) {
        let target = signal_targets[index - 1];
        let target_key = (target * 1_000_000.0).round() as i64;
        if !target_price_keys.insert(target_key) {
            return Err(ProfileApplicationError::DuplicateTargetPrice { price: target });
        }
        if let Some(entry) = entry_price {
            let valid_geometry = match side {
                Side::Buy => target > entry,
                Side::Sell => target < entry,
            };
            if !valid_geometry {
                return Err(ProfileApplicationError::InvalidTargetGeometry {
                    index,
                    side,
                    entry,
                    target,
                });
            }
        }
        targets.push(TargetSpec {
            price: target,
            close_ratio: weight,
        });
    }

    Ok((
        targets,
        TargetResolution {
            selection,
            selected_indices,
            weights,
            remainder,
        },
    ))
}

fn validate_stop_geometry(
    side: Side,
    entry: f64,
    stoploss: f64,
) -> Result<(), ProfileApplicationError> {
    let valid = match side {
        Side::Buy => stoploss < entry,
        Side::Sell => stoploss > entry,
    };
    if valid {
        Ok(())
    } else {
        Err(ProfileApplicationError::InvalidStopGeometry {
            side,
            entry,
            stoploss,
        })
    }
}

fn validate_target_geometry(
    index: usize,
    side: Side,
    entry: f64,
    target: f64,
) -> Result<(), ProfileApplicationError> {
    let valid = match side {
        Side::Buy => target > entry,
        Side::Sell => target < entry,
    };
    if valid {
        Ok(())
    } else {
        Err(ProfileApplicationError::InvalidTargetGeometry {
            index,
            side,
            entry,
            target,
        })
    }
}

fn resolve_stoploss(
    mode: &StoplossMode,
    signal_stoploss: Option<f64>,
    entry_price: Option<f64>,
    side: Side,
) -> Result<Option<f64>, ProfileApplicationError> {
    let stoploss = match mode {
        StoplossMode::FromSignal => signal_stoploss,
        StoplossMode::None => None,
        StoplossMode::FixedDistance { distance } => {
            require_positive_finite("stoploss fixed distance", *distance)?;
            entry_price.map(|entry| match side {
                Side::Buy => entry - distance,
                Side::Sell => entry + distance,
            })
        }
        StoplossMode::FixedPrice { price } => {
            require_positive_finite("stoploss fixed price", *price)?;
            Some(*price)
        }
    };
    if let Some(stoploss) = stoploss {
        require_positive_finite("resolved stoploss", stoploss)?;
        if let Some(entry) = entry_price {
            validate_stop_geometry(side, entry, stoploss)?;
        }
    }
    Ok(stoploss)
}

fn resolve_rules(
    definitions: &[RuleConfigDef],
    entry_price: Option<f64>,
    side: Side,
) -> Result<Vec<RuleConfig>, ProfileApplicationError> {
    let mut rules = Vec::with_capacity(definitions.len());
    for (offset, definition) in definitions.iter().enumerate() {
        let position = offset + 1;
        match definition {
            RuleConfigDef::FixedStoploss { price } => {
                require_positive_finite(format!("rule {position} fixed stoploss price"), *price)?;
                if let Some(entry) = entry_price {
                    validate_stop_geometry(side, entry, *price)?;
                }
            }
            RuleConfigDef::TrailingStop { distance } => {
                require_positive_finite(format!("rule {position} trailing distance"), *distance)?;
                if let Some(entry) = entry_price {
                    let initial_stop = match side {
                        Side::Buy => entry - distance,
                        Side::Sell => entry + distance,
                    };
                    require_positive_finite(
                        format!("rule {position} initial trailing stop"),
                        initial_stop,
                    )?;
                    validate_stop_geometry(side, entry, initial_stop)?;
                }
            }
            RuleConfigDef::TakeProfit { price, close_ratio } => {
                require_positive_finite(format!("rule {position} take-profit price"), *price)?;
                require_positive_finite(
                    format!("rule {position} take-profit close ratio"),
                    *close_ratio,
                )?;
                if *close_ratio > 1.0 {
                    return Err(ProfileApplicationError::InvalidTargetWeight {
                        position,
                        weight: *close_ratio,
                    });
                }
                if let Some(entry) = entry_price {
                    validate_target_geometry(position, side, entry, *price)?;
                }
            }
            RuleConfigDef::BreakevenWhen { trigger_price } => {
                require_positive_finite(
                    format!("rule {position} breakeven trigger price"),
                    *trigger_price,
                )?;
                if let Some(entry) = entry_price {
                    validate_target_geometry(position, side, entry, *trigger_price)?;
                }
            }
            RuleConfigDef::BreakevenWhenOffset {
                trigger_price_offset,
            } => {
                require_positive_finite(
                    format!("rule {position} breakeven trigger offset"),
                    *trigger_price_offset,
                )?;
            }
            RuleConfigDef::BreakevenAfterTargets { after_n } => {
                if *after_n == 0 {
                    return Err(ProfileApplicationError::InvalidCountInput {
                        field: format!("rule {position} breakeven target count"),
                        value: 0,
                    });
                }
            }
            RuleConfigDef::TimeExit { max_seconds } => {
                if *max_seconds == 0 {
                    return Err(ProfileApplicationError::InvalidCountInput {
                        field: format!("rule {position} maximum seconds"),
                        value: 0,
                    });
                }
            }
        }

        if let Some(rule) = definition.resolve(entry_price, side) {
            if let RuleConfig::BreakevenWhen { trigger_price } = &rule {
                require_positive_finite(
                    format!("rule {position} resolved breakeven trigger"),
                    *trigger_price,
                )?;
                if let Some(entry) = entry_price {
                    validate_target_geometry(position, side, entry, *trigger_price)?;
                }
            }
            rules.push(rule);
        }
    }
    Ok(rules)
}

/// Strictly resolve an entry without a management profile.
///
/// Every signal target is retained and receives an equal `1 / N` close weight.
/// Non-entry signals return `Ok(None)`.
pub fn resolve_unprofiled_entry(
    signal: &RawSignal,
) -> Result<Option<ResolvedEntry>, ProfileApplicationError> {
    let (
        symbol,
        side,
        order_type,
        price,
        risk_multiplier,
        stoploss,
        signal_targets,
        group,
        trade_id,
    ) = match signal {
        RawSignal::Entry {
            symbol,
            side,
            order_type,
            price,
            risk_multiplier,
            stoploss,
            targets,
            group,
            trade_id,
            ..
        } => (
            symbol,
            side,
            order_type,
            price,
            risk_multiplier,
            stoploss,
            targets,
            group,
            trade_id,
        ),
        _ => return Ok(None),
    };

    validate_entry_numbers(*price, *risk_multiplier, *stoploss, signal_targets)?;
    let (targets, target_resolution) = resolve_targets(
        signal_targets,
        *side,
        *price,
        TargetSelection::All,
        &[],
        false,
    )?;

    Ok(Some(ResolvedEntry {
        risk_multiplier: *risk_multiplier,
        symbol: symbol.clone(),
        side: *side,
        order_type: *order_type,
        price: *price,
        stoploss: *stoploss,
        targets,
        rules: Vec::new(),
        group: group.clone(),
        trade_id: trade_id.clone(),
        target_resolution,
    }))
}

/// Allocate target close weights from authoritative integer lot steps.
/// Each non-final target rounds down, while a fully allocated final target receives all remaining steps.
/// A positive runner remainder is intentionally left unallocated, and `weights + remainder` must equal one.
pub fn allocate_target_steps(
    total_steps: u64,
    weights: &[f64],
    remainder: f64,
) -> Result<Vec<u64>, ProfileApplicationError> {
    if total_steps == 0 {
        return Err(ProfileApplicationError::InvalidCountInput {
            field: "total_steps".into(),
            value: total_steps,
        });
    }
    if !remainder.is_finite() || remainder < 0.0 {
        return Err(ProfileApplicationError::InvalidRemainder { remainder });
    }
    if weights.is_empty() {
        if weights_sum_to_one(remainder) {
            return Ok(Vec::new());
        }
        return Err(ProfileApplicationError::TargetWeightRemainderMismatch {
            sum: 0.0,
            remainder,
        });
    }

    let computed_remainder = validate_weights(weights, true)?;
    let weight_sum = 1.0 - computed_remainder;
    if !weights_sum_to_one(weight_sum + remainder) {
        return Err(ProfileApplicationError::TargetWeightRemainderMismatch {
            sum: weight_sum,
            remainder,
        });
    }
    let assign_residue_to_final = weights_sum_to_one(weight_sum);

    let mut allocations = Vec::with_capacity(weights.len());
    let mut allocated = 0_u64;
    for (offset, &weight) in weights.iter().enumerate() {
        let is_final = offset + 1 == weights.len();
        let steps = if is_final && assign_residue_to_final {
            total_steps.saturating_sub(allocated)
        } else {
            ((total_steps as f64) * weight).floor() as u64
        };
        if steps == 0 {
            return Err(ProfileApplicationError::ZeroUnitAllocation {
                position: offset + 1,
            });
        }
        allocated = allocated.saturating_add(steps);
        allocations.push(steps);
    }

    Ok(allocations)
}

/// Convert an aligned floating lot size to steps and delegate to [`allocate_target_steps`].
pub fn allocate_target_units(
    size: f64,
    lot_step: f64,
    weights: &[f64],
    remainder: f64,
) -> Result<Vec<u64>, ProfileApplicationError> {
    require_positive_finite("size", size)?;
    require_positive_finite("lot_step", lot_step)?;

    let raw_units = size / lot_step;
    if !raw_units.is_finite() || raw_units >= u64::MAX as f64 {
        return Err(ProfileApplicationError::LotUnitCountOverflow { size, lot_step });
    }
    let rounded_units = raw_units.round();
    let alignment_tolerance = LOT_ALIGNMENT_TOLERANCE * raw_units.abs().max(1.0);
    if (raw_units - rounded_units).abs() > alignment_tolerance || rounded_units < 1.0 {
        return Err(ProfileApplicationError::SizeNotMultipleOfLotStep { size, lot_step });
    }

    allocate_target_steps(rounded_units as u64, weights, remainder)
}

/// Validate a management profile without performing configuration I/O.
pub fn validate_profile(p: &ManagementProfile) -> Result<(), ProfileValidationError> {
    let selection = p.effective_target_selection();

    // Empty ratios are the strict sentinel for equal target weights.
    // Explicit ratios must correspond one-to-one when the selected target
    // count is profile-known. `All` is signal-dependent and is checked by
    // `apply_entry_signal` once the signal targets are available.
    let selected_count = match &selection {
        TargetSelection::All => None,
        TargetSelection::None => Some(0),
        TargetSelection::Selected(indices) => Some(indices.len()),
    };
    if let Some(targets) = selected_count
        && !p.close_ratios.is_empty()
        && targets != p.close_ratios.len()
    {
        return Err(ProfileValidationError::TargetRatioMismatch {
            profile: p.name.clone(),
            targets,
            ratios: p.close_ratios.len(),
        });
    }

    // Keep both the legacy field and the effective strict selection safe even
    // when an explicit selection takes precedence.
    let mut seen = HashSet::new();
    for &index in &p.use_targets {
        if index == 0 {
            return Err(ProfileValidationError::ZeroTargetIndex {
                profile: p.name.clone(),
            });
        }
        if !seen.insert(index) {
            return Err(ProfileValidationError::DuplicateTargetIndex {
                profile: p.name.clone(),
                index,
            });
        }
    }
    if let TargetSelection::Selected(indices) = &selection {
        seen.clear();
        for &index in indices {
            if index == 0 {
                return Err(ProfileValidationError::ZeroTargetIndex {
                    profile: p.name.clone(),
                });
            }
            if !seen.insert(index) {
                return Err(ProfileValidationError::DuplicateTargetIndex {
                    profile: p.name.clone(),
                    index,
                });
            }
        }
    }

    resolve_stoploss(&p.stoploss_mode, None, None, Side::Buy).map_err(|error| {
        ProfileValidationError::InvalidConfiguration {
            profile: p.name.clone(),
            reason: error.to_string(),
        }
    })?;
    resolve_rules(&p.rules, None, Side::Buy).map_err(|error| {
        ProfileValidationError::InvalidConfiguration {
            profile: p.name.clone(),
            reason: error.to_string(),
        }
    })?;

    if p.close_ratios.is_empty() {
        return Ok(());
    }

    match validate_weights(&p.close_ratios, p.let_remainder_run) {
        Ok(_) => Ok(()),
        Err(ProfileApplicationError::InvalidTargetWeight { .. }) => {
            Err(ProfileValidationError::ZeroRatio {
                profile: p.name.clone(),
            })
        }
        Err(ProfileApplicationError::TargetWeightSumExceeded { sum }) => {
            Err(ProfileValidationError::RatioSumExceeded {
                profile: p.name.clone(),
                sum,
            })
        }
        Err(ProfileApplicationError::TargetWeightSumIncomplete { sum }) => {
            Err(ProfileValidationError::RatioSumIncomplete {
                profile: p.name.clone(),
                sum,
            })
        }
        Err(error) => unreachable!("unexpected profile weight validation error: {error}"),
    }
}