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    fn update(&mut self, candle: Candle) -> Option<f64> {
56        self.has_emitted = true;
57        if !self.swing.update(candle) {
58            return Some(0.0);
59        }
60        let pivots = self.swing.pivots();
61        if pivots.len() < 5 {
62            return Some(0.0);
63        }
64        let n = pivots.len();
65        let left_shoulder = pivots[n - 5];
66        let neck_1 = pivots[n - 4];
67        let head = pivots[n - 3];
68        let neck_2 = pivots[n - 2];
69        let right_shoulder = pivots[n - 1];
70
71        let shoulders_match =
72            approx_equal(left_shoulder.price, right_shoulder.price, LEVEL_TOLERANCE);
73        let neckline_flat = approx_equal(neck_1.price, neck_2.price, LEVEL_TOLERANCE);
74        let head_is_peak = head.price > left_shoulder.price && head.price > right_shoulder.price;
75        let head_is_trough = head.price < left_shoulder.price && head.price < right_shoulder.price;
76        let frame_matches = shoulders_match && neckline_flat;
77
78        if right_shoulder.direction > 0.0 {
79            // Head-and-shoulders top: head is the highest of the three highs.
80            if head_is_peak && frame_matches {
81                return Some(-1.0);
82            }
83        } else if head_is_trough && frame_matches {
84            // Inverse: head is the lowest of the three lows.
85            return Some(1.0);
86        }
87        Some(0.0)
88    }
89
90    fn reset(&mut self) {
91        self.swing.reset();
92        self.has_emitted = false;
93    }
94
95    fn warmup_period(&self) -> usize {
96        // Five confirmed pivots; the earliest confirmation of the fifth is bar 6.
97        6
98    }
99
100    fn is_ready(&self) -> bool {
101        self.has_emitted
102    }
103
104    fn name(&self) -> &'static str {
105        "HeadAndShoulders"
106    }
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112    use crate::indicators::pattern_swing::candles_for_pivots;
113    use crate::traits::BatchExt;
114
115    fn run(pivots: &[f64]) -> Vec<f64> {
116        let mut indicator = HeadAndShoulders::new();
117        candles_for_pivots(pivots)
118            .into_iter()
119            .map(|c| indicator.update(c).unwrap())
120            .collect()
121    }
122
123    #[test]
124    fn accessors_and_metadata() {
125        let indicator = HeadAndShoulders::new();
126        assert_eq!(indicator.name(), "HeadAndShoulders");
127        assert_eq!(indicator.warmup_period(), 6);
128        assert!(!indicator.is_ready());
129        assert!(!HeadAndShoulders::default().is_ready());
130    }
131
132    #[test]
133    fn head_and_shoulders_top_is_minus_one() {
134        // LS 100, trough 90, head 120, trough 92, RS 101.
135        let out = run(&[100.0, 90.0, 120.0, 92.0, 101.0]);
136        assert_eq!(*out.last().unwrap(), -1.0);
137        assert!(out[..out.len() - 1].iter().all(|&x| x == 0.0));
138    }
139
140    #[test]
141    fn inverse_head_and_shoulders_is_plus_one() {
142        // Lead high then LS 100, peak 110, head 80, peak 108, RS 101.
143        let out = run(&[130.0, 100.0, 110.0, 80.0, 108.0, 101.0]);
144        assert_eq!(*out.last().unwrap(), 1.0);
145    }
146
147    #[test]
148    fn mismatched_shoulders_do_not_trigger() {
149        // Right shoulder (115) far from left (100) → no pattern.
150        let out = run(&[100.0, 90.0, 130.0, 92.0, 115.0]);
151        assert_eq!(*out.last().unwrap(), 0.0);
152    }
153
154    #[test]
155    fn inverse_mismatched_shoulders_do_not_trigger() {
156        // Inverse shape (ends on a low) but the right shoulder (90) diverges from
157        // the left (100) → enters the inverse branch yet reports no pattern.
158        let out = run(&[130.0, 100.0, 110.0, 80.0, 108.0, 90.0]);
159        assert_eq!(*out.last().unwrap(), 0.0);
160    }
161
162    #[test]
163    fn equal_highs_without_taller_head_do_not_trigger() {
164        // Three equal highs (no dominant head) → not H&S (that is a triple top).
165        let out = run(&[120.0, 90.0, 120.0, 92.0, 120.0]);
166        assert_eq!(*out.last().unwrap(), 0.0);
167    }
168
169    #[test]
170    fn reset_clears_state() {
171        let mut indicator = HeadAndShoulders::new();
172        for c in candles_for_pivots(&[100.0, 90.0, 120.0]) {
173            let _ = indicator.update(c);
174        }
175        indicator.reset();
176        assert!(!indicator.is_ready());
177        let c = Candle::new(99.5, 100.0, 99.5, 99.5, 1.0, 0).unwrap();
178        assert_eq!(indicator.update(c), Some(0.0));
179    }
180
181    #[test]
182    fn batch_equals_streaming() {
183        let candles = candles_for_pivots(&[100.0, 90.0, 120.0, 92.0, 101.0]);
184        let mut a = HeadAndShoulders::new();
185        let mut b = HeadAndShoulders::new();
186        assert_eq!(
187            a.batch(&candles),
188            candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
189        );
190    }
191}