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    fn update(&mut self, candle: Candle) -> Option<f64> {
66        self.has_emitted = true;
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 Some(0.0);
73        };
74        // bar1 black, bar2 white, bar3 black.
75        if bar1.close >= bar1.open || bar2.close <= bar2.open || candle.close >= candle.open {
76            return Some(0.0);
77        }
78        // The white candle trades entirely above the first close.
79        if bar2.low <= bar1.close {
80            return Some(0.0);
81        }
82        // The two black candles close at the same level (the sandwich).
83        let range1 = bar1.high - bar1.low;
84        if (candle.close - bar1.close).abs() <= 0.1 * range1 {
85            return Some(1.0);
86        }
87        Some(0.0)
88    }
89
90    fn reset(&mut self) {
91        self.c1 = None;
92        self.c2 = None;
93        self.has_emitted = false;
94    }
95
96    fn warmup_period(&self) -> usize {
97        3
98    }
99
100    fn is_ready(&self) -> bool {
101        self.has_emitted
102    }
103
104    fn name(&self) -> &'static str {
105        "StickSandwich"
106    }
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112    use crate::traits::BatchExt;
113
114    fn c(open: f64, high: f64, low: f64, close: f64, ts: i64) -> Candle {
115        Candle::new(open, high, low, close, 1.0, ts).unwrap()
116    }
117
118    #[test]
119    fn accessors_and_metadata() {
120        let t = StickSandwich::new();
121        assert_eq!(t.name(), "StickSandwich");
122        assert_eq!(t.warmup_period(), 3);
123        assert!(!t.is_ready());
124    }
125
126    #[test]
127    fn stick_sandwich_is_plus_one() {
128        let mut t = StickSandwich::new();
129        assert_eq!(t.update(c(12.0, 12.1, 9.9, 10.0, 0)), Some(0.0));
130        assert_eq!(t.update(c(10.5, 11.6, 10.4, 11.5, 1)), Some(0.0));
131        assert_eq!(t.update(c(11.5, 11.6, 9.9, 10.0, 2)), Some(1.0));
132    }
133
134    #[test]
135    fn first_two_bars_return_zero() {
136        let mut t = StickSandwich::new();
137        assert_eq!(t.update(c(12.0, 12.1, 9.9, 10.0, 0)), Some(0.0));
138        assert_eq!(t.update(c(10.5, 11.6, 10.4, 11.5, 1)), Some(0.0));
139    }
140
141    #[test]
142    fn first_candle_not_black_yields_zero() {
143        let mut t = StickSandwich::new();
144        // bar1 white.
145        t.update(c(9.9, 12.1, 9.8, 10.0, 0));
146        t.update(c(10.5, 11.6, 10.4, 11.5, 1));
147        assert_eq!(t.update(c(11.5, 11.6, 9.9, 10.0, 2)), Some(0.0));
148    }
149
150    #[test]
151    fn middle_candle_not_white_yields_zero() {
152        let mut t = StickSandwich::new();
153        t.update(c(12.0, 12.1, 9.9, 10.0, 0));
154        // bar2 black.
155        t.update(c(11.5, 11.6, 10.4, 10.5, 1));
156        assert_eq!(t.update(c(11.5, 11.6, 9.9, 10.0, 2)), Some(0.0));
157    }
158
159    #[test]
160    fn third_candle_not_black_yields_zero() {
161        let mut t = StickSandwich::new();
162        t.update(c(12.0, 12.1, 9.9, 10.0, 0));
163        t.update(c(10.5, 11.6, 10.4, 11.5, 1));
164        // bar3 white.
165        assert_eq!(t.update(c(9.9, 11.6, 9.8, 10.0, 2)), Some(0.0));
166    }
167
168    #[test]
169    fn middle_low_not_above_first_close_yields_zero() {
170        let mut t = StickSandwich::new();
171        t.update(c(12.0, 12.1, 9.9, 10.0, 0));
172        // bar2 white but dips below bar1's close.
173        t.update(c(10.5, 11.6, 9.0, 11.5, 1));
174        assert_eq!(t.update(c(11.5, 11.6, 9.9, 10.0, 2)), Some(0.0));
175    }
176
177    #[test]
178    fn mismatched_closes_yield_zero() {
179        let mut t = StickSandwich::new();
180        t.update(c(12.0, 12.1, 9.9, 10.0, 0));
181        t.update(c(10.5, 11.6, 10.4, 11.5, 1));
182        // bar3 black but closes well away from bar1's close.
183        assert_eq!(t.update(c(11.5, 11.6, 7.9, 8.0, 2)), Some(0.0));
184    }
185
186    #[test]
187    fn batch_equals_streaming() {
188        let candles: Vec<Candle> = (0..40)
189            .map(|i| {
190                let base = 100.0 + i as f64;
191                c(base + 2.0, base + 2.1, base - 0.1, base, i)
192            })
193            .collect();
194        let mut a = StickSandwich::new();
195        let mut b = StickSandwich::new();
196        assert_eq!(
197            a.batch(&candles),
198            candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
199        );
200    }
201
202    #[test]
203    fn reset_clears_state() {
204        let mut t = StickSandwich::new();
205        t.update(c(12.0, 12.1, 9.9, 10.0, 0));
206        t.update(c(10.5, 11.6, 10.4, 11.5, 1));
207        t.update(c(11.5, 11.6, 9.9, 10.0, 2));
208        assert!(t.is_ready());
209        t.reset();
210        assert!(!t.is_ready());
211        assert_eq!(t.update(c(12.0, 12.1, 9.9, 10.0, 0)), Some(0.0));
212    }
213}