Skip to main content

wickra_core/indicators/
marubozu.rs

1//! Marubozu candlestick pattern.
2
3use crate::error::{Error, Result};
4use crate::ohlcv::Candle;
5use crate::traits::Indicator;
6
7/// Marubozu — a single-bar strong-continuation candle with body equal to range
8/// and (almost) no shadows.
9///
10/// ```text
11/// range        = high − low
12/// upper_shadow = high − max(open, close)
13/// lower_shadow = min(open, close) − low
14/// shadows OK   = upper_shadow <= tol * range && lower_shadow <= tol * range
15/// ```
16///
17/// When the shadow tolerance is satisfied the output is `+1.0` for a bullish
18/// Marubozu (close > open) and `−1.0` for a bearish one (close < open). Any
19/// candle whose shadows exceed the tolerance — or whose body is zero — yields
20/// `0.0`.
21///
22/// `shadow_tolerance` defaults to `0.05` (5 % of the bar range allowed on each
23/// side) and must lie in `[0, 1)`.
24///
25/// # Signed ±1 encoding
26///
27/// This detector already emits the uniform candlestick sign convention shared
28/// across the pattern family — `+1.0` bullish, `−1.0` bearish, `0.0` no
29/// pattern — so it drops straight into a machine-learning feature matrix where
30/// the bullish and bearish variants of the pattern occupy a single dimension.
31///
32/// # Example
33///
34/// ```
35/// use wickra_core::{Candle, Indicator, Marubozu};
36///
37/// let mut indicator = Marubozu::new();
38/// // Bullish marubozu: open == low, close == high.
39/// let candle = Candle::new(10.0, 12.0, 10.0, 12.0, 1.0, 0).unwrap();
40/// assert_eq!(indicator.update(candle), Some(1.0));
41/// ```
42#[derive(Debug, Clone)]
43pub struct Marubozu {
44    shadow_tolerance: f64,
45    has_emitted: bool,
46}
47
48impl Default for Marubozu {
49    fn default() -> Self {
50        Self::new()
51    }
52}
53
54impl Marubozu {
55    /// Construct a Marubozu detector with the default 5 % shadow tolerance.
56    pub const fn new() -> Self {
57        Self {
58            shadow_tolerance: 0.05,
59            has_emitted: false,
60        }
61    }
62
63    /// Construct a Marubozu detector with a custom shadow tolerance.
64    ///
65    /// `shadow_tolerance` must lie in `[0, 1)`.
66    pub fn with_tolerance(shadow_tolerance: f64) -> Result<Self> {
67        if !(0.0..1.0).contains(&shadow_tolerance) {
68            return Err(Error::InvalidPeriod {
69                message: "marubozu shadow tolerance must lie in [0, 1)",
70            });
71        }
72        Ok(Self {
73            shadow_tolerance,
74            has_emitted: false,
75        })
76    }
77
78    /// Configured shadow tolerance.
79    pub fn shadow_tolerance(&self) -> f64 {
80        self.shadow_tolerance
81    }
82}
83
84impl Indicator for Marubozu {
85    type Input = Candle;
86    type Output = f64;
87
88    #[inline]
89    fn update(&mut self, candle: Candle) -> Option<f64> {
90        self.has_emitted = true;
91        let range = candle.high - candle.low;
92        if range <= 0.0 {
93            return Some(0.0);
94        }
95        let body = candle.close - candle.open;
96        if body == 0.0 {
97            return Some(0.0);
98        }
99        let upper = candle.high - candle.open.max(candle.close);
100        let lower = candle.open.min(candle.close) - candle.low;
101        let tol = self.shadow_tolerance * range;
102        if upper <= tol && lower <= tol {
103            Some(if body > 0.0 { 1.0 } else { -1.0 })
104        } else {
105            Some(0.0)
106        }
107    }
108
109    fn reset(&mut self) {
110        self.has_emitted = false;
111    }
112
113    #[inline]
114    fn warmup_period(&self) -> usize {
115        1
116    }
117
118    #[inline]
119    fn is_ready(&self) -> bool {
120        self.has_emitted
121    }
122
123    #[inline]
124    fn name(&self) -> &'static str {
125        "Marubozu"
126    }
127}
128
129#[cfg(test)]
130mod tests {
131    use super::*;
132    use crate::traits::BatchExt;
133
134    fn c(open: f64, high: f64, low: f64, close: f64, ts: i64) -> Candle {
135        Candle::new(open, high, low, close, 1.0, ts).unwrap()
136    }
137
138    #[test]
139    fn rejects_invalid_tolerance() {
140        assert!(Marubozu::with_tolerance(-0.01).is_err());
141        assert!(Marubozu::with_tolerance(1.0).is_err());
142        assert!(Marubozu::with_tolerance(2.0).is_err());
143    }
144
145    #[test]
146    fn accepts_valid_tolerance() {
147        let m = Marubozu::with_tolerance(0.0).unwrap();
148        assert!((m.shadow_tolerance() - 0.0).abs() < 1e-12);
149        let m = Marubozu::with_tolerance(0.5).unwrap();
150        assert!((m.shadow_tolerance() - 0.5).abs() < 1e-12);
151    }
152
153    #[test]
154    fn accessors_and_metadata() {
155        let m = Marubozu::default();
156        assert_eq!(m.name(), "Marubozu");
157        assert_eq!(m.warmup_period(), 1);
158        assert!(!m.is_ready());
159        assert!((m.shadow_tolerance() - 0.05).abs() < 1e-12);
160    }
161
162    #[test]
163    fn bullish_marubozu_is_plus_one() {
164        let mut m = Marubozu::new();
165        assert_eq!(m.update(c(10.0, 12.0, 10.0, 12.0, 0)), Some(1.0));
166    }
167
168    #[test]
169    fn bearish_marubozu_is_minus_one() {
170        let mut m = Marubozu::new();
171        assert_eq!(m.update(c(12.0, 12.0, 10.0, 10.0, 0)), Some(-1.0));
172    }
173
174    #[test]
175    fn candle_with_long_shadows_is_zero() {
176        let mut m = Marubozu::new();
177        // Big upper shadow violates tolerance.
178        assert_eq!(m.update(c(10.0, 15.0, 10.0, 12.0, 0)), Some(0.0));
179    }
180
181    #[test]
182    fn doji_is_zero() {
183        let mut m = Marubozu::new();
184        // body == 0 -> not a marubozu.
185        assert_eq!(m.update(c(10.0, 11.0, 9.0, 10.0, 0)), Some(0.0));
186    }
187
188    #[test]
189    fn zero_range_yields_zero() {
190        let mut m = Marubozu::new();
191        assert_eq!(m.update(c(10.0, 10.0, 10.0, 10.0, 0)), Some(0.0));
192    }
193
194    #[test]
195    fn batch_equals_streaming() {
196        let candles: Vec<Candle> = (0..40)
197            .map(|i| {
198                let base = 100.0 + i as f64;
199                c(base, base + 2.0, base, base + 2.0, i)
200            })
201            .collect();
202        let mut a = Marubozu::new();
203        let mut b = Marubozu::new();
204        assert_eq!(
205            a.batch(&candles),
206            candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
207        );
208    }
209
210    #[test]
211    fn reset_clears_state() {
212        let mut m = Marubozu::new();
213        m.update(c(10.0, 12.0, 10.0, 12.0, 0));
214        assert!(m.is_ready());
215        m.reset();
216        assert!(!m.is_ready());
217    }
218}