Skip to main content

wickra_core/indicators/
three_drives.rs

1//! Three Drives harmonic pattern.
2
3use crate::indicators::pattern_swing::{
4    approx_equal, ratios_in, xabcd, SwingTracker, SWING_THRESHOLD,
5};
6use crate::ohlcv::Candle;
7use crate::traits::Indicator;
8
9/// Three Drives — a symmetric harmonic pattern of two visible drives separated
10/// by two retracements, read from the last five pivots `X-A-B-C-D` (the two
11/// drive legs are `A→B` and `C→D`):
12///
13/// ```text
14/// AB / XA ∈ [1.13, 1.75]   (drive 1 extends the prior retracement)
15/// CD / BC ∈ [1.13, 1.75]   (drive 2 extends symmetrically)
16/// AB ≈ CD (within 20%)      (the two drives are similar in size)
17/// XA ≈ BC (within 30%)      (the two retracements are similar)
18/// ```
19///
20/// Output is `+1.0` (bullish, terminal D a swing low — drives down), `-1.0`
21/// (bearish, drives up), or `0.0`; never `None`. See
22/// `crates/wickra-core/src/indicators/three_drives.rs`.
23#[derive(Debug, Clone)]
24pub struct ThreeDrives {
25    swing: SwingTracker,
26    has_emitted: bool,
27}
28
29impl ThreeDrives {
30    /// Construct a new Three Drives detector.
31    pub const fn new() -> Self {
32        Self {
33            swing: SwingTracker::new(SWING_THRESHOLD, 5),
34            has_emitted: false,
35        }
36    }
37}
38
39impl Default for ThreeDrives {
40    fn default() -> Self {
41        Self::new()
42    }
43}
44
45impl Indicator for ThreeDrives {
46    type Input = Candle;
47    type Output = f64;
48
49    #[inline]
50    fn update(&mut self, candle: Candle) -> Option<f64> {
51        let advanced = self.swing.update(candle);
52        let pivots = self.swing.pivots();
53        // Too few pivots to form the shape at all: the indicator cannot
54        // judge yet, which is what `None` means.
55        if pivots.len() < 5 {
56            return None;
57        }
58        self.has_emitted = true;
59        // Armed, but this bar did not close a new pivot, so there is
60        // nothing new to match against.
61        if !advanced {
62            return Some(0.0);
63        }
64        let p = xabcd(pivots);
65        let xa = (p.a - p.x).abs();
66        let ab = (p.b - p.a).abs();
67        let bc = (p.c - p.b).abs();
68        let cd = (p.d - p.c).abs();
69        let extensions = ratios_in(&[(ab / xa, 1.13, 1.75), (cd / bc, 1.13, 1.75)]);
70        let symmetric = approx_equal(ab, cd, 0.20) && approx_equal(xa, bc, 0.30);
71        if extensions && symmetric {
72            return Some(if p.bullish { 1.0 } else { -1.0 });
73        }
74        Some(0.0)
75    }
76
77    fn reset(&mut self) {
78        self.swing.reset();
79        self.has_emitted = false;
80    }
81
82    #[inline]
83    fn warmup_period(&self) -> usize {
84        6
85    }
86
87    #[inline]
88    fn is_ready(&self) -> bool {
89        self.has_emitted
90    }
91
92    #[inline]
93    fn name(&self) -> &'static str {
94        "ThreeDrives"
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use crate::indicators::pattern_swing::candles_for_pivots;
102    use crate::traits::BatchExt;
103
104    fn run(pivots: &[f64]) -> Vec<f64> {
105        let mut indicator = ThreeDrives::new();
106        candles_for_pivots(pivots)
107            .into_iter()
108            .filter_map(|c| indicator.update(c))
109            .collect()
110    }
111
112    #[test]
113    fn accessors_and_metadata() {
114        let indicator = ThreeDrives::new();
115        assert_eq!(indicator.name(), "ThreeDrives");
116        assert_eq!(indicator.warmup_period(), 6);
117        assert!(!indicator.is_ready());
118        assert!(!ThreeDrives::default().is_ready());
119    }
120
121    #[test]
122    fn bearish_three_drives_is_minus_one() {
123        // Three rising drives (120, 128, 136) → bearish exhaustion.
124        let out = run(&[120.0, 100.0, 128.0, 108.0, 136.0]);
125        assert_eq!(*out.last().unwrap(), -1.0);
126        assert!(out[..out.len() - 1].iter().all(|&x| x == 0.0));
127    }
128
129    #[test]
130    fn bullish_three_drives_is_plus_one() {
131        // Three falling drives → bullish exhaustion.
132        let out = run(&[150.0, 120.0, 140.0, 112.0, 132.0, 104.0]);
133        assert_eq!(*out.last().unwrap(), 1.0);
134    }
135
136    #[test]
137    fn asymmetric_drives_do_not_trigger() {
138        let out = run(&[150.0, 100.0, 140.0, 110.0, 135.0, 105.0]);
139        assert_eq!(*out.last().unwrap(), 0.0);
140    }
141
142    #[test]
143    fn reset_clears_state() {
144        let mut indicator = ThreeDrives::new();
145        for c in candles_for_pivots(&[120.0, 100.0, 128.0]) {
146            let _ = indicator.update(c);
147        }
148        indicator.reset();
149        assert!(!indicator.is_ready());
150        let c = Candle::new(99.5, 100.0, 99.5, 99.5, 1.0, 0).unwrap();
151        assert_eq!(indicator.update(c), None);
152    }
153
154    #[test]
155    fn batch_equals_streaming() {
156        let candles = candles_for_pivots(&[120.0, 100.0, 128.0, 108.0, 136.0]);
157        let mut a = ThreeDrives::new();
158        let mut b = ThreeDrives::new();
159        assert_eq!(
160            a.batch(&candles),
161            candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
162        );
163    }
164}