Skip to main content

wickra_core/indicators/
three_drives.rs

1//! Three Drives harmonic pattern.
2
3use crate::indicators::pattern_swing::{
4    approx_equal, drive_legs, ratios_in, SwingTracker, SWING_THRESHOLD,
5};
6use crate::ohlcv::Candle;
7use crate::traits::Indicator;
8
9/// Three Drives — a symmetric harmonic pattern of three drives separated by two
10/// retracements, read from the last seven pivots. Each drive extends the
11/// retracement that precedes it, so the seven pivots span six alternating legs
12/// `R1 D1 R2 D2 R3 D3`:
13///
14/// ```text
15/// D1 / R1 ∈ [1.13, 1.75]        (each drive extends the leg before it)
16/// D2 / R2 ∈ [1.13, 1.75]
17/// D3 / R3 ∈ [1.13, 1.75]
18/// D1 ≈ D2 ≈ D3 (within 20%)     (the three drives are similar in size)
19/// R1 ≈ R2 ≈ R3 (within 30%)     (the retracements between them are similar)
20/// ```
21///
22/// The third drive is what separates this from a plain two-push extension: a
23/// structure that stops after two drives is not a match, it is an incomplete
24/// pattern the detector keeps waiting on.
25///
26/// Output is `+1.0` (bullish, terminal D a swing low — drives down), `-1.0`
27/// (bearish, drives up), or `0.0`; never `None`. See
28/// `crates/wickra-core/src/indicators/three_drives.rs`.
29#[derive(Debug, Clone)]
30pub struct ThreeDrives {
31    swing: SwingTracker,
32    has_emitted: bool,
33}
34
35impl ThreeDrives {
36    /// Construct a new Three Drives detector.
37    pub const fn new() -> Self {
38        Self {
39            swing: SwingTracker::new(SWING_THRESHOLD, 7),
40            has_emitted: false,
41        }
42    }
43}
44
45impl Default for ThreeDrives {
46    fn default() -> Self {
47        Self::new()
48    }
49}
50
51impl Indicator for ThreeDrives {
52    type Input = Candle;
53    type Output = f64;
54
55    #[inline]
56    fn update(&mut self, candle: Candle) -> Option<f64> {
57        let advanced = self.swing.update(candle);
58        let pivots = self.swing.pivots();
59        // Too few pivots to form the shape at all: the indicator cannot
60        // judge yet, which is what `None` means.
61        if pivots.len() < 7 {
62            return None;
63        }
64        self.has_emitted = true;
65        // Armed, but this bar did not close a new pivot, so there is
66        // nothing new to match against.
67        if !advanced {
68            return Some(0.0);
69        }
70        let p = drive_legs(pivots);
71        let [retr1, drive1, retr2, drive2, retr3, drive3] = p.legs;
72        let extensions = ratios_in(&[
73            (drive1 / retr1, 1.13, 1.75),
74            (drive2 / retr2, 1.13, 1.75),
75            (drive3 / retr3, 1.13, 1.75),
76        ]);
77        let drives_match = approx_equal(drive1, drive2, 0.20) && approx_equal(drive2, drive3, 0.20);
78        let retracements_match =
79            approx_equal(retr1, retr2, 0.30) && approx_equal(retr2, retr3, 0.30);
80        if extensions && drives_match && retracements_match {
81            return Some(if p.bullish { 1.0 } else { -1.0 });
82        }
83        Some(0.0)
84    }
85
86    fn reset(&mut self) {
87        self.swing.reset();
88        self.has_emitted = false;
89    }
90
91    #[inline]
92    fn warmup_period(&self) -> usize {
93        8
94    }
95
96    #[inline]
97    fn is_ready(&self) -> bool {
98        self.has_emitted
99    }
100
101    #[inline]
102    fn name(&self) -> &'static str {
103        "ThreeDrives"
104    }
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110    use crate::indicators::pattern_swing::candles_for_pivots;
111    use crate::traits::BatchExt;
112
113    fn run(pivots: &[f64]) -> Vec<f64> {
114        let mut indicator = ThreeDrives::new();
115        candles_for_pivots(pivots)
116            .into_iter()
117            .filter_map(|c| indicator.update(c))
118            .collect()
119    }
120
121    #[test]
122    fn accessors_and_metadata() {
123        let indicator = ThreeDrives::new();
124        assert_eq!(indicator.name(), "ThreeDrives");
125        assert_eq!(indicator.warmup_period(), 8);
126        assert!(!indicator.is_ready());
127        assert!(!ThreeDrives::default().is_ready());
128    }
129
130    #[test]
131    fn bearish_three_drives_is_minus_one() {
132        // Seven pivots, three rising drives (124, 128, 132) each extending a
133        // 10-point retracement by 14: every D/R is 1.4 and both symmetry bands
134        // hold exactly.
135        let out = run(&[120.0, 110.0, 124.0, 114.0, 128.0, 118.0, 132.0]);
136        assert_eq!(*out.last().unwrap(), -1.0);
137        assert!(out[..out.len() - 1].iter().all(|&x| x == 0.0));
138    }
139
140    #[test]
141    fn two_drives_alone_do_not_complete_the_pattern() {
142        // The five-pivot shape holds only two drive legs. A third drive is what
143        // the pattern is named for, so the detector must still be waiting.
144        let out = run(&[120.0, 100.0, 128.0, 108.0, 136.0]);
145        assert!(out.is_empty());
146    }
147
148    #[test]
149    fn bullish_three_drives_is_plus_one() {
150        // Mirror image: three falling drives (114, 110, 106) off 10-point
151        // upward retracements. The leading pivot only seeds the alternation;
152        // the detector reads the last seven.
153        let out = run(&[132.0, 118.0, 128.0, 114.0, 124.0, 110.0, 120.0, 106.0]);
154        assert_eq!(*out.last().unwrap(), 1.0);
155    }
156
157    #[test]
158    fn asymmetric_drives_do_not_trigger() {
159        // Every D/R stays inside [1.13, 1.75] and the retracements stay within
160        // 30% of each other, but the third drive is 20 against the first two at
161        // 14 — outside the 20% band, so the shape is rejected on symmetry alone.
162        let out = run(&[120.0, 110.0, 124.0, 114.0, 128.0, 114.0, 134.0]);
163        assert_eq!(*out.last().unwrap(), 0.0);
164    }
165
166    #[test]
167    fn reset_clears_state() {
168        let mut indicator = ThreeDrives::new();
169        for c in candles_for_pivots(&[120.0, 100.0, 128.0]) {
170            let _ = indicator.update(c);
171        }
172        indicator.reset();
173        assert!(!indicator.is_ready());
174        let c = Candle::new(99.5, 100.0, 99.5, 99.5, 1.0, 0).unwrap();
175        assert_eq!(indicator.update(c), None);
176    }
177
178    #[test]
179    fn batch_equals_streaming() {
180        let candles = candles_for_pivots(&[120.0, 110.0, 124.0, 114.0, 128.0, 118.0, 132.0]);
181        let mut a = ThreeDrives::new();
182        let mut b = ThreeDrives::new();
183        assert_eq!(
184            a.batch(&candles),
185            candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
186        );
187    }
188}