quant-system-core 0.3.2

Core trading domain - engine, raw signals, 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
//! Composable position management rules.
//!
//! Each [`Rule`] variant carries both its configuration **and** its mutable
//! runtime state (e.g. whether it has already triggered).  Rules are evaluated
//! on every price tick for open positions and produce [`Effect`]s that the
//! engine applies.

use serde::{Deserialize, Serialize};

use crate::types::{
    CloseReason, Effect, FillModel, PositionStatus, PriceQuote, RuleConfig, Side,
    position_size_tolerance,
};

// ─── PositionData view (passed to rules for evaluation) ─────────────────────

/// Read-only snapshot of the position fields that rules need for evaluation.
///
/// This is a subset of `Position` that avoids borrow-checker conflicts when
/// rules (stored inside `Position`) need to inspect the position's data.
pub struct PositionView<'a> {
    pub id: &'a str,
    pub symbol: &'a str,
    pub side: Side,
    pub status: PositionStatus,
    pub average_entry: f64,
    pub remaining_ratio: f64,
    pub target_hits: u32,
    pub open_ts: Option<chrono::NaiveDateTime>,
}

// ─── Rule enum ──────────────────────────────────────────────────────────────

/// A composable management rule that is evaluated on every price update.
///
/// Rules are stored per-position and carry their own mutable state so that
/// trigger-once semantics (e.g. breakeven) work correctly.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Rule {
    /// Close the full remaining position when price crosses the stoploss level.
    FixedStoploss { price: f64 },

    /// Stoploss that follows the price at a fixed `distance`.
    ///
    /// For a **Buy** position the stop trails below the highest bid seen;
    /// for a **Sell** position it trails above the lowest ask seen.
    TrailingStop {
        distance: f64,
        #[serde(default)]
        peak_price: f64,
        #[serde(default)]
        initialized: bool,
    },

    /// Close `close_ratio` of the position when price reaches `price`.
    /// Fires at most once.
    TakeProfit {
        price: f64,
        close_ratio: f64,
        #[serde(default)]
        triggered: bool,
    },

    /// When price reaches `trigger_price`, move the stoploss to the entry
    /// price (breakeven).  Fires at most once.
    BreakevenWhen {
        trigger_price: f64,
        #[serde(default)]
        triggered: bool,
    },

    /// After `after_n` take-profit hits, move the stoploss to entry.
    /// Fires at most once.
    BreakevenAfterTargets {
        after_n: u32,
        #[serde(default)]
        triggered: bool,
    },

    /// Close the position if it has been open longer than `max_seconds`.
    TimeExit { max_seconds: u64 },
}

// ─── Constructors ───────────────────────────────────────────────────────────

impl Rule {
    pub fn fixed_stoploss(price: f64) -> Self {
        Rule::FixedStoploss { price }
    }

    pub fn trailing_stop(distance: f64) -> Self {
        Rule::TrailingStop {
            distance,
            peak_price: 0.0,
            initialized: false,
        }
    }

    pub fn take_profit(price: f64, close_ratio: f64) -> Self {
        Rule::TakeProfit {
            price,
            close_ratio,
            triggered: false,
        }
    }

    pub fn breakeven_when(trigger_price: f64) -> Self {
        Rule::BreakevenWhen {
            trigger_price,
            triggered: false,
        }
    }

    pub fn breakeven_after_targets(after_n: u32) -> Self {
        Rule::BreakevenAfterTargets {
            after_n,
            triggered: false,
        }
    }

    pub fn time_exit(max_seconds: u64) -> Self {
        Rule::TimeExit { max_seconds }
    }

    /// Build a live `Rule` from a declarative [`RuleConfig`].
    pub fn from_config(config: RuleConfig) -> Self {
        match config {
            RuleConfig::FixedStoploss { price } => Self::fixed_stoploss(price),
            RuleConfig::TrailingStop { distance } => Self::trailing_stop(distance),
            RuleConfig::TakeProfit { price, close_ratio } => Self::take_profit(price, close_ratio),
            RuleConfig::BreakevenWhen { trigger_price } => Self::breakeven_when(trigger_price),
            RuleConfig::BreakevenAfterTargets { after_n } => Self::breakeven_after_targets(after_n),
            RuleConfig::TimeExit { max_seconds } => Self::time_exit(max_seconds),
        }
    }
}

// ─── Evaluation ─────────────────────────────────────────────────────────────

impl Rule {
    /// Whether this rule requires tick-by-tick evaluation (not indexable as a static alert).
    pub fn is_stateful(&self) -> bool {
        matches!(
            self,
            Rule::TrailingStop { .. } | Rule::TimeExit { .. } | Rule::BreakevenAfterTargets { .. }
        )
    }

