Skip to main content

wickra_core/indicators/
harami.rs

1//! Bullish / Bearish Harami candlestick pattern.
2
3use crate::ohlcv::Candle;
4use crate::traits::Indicator;
5
6/// Harami — a 2-bar reversal pattern. The current candle's body sits entirely
7/// inside the previous candle's body and points in the opposite direction.
8///
9/// ```text
10/// prev_body  = |prev.close − prev.open|
11/// curr_body  = |curr.close − curr.open|
12/// bullish    = prev red & curr green
13///             & curr.open >= prev.close & curr.close <= prev.open
14///             & curr_body < prev_body
15/// bearish    = prev green & curr red
16///             & curr.open <= prev.close & curr.close >= prev.open
17///             & curr_body < prev_body
18/// ```
19///
20/// Output is `+1.0` for a bullish harami (small green inside a prior red),
21/// `−1.0` for a bearish harami (small red inside a prior green), `0.0`
22/// otherwise. The first bar always returns `0.0`. Pattern-shape check only —
23/// no trend filter is applied; combine with a trend indicator for actionable
24/// signals.
25///
26/// # Signed ±1 encoding
27///
28/// This detector already emits the uniform candlestick sign convention shared
29/// across the pattern family — `+1.0` bullish, `−1.0` bearish, `0.0` no
30/// pattern — so it drops straight into a machine-learning feature matrix where
31/// the bullish and bearish variants of the pattern occupy a single dimension.
32///
33/// # Example
34///
35/// ```
36/// use wickra_core::{Candle, Harami, Indicator};
37///
38/// let mut indicator = Harami::new();
39/// indicator.update(Candle::new(12.0, 12.5, 9.5, 10.0, 1.0, 0).unwrap());
40/// let out = indicator
41///     .update(Candle::new(10.5, 11.5, 10.4, 11.0, 1.0, 1).unwrap());
42/// assert_eq!(out, Some(1.0));
43/// ```
44#[derive(Debug, Clone, Default)]
45pub struct Harami {
46    prev: Option<Candle>,
47    has_emitted: bool,
48}
49
50impl Harami {
51    /// Construct a new Harami detector.
52    pub const fn new() -> Self {
53        Self {
54            prev: None,
55            has_emitted: false,
56        }
57    }
58}
59
60impl Indicator for Harami {
61    type Input = Candle;
62    type Output = f64;
63
64    #[inline]
65    fn update(&mut self, candle: Candle) -> Option<f64> {
66        let prev = self.prev;
67        self.prev = Some(candle);
68        let p = prev?;
69        self.has_emitted = true;
70        let prev_body = (p.close - p.open).abs();
71        let curr_body = (candle.close - candle.open).abs();
72        if prev_body <= 0.0 || curr_body <= 0.0 || curr_body >= prev_body {
73            return Some(0.0);
74        }
75        let prev_red = p.close < p.open;
76        let prev_green = p.close > p.open;
77        let curr_green = candle.close > candle.open;
78        let curr_red = candle.close < candle.open;
79        // Bullish: small green strictly inside prior red body (open >= prev.close, close <= prev.open).
80        if prev_red && curr_green && candle.open >= p.close && candle.close <= p.open {
81            Some(1.0)
82        } else if prev_green && curr_red && candle.open <= p.close && candle.close >= p.open {
83            Some(-1.0)
84        } else {
85            Some(0.0)
86        }
87    }
88
89    fn reset(&mut self) {
90        self.prev = None;
91        self.has_emitted = false;
92    }
93
94    #[inline]
95    fn warmup_period(&self) -> usize {
96        2
97    }
98
99    #[inline]
100    fn is_ready(&self) -> bool {
101        self.has_emitted
102    }
103
104    #[inline]
105    fn name(&self) -> &'static str {
106        "Harami"
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113    use crate::traits::BatchExt;
114
115    fn c(open: f64, high: f64, low: f64, close: f64, ts: i64) -> Candle {
116        Candle::new(open, high, low, close, 1.0, ts).unwrap()
117    }
118
119    #[test]
120    fn accessors_and_metadata() {
121        let h = Harami::new();
122        assert_eq!(h.name(), "Harami");
123        assert_eq!(h.warmup_period(), 2);
124        assert!(!h.is_ready());
125    }
126
127    #[test]
128    fn bullish_harami_is_plus_one() {
129        let mut h = Harami::new();
130        // Prior red 12 -> 10 (body 2). Current green 10.5 -> 11 inside.
131        assert_eq!(h.update(c(12.0, 12.5, 9.5, 10.0, 0)), None);
132        assert_eq!(h.update(c(10.5, 11.5, 10.4, 11.0, 1)), Some(1.0));
133    }
134
135    #[test]
136    fn bearish_harami_is_minus_one() {
137        let mut h = Harami::new();
138        // Prior green 10 -> 12 (body 2). Current red 11.5 -> 11 inside.
139        assert_eq!(h.update(c(10.0, 12.5, 9.5, 12.0, 0)), None);
140        assert_eq!(h.update(c(11.5, 11.6, 10.9, 11.0, 1)), Some(-1.0));
141    }
142
143    #[test]
144    fn larger_body_is_not_harami() {
145        let mut h = Harami::new();
146        h.update(c(11.0, 11.2, 9.8, 10.0, 0));
147        // Current body bigger than prior.
148        assert_eq!(h.update(c(9.5, 12.0, 9.5, 11.5, 1)), Some(0.0));
149    }
150
151    #[test]
152    fn same_direction_is_not_harami() {
153        let mut h = Harami::new();
154        h.update(c(10.0, 12.5, 9.5, 12.0, 0));
155        // Smaller candle but also green -> 0.
156        assert_eq!(h.update(c(11.0, 11.6, 10.9, 11.5, 1)), Some(0.0));
157    }
158
159    #[test]
160    fn first_bar_returns_zero() {
161        let mut h = Harami::new();
162        assert_eq!(h.update(c(10.0, 11.0, 9.0, 11.0, 0)), None);
163    }
164
165    #[test]
166    fn batch_equals_streaming() {
167        let candles: Vec<Candle> = (0..40)
168            .map(|i| {
169                let base = 100.0 + i as f64;
170                if i % 2 == 0 {
171                    c(base + 2.0, base + 2.5, base - 0.5, base, i)
172                } else {
173                    c(base + 1.0, base + 1.5, base + 0.7, base + 1.3, i)
174                }
175            })
176            .collect();
177        let mut a = Harami::new();
178        let mut b = Harami::new();
179        assert_eq!(
180            a.batch(&candles),
181            candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
182        );
183    }
184
185    #[test]
186    fn reset_clears_state() {
187        let mut h = Harami::new();
188        h.update(c(12.0, 12.5, 9.5, 10.0, 0));
189        h.update(c(10.5, 11.5, 10.4, 11.0, 1));
190        assert!(h.is_ready());
191        h.reset();
192        assert!(!h.is_ready());
193        // After reset the next bar again has no prev.
194        assert_eq!(h.update(c(12.0, 12.5, 9.5, 10.0, 0)), None);
195    }
196}