Skip to main content

wickra_core/indicators/
stick_sandwich.rs

1//! Stick Sandwich candlestick pattern.
2
3use crate::ohlcv::Candle;
4use crate::traits::Indicator;
5
6/// Stick Sandwich — a 3-bar bullish reversal. A black candle is followed by a
7/// white candle that trades entirely above the first close, then a second black
8/// candle drives price back down to close at the same level as the first. The
9/// matching closes "sandwich" the white candle and mark a support floor.
10///
11/// ```text
12/// bar1 black, bar2 white, bar3 black
13/// bar2 trades above bar1's close: low2 > close1
14/// matching closes: |close3 − close1| <= 0.1 * (high1 − low1)
15/// ```
16///
17/// Output is `+1.0` when the pattern completes and `0.0` otherwise. Stick Sandwich
18/// is a single-direction (bullish-only) reversal, so it never emits `−1.0`. The
19/// first two bars always return `0.0` because the three-bar window is not yet
20/// filled. The matching-close tolerance follows the geometric house style (a fixed
21/// fraction of the first bar's range) rather than TA-Lib's rolling averages.
22/// Pattern-shape check only — no trend filter is applied; combine with a trend
23/// indicator for actionable signals.
24///
25/// # Signed ±1 encoding
26///
27/// This detector emits the uniform candlestick sign convention shared across the
28/// pattern family — `+1.0` bullish, `0.0` no pattern — so it drops straight into
29/// a machine-learning feature matrix as a single dimension.
30///
31/// # Example
32///
33/// ```
34/// use wickra_core::{Candle, Indicator, StickSandwich};
35///
36/// let mut indicator = StickSandwich::new();
37/// indicator.update(Candle::new(12.0, 12.1, 9.9, 10.0, 1.0, 0).unwrap());
38/// indicator.update(Candle::new(10.5, 11.6, 10.4, 11.5, 1.0, 1).unwrap());
39/// let out = indicator
40///     .update(Candle::new(11.5, 11.6, 9.9, 10.0, 1.0, 2).unwrap());
41/// assert_eq!(out, Some(1.0));
42/// ```
43#[derive(Debug, Clone, Default)]
44pub struct StickSandwich {
45    c1: Option<Candle>,
46    c2: Option<Candle>,
47    has_emitted: bool,
48}
49
50impl StickSandwich {
51    /// Construct a new Stick Sandwich detector.
52    pub const fn new() -> Self {
53        Self {
54            c1: None,
55            c2: None,
56            has_emitted: false,
57        }
58    }
59}
60
61impl Indicator for StickSandwich {
62    type Input = Candle;
63    type Output = f64;
64
65    #[inline]
66    fn update(&mut self, candle: Candle) -> Option<f64> {
67        let bar1 = self.c1;
68        let bar2 = self.c2;
69        self.c1 = self.c2;
70        self.c2 = Some(candle);
71        let (Some(bar1), Some(bar2)) = (bar1, bar2) else {
72            return None;
73        };
74        self.has_emitted = true;
75        // bar1 black, bar2 white, bar3 black.
76        if bar1.close >= bar1.open || bar2.close <= bar2.open || candle.close >= candle.open {
77            return Some(0.0);
78        }
79        // The white candle trades entirely above the first close.
80        if bar2.low <= bar1.close {
81            return Some(0.0);
82        }
83        // The two black candles close at the same level (the sandwich).
84        let range1 = bar1.high - bar1.low;
85        if (candle.close - bar1.close).abs() <= 0.1 * range1 {
86            return Some(1.0);
87        }
88        Some(0.0)
89    }
90
91    fn reset(&mut self) {
92        self.c1 = None;
93        self.c2 = None;
94        self.has_emitted = false;
95    }
96
97    #[inline]
98    fn warmup_period(&self) -> usize {
99        3
100    }
101
102    #[inline]
103    fn is_ready(&self) -> bool {
104        self.has_emitted
105    }
106
107    #[inline]
108    fn name(&self) -> &'static str {
109        "StickSandwich"
110    }
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116    use crate::traits::BatchExt;
117
118    fn c(open: f64, high: f64, low: f64, close: f64, ts: i64) -> Candle {
119        Candle::new(open, high, low, close, 1.0, ts).unwrap()
120    }
121
122    #[test]
123    fn accessors_and_metadata() {
124        let t = StickSandwich::new();
125        assert_eq!(t.name(), "StickSandwich");
126        assert_eq!(t.warmup_period(), 3);
127        assert!(!t.is_ready());
128    }
129
130    #[test]
131    fn stick_sandwich_is_plus_one() {
132        let mut t = StickSandwich::new();
133        assert_eq!(t.update(c(12.0, 12.1, 9.9, 10.0, 0)), None);
134        assert_eq!(t.update(c(10.5, 11.6, 10.4, 11.5, 1)), None);
135        assert_eq!(t.update(c(11.5, 11.6, 9.9, 10.0, 2)), Some(1.0));
136    }
137
138    #[test]
139    fn first_two_bars_return_zero() {
140        let mut t = StickSandwich::new();
141        assert_eq!(t.update(c(12.0, 12.1, 9.9, 10.0, 0)), None);
142        assert_eq!(t.update(c(10.5, 11.6, 10.4, 11.5, 1)), None);
143    }
144
145    #[test]
146    fn first_candle_not_black_yields_zero() {
147        let mut t = StickSandwich::new();
148        // bar1 white.
149        t.update(c(9.9, 12.1, 9.8, 10.0, 0));
150        t.update(c(10.5, 11.6, 10.4, 11.5, 1));
151        assert_eq!(t.update(c(11.5, 11.6, 9.9, 10.0, 2)), Some(0.0));
152    }
153
154    #[test]
155    fn middle_candle_not_white_yields_zero() {
156        let mut t = StickSandwich::new();
157        t.update(c(12.0, 12.1, 9.9, 10.0, 0));
158        // bar2 black.
159        t.update(c(11.5, 11.6, 10.4, 10.5, 1));
160        assert_eq!(t.update(c(11.5, 11.6, 9.9, 10.0, 2)), Some(0.0));
161    }
162
163    #[test]
164    fn third_candle_not_black_yields_zero() {
165        let mut t = StickSandwich::new();
166        t.update(c(12.0, 12.1, 9.9, 10.0, 0));
167        t.update(c(10.5, 11.6, 10.4, 11.5, 1));
168        // bar3 white.
169        assert_eq!(t.update(c(9.9, 11.6, 9.8, 10.0, 2)), Some(0.0));
170    }
171
172    #[test]
173    fn middle_low_not_above_first_close_yields_zero() {
174        let mut t = StickSandwich::new();
175        t.update(c(12.0, 12.1, 9.9, 10.0, 0));
176        // bar2 white but dips below bar1's close.
177        t.update(c(10.5, 11.6, 9.0, 11.5, 1));
178        assert_eq!(t.update(c(11.5, 11.6, 9.9, 10.0, 2)), Some(0.0));
179    }
180
181    #[test]
182    fn mismatched_closes_yield_zero() {
183        let mut t = StickSandwich::new();
184        t.update(c(12.0, 12.1, 9.9, 10.0, 0));
185        t.update(c(10.5, 11.6, 10.4, 11.5, 1));
186        // bar3 black but closes well away from bar1's close.
187        assert_eq!(t.update(c(11.5, 11.6, 7.9, 8.0, 2)), Some(0.0));
188    }
189
190    #[test]
191    fn batch_equals_streaming() {
192        let candles: Vec<Candle> = (0..40)
193            .map(|i| {
194                let base = 100.0 + i as f64;
195                c(base + 2.0, base + 2.1, base - 0.1, base, i)
196            })
197            .collect();
198        let mut a = StickSandwich::new();
199        let mut b = StickSandwich::new();
200        assert_eq!(
201            a.batch(&candles),
202            candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
203        );
204    }
205
206    #[test]
207    fn reset_clears_state() {
208        let mut t = StickSandwich::new();
209        t.update(c(12.0, 12.1, 9.9, 10.0, 0));
210        t.update(c(10.5, 11.6, 10.4, 11.5, 1));
211        t.update(c(11.5, 11.6, 9.9, 10.0, 2));
212        assert!(t.is_ready());
213        t.reset();
214        assert!(!t.is_ready());
215        assert_eq!(t.update(c(12.0, 12.1, 9.9, 10.0, 0)), None);
216    }
217}