    /// Human-readable name used for logging, record keeping, and `RemoveRule`.
    pub fn name(&self) -> &'static str {
        match self {
            Rule::FixedStoploss { .. } => "FixedStoploss",
            Rule::TrailingStop { .. } => "TrailingStop",
            Rule::TakeProfit { .. } => "TakeProfit",
            Rule::BreakevenWhen { .. } => "BreakevenWhen",
            Rule::BreakevenAfterTargets { .. } => "BreakevenAfterTargets",
            Rule::TimeExit { .. } => "TimeExit",
        }
    }

    /// Evaluate the rule against the current quote and position state.
    ///
    /// Returns zero or more [`Effect`]s.  The engine is responsible for
    /// applying these effects to the position afterwards.
    pub fn evaluate(
        &mut self,
        data: &PositionView<'_>,
        quote: &PriceQuote,
        model: FillModel,
    ) -> Vec<Effect> {
        // Only evaluate for open positions.
        if data.status != PositionStatus::Open {
            return vec![];
        }

        match self {
            // ── Fixed stoploss ──────────────────────────────────────────
            Rule::FixedStoploss { price } => {
                let check = quote.eval_price(data.side, model);
                let hit = match data.side {
                    Side::Buy => check <= *price,
                    Side::Sell => check >= *price,
                };
                if hit {
                    vec![Effect::PositionClosed {
                        id: data.id.to_owned(),
                        reason: CloseReason::Stoploss,
                    }]
                } else {
                    vec![]
                }
            }

            // ── Trailing stop ───────────────────────────────────────────
            Rule::TrailingStop {
                distance,
                peak_price,
                initialized,
            } => {
                if !*initialized {
                    *peak_price = data.average_entry;
                    *initialized = true;
                }

                let check = quote.eval_price(data.side, model);

                match data.side {
                    Side::Buy => {
                        if check > *peak_price {
                            *peak_price = check;
                        }
                        let trailing_sl = *peak_price - *distance;
                        if check <= trailing_sl {
                            vec![Effect::PositionClosed {
                                id: data.id.to_owned(),
                                reason: CloseReason::TrailingStop,
                            }]
                        } else {
                            vec![]
                        }
                    }
                    Side::Sell => {
                        if check < *peak_price {
                            *peak_price = check;
                        }
                        let trailing_sl = *peak_price + *distance;
                        if check >= trailing_sl {
                            vec![Effect::PositionClosed {
                                id: data.id.to_owned(),
                                reason: CloseReason::TrailingStop,
                            }]
                        } else {
                            vec![]
                        }
                    }
                }
            }

            // ── Take profit ─────────────────────────────────────────────
            Rule::TakeProfit {
                price,
                close_ratio,
                triggered,
            } => {
                if *triggered {
                    return vec![];
                }
                if data.remaining_ratio <= 0.0 {
                    return vec![];
                }

                let check = quote.eval_price(data.side, model);
                let hit = match data.side {
                    Side::Buy => check >= *price,
                    Side::Sell => check <= *price,
                };

                if hit {
                    *triggered = true;
                    let actual_ratio = close_ratio.min(data.remaining_ratio);

                    // If this closes the remaining position, emit CloseFull.
                    if data.remaining_ratio - actual_ratio <= position_size_tolerance(1.0) {
                        vec![Effect::PositionClosed {
                            id: data.id.to_owned(),
                            reason: CloseReason::Target,
                        }]
                    } else {
                        vec![Effect::PartialClose {
                            id: data.id.to_owned(),
                            ratio: actual_ratio,
                            reason: CloseReason::Target,
                        }]
                    }
                } else {
                    vec![]
                }
            }

            // ── Breakeven when price reached ────────────────────────────
            Rule::BreakevenWhen {
                trigger_price,
                triggered,
            } => {
                if *triggered {
                    return vec![];
                }

                let check = quote.eval_price(data.side, model);
                let hit = match data.side {
                    Side::Buy => check >= *trigger_price,
                    Side::Sell => check <= *trigger_price,
                };

                if hit {
                    *triggered = true;
                    vec![Effect::StoplossModified {
                        id: data.id.to_owned(),
                        old_price: 0.0, // filled in by engine
                        new_price: data.average_entry,
                    }]
                } else {
                    vec![]
                }
            }

            // ── Breakeven after N target hits ───────────────────────────
            Rule::BreakevenAfterTargets { after_n, triggered } => {
                if *triggered {
                    return vec![];
                }

                if data.target_hits >= *after_n {
                    *triggered = true;
                    vec![Effect::StoplossModified {
                        id: data.id.to_owned(),
                        old_price: 0.0, // filled in by engine
                        new_price: data.average_entry,
                    }]
                } else {
                    vec![]
                }
            }

            // ── Time-based exit ─────────────────────────────────────────
            Rule::TimeExit { max_seconds } => {
                if let Some(open_ts) = data.open_ts {
                    let elapsed = (quote.ts - open_ts).num_seconds();
                    if elapsed >= *max_seconds as i64 {
                        vec![Effect::PositionClosed {
                            id: data.id.to_owned(),
                            reason: CloseReason::TimeExit,
                        }]
                    } else {
                        vec![]
                    }
                } else {
                    vec![]
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::NaiveDate;

    fn ts(h: u32, m: u32, s: u32) -> chrono::NaiveDateTime {
        NaiveDate::from_ymd_opt(2026, 1, 1)
            .unwrap()
            .and_hms_opt(h, m, s)
            .unwrap()
    }

    fn quote(bid: f64, ask: f64) -> PriceQuote {
        PriceQuote {
            symbol: "EURUSD".into(),
            ts: ts(12, 0, 0),
            bid,
            ask,
        }
    }

    fn view_buy(id: &str, entry: f64) -> PositionView<'_> {
        PositionView {
            id,
            symbol: "EURUSD",
            side: Side::Buy,
            status: PositionStatus::Open,
            average_entry: entry,
            remaining_ratio: 1.0,
            target_hits: 0,
            open_ts: Some(ts(10, 0, 0)),
        }
    }

    fn view_sell(id: &str, entry: f64) -> PositionView<'_> {
        PositionView {
            id,
            symbol: "EURUSD",
            side: Side::Sell,
            status: PositionStatus::Open,
            average_entry: entry,
            remaining_ratio: 1.0,
            target_hits: 0,
            open_ts: Some(ts(10, 0, 0)),
        }
    }

    #[test]
    fn fixed_stoploss_buy_triggers() {
        let mut rule = Rule::fixed_stoploss(1.0800);
        let v = view_buy("p1", 1.0850);
        // bid at SL → triggers
        let effects = rule.evaluate(&v, &quote(1.0800, 1.0802), FillModel::BidAsk);
        assert_eq!(effects.len(), 1);
        assert!(matches!(
            &effects[0],
            Effect::PositionClosed {
                reason: CloseReason::Stoploss,
                ..
            }
        ));
    }

    #[test]
    fn fixed_stoploss_buy_no_trigger() {
        let mut rule = Rule::fixed_stoploss(1.0800);
        let v = view_buy("p1", 1.0850);
        let effects = rule.evaluate(&v, &quote(1.0810, 1.0812), FillModel::BidAsk);
        assert!(effects.is_empty());
    }

    #[test]
    fn fixed_stoploss_sell_triggers() {
        let mut rule = Rule::fixed_stoploss(1.0900);
        let v = view_sell("p1", 1.0850);
        // ask at SL → triggers
        let effects = rule.evaluate(&v, &quote(1.0898, 1.0900), FillModel::BidAsk);
        assert_eq!(effects.len(), 1);
        assert!(matches!(
            &effects[0],
            Effect::PositionClosed {
                reason: CloseReason::Stoploss,
                ..
            }
        ));
    }

    #[test]
    fn trailing_stop_buy() {
        let mut rule = Rule::trailing_stop(0.0020);
        let v = view_buy("p1", 1.0850);

        // Price rises → no trigger
        let effects = rule.evaluate(&v, &quote(1.0870, 1.0872), FillModel::BidAsk);
        assert!(effects.is_empty());

        // Price rises more → no trigger, peak updates
        let effects = rule.evaluate(&v, &quote(1.0900, 1.0902), FillModel::BidAsk);
        assert!(effects.is_empty());

        // Price drops within distance → no trigger (0.0900 - 0.0020 = 0.0880)
        let effects = rule.evaluate(&v, &quote(1.0882, 1.0884), FillModel::BidAsk);
        assert!(effects.is_empty());

        // Price drops beyond distance → triggers
        let effects = rule.evaluate(&v, &quote(1.0879, 1.0881), FillModel::BidAsk);
        assert_eq!(effects.len(), 1);
        assert!(matches!(
            &effects[0],
            Effect::PositionClosed {
                reason: CloseReason::TrailingStop,
                ..
            }
        ));
    }

    #[test]
    fn take_profit_partial() {
        let mut rule = Rule::take_profit(1.0900, 0.5);
        let v = view_buy("p1", 1.0850);

        // Not reached
        let effects = rule.evaluate(&v, &quote(1.0890, 1.0892), FillModel::BidAsk);
        assert!(effects.is_empty());

        // Reached → partial close
        let effects = rule.evaluate(&v, &quote(1.0900, 1.0902), FillModel::BidAsk);
        assert_eq!(effects.len(), 1);
        assert!(
            matches!(&effects[0], Effect::PartialClose { ratio, .. } if (*ratio - 0.5).abs() < f64::EPSILON)
        );

        // Second call → already triggered
        let effects = rule.evaluate(&v, &quote(1.0910, 1.0912), FillModel::BidAsk);
        assert!(effects.is_empty());
    }

    #[test]
    fn take_profit_closes_remaining() {
        let mut rule = Rule::take_profit(1.0900, 1.0);
        let v = view_buy("p1", 1.0850);

        let effects = rule.evaluate(&v, &quote(1.0900, 1.0902), FillModel::BidAsk);
        assert_eq!(effects.len(), 1);
        assert!(matches!(
            &effects[0],
            Effect::PositionClosed {
                reason: CloseReason::Target,
                ..
            }
        ));
    }

    #[test]
    fn breakeven_when_triggers() {
        let mut rule = Rule::breakeven_when(1.0900);
        let v = view_buy("p1", 1.0850);

        // Not reached
        let effects = rule.evaluate(&v, &quote(1.0890, 1.0892), FillModel::BidAsk);
        assert!(effects.is_empty());

        // Reached
        let effects = rule.evaluate(&v, &quote(1.0900, 1.0902), FillModel::BidAsk);
        assert_eq!(effects.len(), 1);
        assert!(
            matches!(&effects[0], Effect::StoplossModified { new_price, .. } if (*new_price - 1.0850).abs() < f64::EPSILON)
        );

        // Already triggered
        let effects = rule.evaluate(&v, &quote(1.0910, 1.0912), FillModel::BidAsk);
        assert!(effects.is_empty());
    }

    #[test]
    fn breakeven_after_targets() {
        let mut rule = Rule::breakeven_after_targets(2);

        // Not enough target hits
        let mut v = view_buy("p1", 1.0850);
        v.target_hits = 1;
        let effects = rule.evaluate(&v, &quote(1.0900, 1.0902), FillModel::BidAsk);
        assert!(effects.is_empty());

        // Enough target hits
        v.target_hits = 2;
        let effects = rule.evaluate(&v, &quote(1.0900, 1.0902), FillModel::BidAsk);
        assert_eq!(effects.len(), 1);
        assert!(matches!(&effects[0], Effect::StoplossModified { .. }));

        // Already triggered
        v.target_hits = 3;
        let effects = rule.evaluate(&v, &quote(1.0900, 1.0902), FillModel::BidAsk);
        assert!(effects.is_empty());
    }

    #[test]
    fn time_exit_triggers() {
        let mut rule = Rule::time_exit(3600); // 1 hour
        let v = view_buy("p1", 1.0850); // open_ts = 10:00:00

        // 30 minutes later → no trigger
        let mut q = quote(1.0860, 1.0862);
        q.ts = ts(10, 30, 0);
        let effects = rule.evaluate(&v, &q, FillModel::BidAsk);
        assert!(effects.is_empty());

        // 1 hour later → triggers
        q.ts = ts(11, 0, 0);
        let effects = rule.evaluate(&v, &q, FillModel::BidAsk);
        assert_eq!(effects.len(), 1);
        assert!(matches!(
            &effects[0],
            Effect::PositionClosed {
                reason: CloseReason::TimeExit,
                ..
            }
        ));
    }

    #[test]
    fn rule_skips_closed_position() {
        let mut rule = Rule::fixed_stoploss(1.0800);
        let mut v = view_buy("p1", 1.0850);
        v.status = PositionStatus::Closed;

        let effects = rule.evaluate(&v, &quote(1.0790, 1.0792), FillModel::BidAsk);
        assert!(effects.is_empty());
    }

    #[test]
    fn from_config_roundtrip() {
        let configs = vec![
            RuleConfig::FixedStoploss { price: 1.08 },
            RuleConfig::TrailingStop { distance: 0.002 },
            RuleConfig::TakeProfit {
                price: 1.09,
                close_ratio: 0.5,
            },
            RuleConfig::BreakevenWhen {
                trigger_price: 1.09,
            },
            RuleConfig::BreakevenAfterTargets { after_n: 2 },
            RuleConfig::TimeExit { max_seconds: 3600 },
        ];
        let names: Vec<&str> = configs
            .into_iter()
            .map(|c| Rule::from_config(c).name())
            .collect();
        assert_eq!(
            names,
            vec![
                "FixedStoploss",
                "TrailingStop",
                "TakeProfit",
                "BreakevenWhen",
                "BreakevenAfterTargets",
                "TimeExit",
            ]
        );
    }
}