Skip to main content

wickra_core/indicators/
hanging_man.rs

1//! Hanging Man candlestick pattern.
2
3use crate::ohlcv::Candle;
4use crate::traits::Indicator;
5
6/// Hanging Man — a single-bar bearish reversal candidate.
7///
8/// A Hanging Man has the same geometry as a Hammer (small body near the top,
9/// long lower shadow ≥ 2× body, short upper shadow) but is read bearishly
10/// because it appears at the top of an uptrend.
11///
12/// ```text
13/// body         = |close − open|
14/// upper_shadow = high − max(open, close)
15/// lower_shadow = min(open, close) − low
16/// hanging      = lower_shadow >= 2 * body
17///               && upper_shadow <= body
18///               && body > 0
19/// ```
20///
21/// Output is `−1.0` when the shape matches, `0.0` otherwise. Pattern-shape
22/// check only — no trend filter is applied; combine with a trend indicator
23/// for actionable signals.
24///
25/// # Signed ±1 encoding
26///
27/// A Hanging Man is bearish by definition, so under the uniform candlestick
28/// sign convention (`+1.0` bullish, `−1.0` bearish, `0.0` none) it emits
29/// `−1.0` when the shape matches and `0.0` otherwise — it never emits `+1.0`.
30/// The same geometry read at the bottom of a downtrend is the bullish
31/// `Hammer`, which carries the opposite sign.
32///
33/// # Example
34///
35/// ```
36/// use wickra_core::{Candle, HangingMan, Indicator};
37///
38/// let mut indicator = HangingMan::new();
39/// let candle = Candle::new(10.0, 10.6, 5.0, 10.5, 1.0, 0).unwrap();
40/// assert_eq!(indicator.update(candle), Some(-1.0));
41/// ```
42#[derive(Debug, Clone, Default)]
43pub struct HangingMan {
44    has_emitted: bool,
45}
46
47impl HangingMan {
48    /// Construct a new Hanging Man detector.
49    pub const fn new() -> Self {
50        Self { has_emitted: false }
51    }
52}
53
54impl Indicator for HangingMan {
55    type Input = Candle;
56    type Output = f64;
57
58    fn update(&mut self, candle: Candle) -> Option<f64> {
59        self.has_emitted = true;
60        let range = candle.high - candle.low;
61        if range <= 0.0 {
62            return Some(0.0);
63        }
64        let body = (candle.close - candle.open).abs();
65        if body <= 0.0 {
66            return Some(0.0);
67        }
68        let upper = candle.high - candle.open.max(candle.close);
69        let lower = candle.open.min(candle.close) - candle.low;
70        Some(if lower >= 2.0 * body && upper <= body {
71            -1.0
72        } else {
73            0.0
74        })
75    }
76
77    fn reset(&mut self) {
78        self.has_emitted = false;
79    }
80
81    fn warmup_period(&self) -> usize {
82        1
83    }
84
85    fn is_ready(&self) -> bool {
86        self.has_emitted
87    }
88
89    fn name(&self) -> &'static str {
90        "HangingMan"
91    }
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97    use crate::traits::BatchExt;
98
99    fn c(open: f64, high: f64, low: f64, close: f64, ts: i64) -> Candle {
100        Candle::new(open, high, low, close, 1.0, ts).unwrap()
101    }
102
103    #[test]
104    fn accessors_and_metadata() {
105        let h = HangingMan::new();
106        assert_eq!(h.name(), "HangingMan");
107        assert_eq!(h.warmup_period(), 1);
108        assert!(!h.is_ready());
109    }
110
111    #[test]
112    fn clean_hanging_man_is_minus_one() {
113        let mut h = HangingMan::new();
114        assert_eq!(h.update(c(10.0, 10.6, 5.0, 10.5, 0)), Some(-1.0));
115    }
116
117    #[test]
118    fn marubozu_is_not_hanging_man() {
119        let mut h = HangingMan::new();
120        assert_eq!(h.update(c(10.0, 12.0, 10.0, 12.0, 0)), Some(0.0));
121    }
122
123    #[test]
124    fn doji_is_not_hanging_man() {
125        let mut h = HangingMan::new();
126        assert_eq!(h.update(c(10.0, 11.0, 9.0, 10.0, 0)), Some(0.0));
127    }
128
129    #[test]
130    fn zero_range_yields_zero() {
131        let mut h = HangingMan::new();
132        assert_eq!(h.update(c(10.0, 10.0, 10.0, 10.0, 0)), Some(0.0));
133    }
134
135    #[test]
136    fn batch_equals_streaming() {
137        let candles: Vec<Candle> = (0..40)
138            .map(|i| {
139                let base = 100.0 + i as f64;
140                c(base, base + 2.0, base - 4.0, base + 0.5, i)
141            })
142            .collect();
143        let mut a = HangingMan::new();
144        let mut b = HangingMan::new();
145        assert_eq!(
146            a.batch(&candles),
147            candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
148        );
149    }
150
151    #[test]
152    fn reset_clears_state() {
153        let mut h = HangingMan::new();
154        h.update(c(10.0, 10.6, 5.0, 10.5, 0));
155        assert!(h.is_ready());
156        h.reset();
157        assert!(!h.is_ready());
158    }
159}