Skip to main content

wickra_core/indicators/
two_crows.rs

1//! Two Crows candlestick pattern.
2
3use crate::ohlcv::Candle;
4use crate::traits::Indicator;
5
6/// Two Crows — a 3-bar bearish reversal pattern that appears after an advance.
7///
8/// ```text
9/// bar1 green (long white)
10/// bar2 red   & its body gaps up above bar1's body  (bar2.close > bar1.close)
11/// bar3 red   & opens inside bar2's body            (bar2.close < bar3.open < bar2.open)
12///            & closes inside bar1's body            (bar1.open  < bar3.close < bar1.close)
13/// ```
14///
15/// Output is `−1.0` when the pattern completes and `0.0` otherwise. Two Crows is
16/// a single-direction (bearish-only) pattern, so it never emits `+1.0`. The
17/// first two bars always return `0.0` because the three-bar window is not yet
18/// filled. Pattern-shape check only — no trend filter is applied; combine with a
19/// trend indicator for actionable signals.
20///
21/// # Signed ±1 encoding
22///
23/// This detector emits the uniform candlestick sign convention shared across the
24/// pattern family — `−1.0` bearish, `0.0` no pattern — so it drops straight into
25/// a machine-learning feature matrix as a single dimension.
26///
27/// # Example
28///
29/// ```
30/// use wickra_core::{Candle, Indicator, TwoCrows};
31///
32/// let mut indicator = TwoCrows::new();
33/// indicator.update(Candle::new(10.0, 12.2, 9.9, 12.0, 1.0, 0).unwrap());
34/// indicator.update(Candle::new(14.0, 14.2, 12.9, 13.0, 1.0, 1).unwrap());
35/// let out = indicator
36///     .update(Candle::new(13.5, 13.6, 10.9, 11.0, 1.0, 2).unwrap());
37/// assert_eq!(out, Some(-1.0));
38/// ```
39#[derive(Debug, Clone, Default)]
40pub struct TwoCrows {
41    prev: Option<Candle>,
42    prev_prev: Option<Candle>,
43    has_emitted: bool,
44}
45
46impl TwoCrows {
47    /// Construct a new Two Crows detector.
48    pub const fn new() -> Self {
49        Self {
50            prev: None,
51            prev_prev: None,
52            has_emitted: false,
53        }
54    }
55}
56
57impl Indicator for TwoCrows {
58    type Input = Candle;
59    type Output = f64;
60
61    #[inline]
62    fn update(&mut self, candle: Candle) -> Option<f64> {
63        let pp = self.prev_prev;
64        let p = self.prev;
65        self.prev_prev = self.prev;
66        self.prev = Some(candle);
67        let (Some(bar1), Some(bar2)) = (pp, p) else {
68            return None;
69        };
70        self.has_emitted = true;
71        if bar1.close > bar1.open
72            && bar2.close < bar2.open
73            && bar2.close > bar1.close
74            && candle.close < candle.open
75            && candle.open < bar2.open
76            && candle.open > bar2.close
77            && candle.close > bar1.open
78            && candle.close < bar1.close
79        {
80            return Some(-1.0);
81        }
82        Some(0.0)
83    }
84
85    fn reset(&mut self) {
86        self.prev = None;
87        self.prev_prev = None;
88        self.has_emitted = false;
89    }
90
91    #[inline]
92    fn warmup_period(&self) -> usize {
93        3
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        "TwoCrows"
104    }
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110    use crate::traits::BatchExt;
111
112    fn c(open: f64, high: f64, low: f64, close: f64, ts: i64) -> Candle {
113        Candle::new(open, high, low, close, 1.0, ts).unwrap()
114    }
115
116    #[test]
117    fn accessors_and_metadata() {
118        let t = TwoCrows::new();
119        assert_eq!(t.name(), "TwoCrows");
120        assert_eq!(t.warmup_period(), 3);
121        assert!(!t.is_ready());
122    }
123
124    #[test]
125    fn two_crows_is_minus_one() {
126        let mut t = TwoCrows::new();
127        // bar1 green 10->12; bar2 red 14->13 (body above bar1); bar3 red
128        // opens 13.5 (inside [13,14]) and closes 11 (inside [10,12]).
129        assert_eq!(t.update(c(10.0, 12.2, 9.9, 12.0, 0)), None);
130        assert_eq!(t.update(c(14.0, 14.2, 12.9, 13.0, 1)), None);
131        assert_eq!(t.update(c(13.5, 13.6, 10.9, 11.0, 2)), Some(-1.0));
132    }
133
134    #[test]
135    fn no_gap_up_yields_zero() {
136        let mut t = TwoCrows::new();
137        // bar2 red but its body does not gap above bar1's body.
138        t.update(c(10.0, 12.2, 9.9, 12.0, 0));
139        t.update(c(11.5, 12.0, 10.4, 11.0, 1));
140        assert_eq!(t.update(c(11.0, 11.2, 9.9, 10.5, 2)), Some(0.0));
141    }
142
143    #[test]
144    fn third_close_below_first_body_yields_zero() {
145        let mut t = TwoCrows::new();
146        t.update(c(10.0, 12.2, 9.9, 12.0, 0));
147        t.update(c(14.0, 14.2, 12.9, 13.0, 1));
148        // bar3 closes 9.5, below bar1's body low (10) -> not Two Crows.
149        assert_eq!(t.update(c(13.5, 13.6, 9.4, 9.5, 2)), Some(0.0));
150    }
151
152    #[test]
153    fn first_two_bars_return_zero() {
154        let mut t = TwoCrows::new();
155        assert_eq!(t.update(c(10.0, 12.2, 9.9, 12.0, 0)), None);
156        assert_eq!(t.update(c(14.0, 14.2, 12.9, 13.0, 1)), None);
157    }
158
159    #[test]
160    fn batch_equals_streaming() {
161        let candles: Vec<Candle> = (0..40)
162            .map(|i| {
163                let base = 100.0 + i as f64;
164                if i % 3 == 0 {
165                    c(base, base + 0.5, base - 1.0, base + 0.4, i)
166                } else {
167                    c(base + 1.5, base + 1.7, base - 0.2, base + 0.6, i)
168                }
169            })
170            .collect();
171        let mut a = TwoCrows::new();
172        let mut b = TwoCrows::new();
173        assert_eq!(
174            a.batch(&candles),
175            candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
176        );
177    }
178
179    #[test]
180    fn reset_clears_state() {
181        let mut t = TwoCrows::new();
182        t.update(c(10.0, 12.2, 9.9, 12.0, 0));
183        t.update(c(14.0, 14.2, 12.9, 13.0, 1));
184        t.update(c(13.5, 13.6, 10.9, 11.0, 2));
185        assert!(t.is_ready());
186        t.reset();
187        assert!(!t.is_ready());
188        assert_eq!(t.update(c(10.0, 12.2, 9.9, 12.0, 0)), None);
189    }
190}