Skip to main content

wickra_core/indicators/
head_and_shoulders.rs

1//! Head-and-Shoulders (and Inverse) reversal chart pattern.
2
3use crate::indicators::pattern_swing::{
4    approx_equal, SwingTracker, LEVEL_TOLERANCE, SWING_THRESHOLD,
5};
6use crate::ohlcv::Candle;
7use crate::traits::Indicator;
8
9/// Head-and-Shoulders / Inverse Head-and-Shoulders — a five-pivot reversal
10/// pattern with a central extreme (the head) flanked by two lower/higher
11/// shoulders at a similar level, joined by a roughly horizontal neckline.
12///
13/// Built on confirmed swing pivots (`SWING_THRESHOLD` = 5%); recognised on the
14/// bar that confirms the right shoulder:
15///
16/// ```text
17/// head-and-shoulders top (bearish, -1):
18///   LeftShoulder(high) , Trough , Head(high) , Trough , RightShoulder(high)
19///   Head > both shoulders ; LeftShoulder ≈ RightShoulder ; Trough₁ ≈ Trough₂
20///
21/// inverse head-and-shoulders (bullish, +1):
22///   LeftShoulder(low) , Peak , Head(low) , Peak , RightShoulder(low)
23///   Head < both shoulders ; LeftShoulder ≈ RightShoulder ; Peak₁ ≈ Peak₂
24/// ```
25///
26/// The shoulders must match within `LEVEL_TOLERANCE` (3%) and the two neckline
27/// points within the same tolerance. Output is `-1.0` for a top, `+1.0` for an
28/// inverse, `0.0` otherwise; never `None`.
29#[derive(Debug, Clone)]
30pub struct HeadAndShoulders {
31    swing: SwingTracker,
32    has_emitted: bool,
33}
34
35impl HeadAndShoulders {
36    /// Construct a new Head-and-Shoulders detector.
37    pub const fn new() -> Self {
38        Self {
39            swing: SwingTracker::new(SWING_THRESHOLD, 5),
40            has_emitted: false,
41        }
42    }
43}
44
45impl Default for HeadAndShoulders {
46    fn default() -> Self {
47        Self::new()
48    }
49}
50
51impl Indicator for HeadAndShoulders {
52    type Input = Candle;
53    type Output = f64;
54
55    #[inline]
56    fn update(&mut self, candle: Candle) -> Option<f64> {
57        let advanced = self.swing.update(candle);
58        let pivots = self.swing.pivots();
59        // Too few pivots to form the shape at all: the indicator cannot
60        // judge yet, which is what `None` means.
61        if pivots.len() < 5 {
62            return None;
63        }
64        self.has_emitted = true;
65        // Armed, but this bar did not close a new pivot, so there is
66        // nothing new to match against.
67        if !advanced {
68            return Some(0.0);
69        }
70        let n = pivots.len();
71        let left_shoulder = pivots[n - 5];
72        let neck_1 = pivots[n - 4];
73        let head = pivots[n - 3];
74        let neck_2 = pivots[n - 2];
75        let right_shoulder = pivots[n - 1];
76
77        let shoulders_match =
78            approx_equal(left_shoulder.price, right_shoulder.price, LEVEL_TOLERANCE);
79        let neckline_flat = approx_equal(neck_1.price, neck_2.price, LEVEL_TOLERANCE);
80        let head_is_peak = head.price > left_shoulder.price && head.price > right_shoulder.price;
81        let head_is_trough = head.price < left_shoulder.price && head.price < right_shoulder.price;
82        let frame_matches = shoulders_match && neckline_flat;
83
84        if right_shoulder.direction > 0.0 {
85            // Head-and-shoulders top: head is the highest of the three highs.
86            if head_is_peak && frame_matches {
87                return Some(-1.0);
88            }
89        } else if head_is_trough && frame_matches {
90            // Inverse: head is the lowest of the three lows.
91            return Some(1.0);
92        }
93        Some(0.0)
94    }
95
96    fn reset(&mut self) {
97        self.swing.reset();
98        self.has_emitted = false;
99    }
100
101    #[inline]
102    fn warmup_period(&self) -> usize {
103        // Five confirmed pivots; the earliest confirmation of the fifth is bar 6.
104        6
105    }
106
107    #[inline]
108    fn is_ready(&self) -> bool {
109        self.has_emitted
110    }
111
112    #[inline]
113    fn name(&self) -> &'static str {
114        "HeadAndShoulders"
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121    use crate::indicators::pattern_swing::candles_for_pivots;
122    use crate::traits::BatchExt;
123
124    fn run(pivots: &[f64]) -> Vec<f64> {
125        let mut indicator = HeadAndShoulders::new();
126        candles_for_pivots(pivots)
127            .into_iter()
128            .filter_map(|c| indicator.update(c))
129            .collect()
130    }
131
132    #[test]
133    fn accessors_and_metadata() {
134        let indicator = HeadAndShoulders::new();
135        assert_eq!(indicator.name(), "HeadAndShoulders");
136        assert_eq!(indicator.warmup_period(), 6);
137        assert!(!indicator.is_ready());
138        assert!(!HeadAndShoulders::default().is_ready());
139    }
140
141    #[test]
142    fn head_and_shoulders_top_is_minus_one() {
143        // LS 100, trough 90, head 120, trough 92, RS 101.
144        let out = run(&[100.0, 90.0, 120.0, 92.0, 101.0]);
145        assert_eq!(*out.last().unwrap(), -1.0);
146        assert!(out[..out.len() - 1].iter().all(|&x| x == 0.0));
147    }
148
149    #[test]
150    fn inverse_head_and_shoulders_is_plus_one() {
151        // Lead high then LS 100, peak 110, head 80, peak 108, RS 101.
152        let out = run(&[130.0, 100.0, 110.0, 80.0, 108.0, 101.0]);
153        assert_eq!(*out.last().unwrap(), 1.0);
154    }
155
156    #[test]
157    fn mismatched_shoulders_do_not_trigger() {
158        // Right shoulder (115) far from left (100) → no pattern.
159        let out = run(&[100.0, 90.0, 130.0, 92.0, 115.0]);
160        assert_eq!(*out.last().unwrap(), 0.0);
161    }
162
163    #[test]
164    fn inverse_mismatched_shoulders_do_not_trigger() {
165        // Inverse shape (ends on a low) but the right shoulder (90) diverges from
166        // the left (100) → enters the inverse branch yet reports no pattern.
167        let out = run(&[130.0, 100.0, 110.0, 80.0, 108.0, 90.0]);
168        assert_eq!(*out.last().unwrap(), 0.0);
169    }
170
171    #[test]
172    fn equal_highs_without_taller_head_do_not_trigger() {
173        // Three equal highs (no dominant head) → not H&S (that is a triple top).
174        let out = run(&[120.0, 90.0, 120.0, 92.0, 120.0]);
175        assert_eq!(*out.last().unwrap(), 0.0);
176    }
177
178    #[test]
179    fn reset_clears_state() {
180        let mut indicator = HeadAndShoulders::new();
181        for c in candles_for_pivots(&[100.0, 90.0, 120.0]) {
182            let _ = indicator.update(c);
183        }
184        indicator.reset();
185        assert!(!indicator.is_ready());
186        let c = Candle::new(99.5, 100.0, 99.5, 99.5, 1.0, 0).unwrap();
187        assert_eq!(indicator.update(c), None);
188    }
189
190    #[test]
191    fn batch_equals_streaming() {
192        let candles = candles_for_pivots(&[100.0, 90.0, 120.0, 92.0, 101.0]);
193        let mut a = HeadAndShoulders::new();
194        let mut b = HeadAndShoulders::new();
195        assert_eq!(
196            a.batch(&candles),
197            candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
198        );
199    }
200}