Skip to main content

wickra_core/indicators/
stalled_pattern.rs

1//! Stalled Pattern (Deliberation) candlestick pattern.
2
3use crate::ohlcv::Candle;
4use crate::traits::Indicator;
5
6/// Stalled Pattern (also called Deliberation) — a 3-bar bearish reversal warning.
7/// Two long white candles push higher, then a small-bodied white candle opens at
8/// or near the top of the second body and barely advances — the rally is running
9/// out of breath, hinting that buyers are losing control.
10///
11/// ```text
12/// long body  = |close − open| >= 0.5 * (high − low)
13/// small body = |close − open| <= 0.3 * (high − low)
14/// bar1, bar2 long white; bar3 small white
15/// rising closes: close3 > close2 > close1
16/// bar3 rides the shoulder: open3 >= close2 − 0.1 * (high2 − low2)
17/// ```
18///
19/// Output is `−1.0` when the pattern completes and `0.0` otherwise. Stalled Pattern
20/// is a single-direction (bearish-only) warning, so it never emits `+1.0`. The
21/// first two bars always return `0.0` because the three-bar window is not yet
22/// filled. Body thresholds follow the geometric house style rather than TA-Lib's
23/// rolling averages. Pattern-shape check only — no trend filter is applied; combine
24/// with a trend indicator for actionable signals.
25///
26/// # Signed ±1 encoding
27///
28/// This detector emits the uniform candlestick sign convention shared across the
29/// pattern family — `−1.0` bearish, `0.0` no pattern — so it drops straight into
30/// a machine-learning feature matrix as a single dimension.
31///
32/// # Example
33///
34/// ```
35/// use wickra_core::{Candle, Indicator, StalledPattern};
36///
37/// let mut indicator = StalledPattern::new();
38/// indicator.update(Candle::new(10.0, 12.05, 9.9, 12.0, 1.0, 0).unwrap());
39/// indicator.update(Candle::new(11.0, 14.05, 10.9, 14.0, 1.0, 1).unwrap());
40/// let out = indicator
41///     .update(Candle::new(14.0, 14.6, 13.95, 14.15, 1.0, 2).unwrap());
42/// assert_eq!(out, Some(-1.0));
43/// ```
44#[derive(Debug, Clone, Default)]
45pub struct StalledPattern {
46    c1: Option<Candle>,
47    c2: Option<Candle>,
48    has_emitted: bool,
49}
50
51impl StalledPattern {
52    /// Construct a new Stalled Pattern detector.
53    pub const fn new() -> Self {
54        Self {
55            c1: None,
56            c2: None,
57            has_emitted: false,
58        }
59    }
60}
61
62impl Indicator for StalledPattern {
63    type Input = Candle;
64    type Output = f64;
65
66    fn update(&mut self, candle: Candle) -> Option<f64> {
67        self.has_emitted = true;
68        let bar1 = self.c1;
69        let bar2 = self.c2;
70        self.c1 = self.c2;
71        self.c2 = Some(candle);
72        let (Some(bar1), Some(bar2)) = (bar1, bar2) else {
73            return Some(0.0);
74        };
75        let range1 = bar1.high - bar1.low;
76        let range2 = bar2.high - bar2.low;
77        let range3 = candle.high - candle.low;
78        if range1 <= 0.0 || range2 <= 0.0 || range3 <= 0.0 {
79            return Some(0.0);
80        }
81        // All three candles are white.
82        if bar1.close <= bar1.open || bar2.close <= bar2.open || candle.close <= candle.open {
83            return Some(0.0);
84        }
85        // Rising closes.
86        if candle.close <= bar2.close || bar2.close <= bar1.close {
87            return Some(0.0);
88        }
89        // bar1 and bar2 are long bodies.
90        if bar1.close - bar1.open < 0.5 * range1 || bar2.close - bar2.open < 0.5 * range2 {
91            return Some(0.0);
92        }
93        // bar3 is a small body.
94        if candle.close - candle.open > 0.3 * range3 {
95            return Some(0.0);
96        }
97        // bar3 opens at or near the top of bar2's body (rides the shoulder).
98        if candle.open >= bar2.close - 0.1 * range2 {
99            return Some(-1.0);
100        }
101        Some(0.0)
102    }
103
104    fn reset(&mut self) {
105        self.c1 = None;
106        self.c2 = None;
107        self.has_emitted = false;
108    }
109
110    fn warmup_period(&self) -> usize {
111        3
112    }
113
114    fn is_ready(&self) -> bool {
115        self.has_emitted
116    }
117
118    fn name(&self) -> &'static str {
119        "StalledPattern"
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126    use crate::traits::BatchExt;
127
128    fn c(open: f64, high: f64, low: f64, close: f64, ts: i64) -> Candle {
129        Candle::new(open, high, low, close, 1.0, ts).unwrap()
130    }
131
132    #[test]
133    fn accessors_and_metadata() {
134        let t = StalledPattern::new();
135        assert_eq!(t.name(), "StalledPattern");
136        assert_eq!(t.warmup_period(), 3);
137        assert!(!t.is_ready());
138    }
139
140    #[test]
141    fn stalled_pattern_is_minus_one() {
142        let mut t = StalledPattern::new();
143        assert_eq!(t.update(c(10.0, 12.05, 9.9, 12.0, 0)), Some(0.0));
144        assert_eq!(t.update(c(11.0, 14.05, 10.9, 14.0, 1)), Some(0.0));
145        assert_eq!(t.update(c(14.0, 14.6, 13.95, 14.15, 2)), Some(-1.0));
146    }
147
148    #[test]
149    fn first_two_bars_return_zero() {
150        let mut t = StalledPattern::new();
151        assert_eq!(t.update(c(10.0, 12.05, 9.9, 12.0, 0)), Some(0.0));
152        assert_eq!(t.update(c(11.0, 14.05, 10.9, 14.0, 1)), Some(0.0));
153    }
154
155    #[test]
156    fn zero_range_yields_zero() {
157        let mut t = StalledPattern::new();
158        t.update(c(10.0, 12.05, 9.9, 12.0, 0));
159        t.update(c(11.0, 14.05, 10.9, 14.0, 1));
160        // bar3 has zero range.
161        assert_eq!(t.update(c(14.0, 14.0, 14.0, 14.0, 2)), Some(0.0));
162    }
163
164    #[test]
165    fn non_white_yields_zero() {
166        let mut t = StalledPattern::new();
167        t.update(c(10.0, 12.05, 9.9, 12.0, 0));
168        t.update(c(11.0, 14.05, 10.9, 14.0, 1));
169        // bar3 is black.
170        assert_eq!(t.update(c(14.2, 14.6, 13.95, 14.05, 2)), Some(0.0));
171    }
172
173    #[test]
174    fn non_rising_closes_yield_zero() {
175        let mut t = StalledPattern::new();
176        t.update(c(10.0, 12.05, 9.9, 12.0, 0));
177        t.update(c(11.0, 14.05, 10.9, 14.0, 1));
178        // bar3 closes below bar2's close (white but not advancing).
179        assert_eq!(t.update(c(13.5, 14.0, 13.45, 13.6, 2)), Some(0.0));
180    }
181
182    #[test]
183    fn short_first_bodies_yield_zero() {
184        let mut t = StalledPattern::new();
185        // bar1 is white but its body is short relative to range.
186        t.update(c(11.5, 14.0, 10.0, 12.0, 0));
187        t.update(c(11.0, 14.05, 10.9, 14.0, 1));
188        assert_eq!(t.update(c(14.0, 14.6, 13.95, 14.15, 2)), Some(0.0));
189    }
190
191    #[test]
192    fn large_third_body_yields_zero() {
193        let mut t = StalledPattern::new();
194        t.update(c(10.0, 12.05, 9.9, 12.0, 0));
195        t.update(c(11.0, 14.05, 10.9, 14.0, 1));
196        // bar3 has a large body (not a small stalling candle).
197        assert_eq!(t.update(c(14.0, 16.05, 13.95, 16.0, 2)), Some(0.0));
198    }
199
200    #[test]
201    fn third_bar_off_shoulder_yields_zero() {
202        let mut t = StalledPattern::new();
203        t.update(c(10.0, 12.05, 9.9, 12.0, 0));
204        t.update(c(11.0, 14.05, 10.9, 14.0, 1));
205        // bar3 is a small white candle but opens well below bar2's close,
206        // so it is not riding the shoulder.
207        assert_eq!(t.update(c(13.6, 14.1, 12.55, 14.05, 2)), Some(0.0));
208    }
209
210    #[test]
211    fn batch_equals_streaming() {
212        let candles: Vec<Candle> = (0..40)
213            .map(|i| {
214                let base = 100.0 + i as f64;
215                c(base, base + 2.05, base - 0.1, base + 2.0, i)
216            })
217            .collect();
218        let mut a = StalledPattern::new();
219        let mut b = StalledPattern::new();
220        assert_eq!(
221            a.batch(&candles),
222            candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
223        );
224    }
225
226    #[test]
227    fn reset_clears_state() {
228        let mut t = StalledPattern::new();
229        t.update(c(10.0, 12.05, 9.9, 12.0, 0));
230        t.update(c(11.0, 14.05, 10.9, 14.0, 1));
231        t.update(c(14.0, 14.6, 13.95, 14.15, 2));
232        assert!(t.is_ready());
233        t.reset();
234        assert!(!t.is_ready());
235        assert_eq!(t.update(c(10.0, 12.05, 9.9, 12.0, 0)), Some(0.0));
236    }
237}