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    #[inline]
59    fn update(&mut self, candle: Candle) -> Option<f64> {
60        self.has_emitted = true;
61        let range = candle.high - candle.low;
62        if range <= 0.0 {
63            return Some(0.0);
64        }
65        let body = (candle.close - candle.open).abs();
66        if body <= 0.0 {
67            return Some(0.0);
68        }
69        let upper = candle.high - candle.open.max(candle.close);
70        let lower = candle.open.min(candle.close) - candle.low;
71        Some(if lower >= 2.0 * body && upper <= body {
72            -1.0
73        } else {
74            0.0
75        })
76    }
77
78    fn reset(&mut self) {
79        self.has_emitted = false;
80    }
81
82    #[inline]
83    fn warmup_period(&self) -> usize {
84        1
85    }
86
87    #[inline]
88    fn is_ready(&self) -> bool {
89        self.has_emitted
90    }
91
92    #[inline]
93    fn name(&self) -> &'static str {
94        "HangingMan"
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101    use crate::traits::BatchExt;
102
103    fn c(open: f64, high: f64, low: f64, close: f64, ts: i64) -> Candle {
104        Candle::new(open, high, low, close, 1.0, ts).unwrap()
105    }
106
107    #[test]
108    fn accessors_and_metadata() {
109        let h = HangingMan::new();
110        assert_eq!(h.name(), "HangingMan");
111        assert_eq!(h.warmup_period(), 1);
112        assert!(!h.is_ready());
113    }
114
115    #[test]
116    fn clean_hanging_man_is_minus_one() {
117        let mut h = HangingMan::new();
118        assert_eq!(h.update(c(10.0, 10.6, 5.0, 10.5, 0)), Some(-1.0));
119    }
120
121    #[test]
122    fn marubozu_is_not_hanging_man() {
123        let mut h = HangingMan::new();
124        assert_eq!(h.update(c(10.0, 12.0, 10.0, 12.0, 0)), Some(0.0));
125    }
126
127    #[test]
128    fn doji_is_not_hanging_man() {
129        let mut h = HangingMan::new();
130        assert_eq!(h.update(c(10.0, 11.0, 9.0, 10.0, 0)), Some(0.0));
131    }
132
133    #[test]
134    fn zero_range_yields_zero() {
135        let mut h = HangingMan::new();
136        assert_eq!(h.update(c(10.0, 10.0, 10.0, 10.0, 0)), Some(0.0));
137    }
138
139    #[test]
140    fn batch_equals_streaming() {
141        let candles: Vec<Candle> = (0..40)
142            .map(|i| {
143                let base = 100.0 + i as f64;
144                c(base, base + 2.0, base - 4.0, base + 0.5, i)
145            })
146            .collect();
147        let mut a = HangingMan::new();
148        let mut b = HangingMan::new();
149        assert_eq!(
150            a.batch(&candles),
151            candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
152        );
153    }
154
155    #[test]
156    fn reset_clears_state() {
157        let mut h = HangingMan::new();
158        h.update(c(10.0, 10.6, 5.0, 10.5, 0));
159        assert!(h.is_ready());
160        h.reset();
161        assert!(!h.is_ready());
162    }
163}