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
//! RegimeGate primitive — fires when a regime indicator transitions above/below a threshold.
//!
//! Maps to `OperatorClass::RegimeGate`.
use crate::core::signal::direction::Direction;
use crate::core::signal::kind::{CompositeSub, SignalKind};
/// Which side of the threshold constitutes "in regime".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GateDirection {
/// Regime is active when `regime_value > threshold`.
Above,
/// Regime is active when `regime_value < threshold`.
Below,
}
/// Detects entry/exit into a market regime defined by a threshold.
#[derive(Debug, Clone)]
pub struct RegimeGate {
regime_threshold: f64,
direction: GateDirection,
in_regime: bool,
initialized: bool,
}
impl RegimeGate {
pub fn new(regime_threshold: f64, direction: GateDirection) -> Self {
Self {
regime_threshold,
direction,
in_regime: false,
initialized: false,
}
}
/// Detect regime gate transitions from a pre-computed regime value (slice-based hot loop).
///
/// Returns `Some((SignalKind::Composite(CompositeSub::Confirmed), Direction::Up))`
/// on regime entry, `Direction::Down` on regime exit.
pub fn detect_from_values(&mut self, regime_value: f64) -> Option<(SignalKind, Direction)> {
let now_in = match self.direction {
GateDirection::Above => regime_value > self.regime_threshold,
GateDirection::Below => regime_value < self.regime_threshold,
};
if !self.initialized {
self.in_regime = now_in;
self.initialized = true;
return None;
}
let prev = self.in_regime;
self.in_regime = now_in;
if !prev && now_in {
Some((SignalKind::Composite(CompositeSub::Confirmed), Direction::Up))
} else if prev && !now_in {
Some((SignalKind::Composite(CompositeSub::Confirmed), Direction::Down))
} else {
None
}
}
/// Whether the detector is currently inside a regime.
pub fn in_regime(&self) -> bool {
self.in_regime
}
/// Reset state.
pub fn reset(&mut self) {
self.in_regime = false;
self.initialized = false;
}
}