Skip to main content

wickra_core/indicators/
triangle.rs

1//! Triangle (ascending / descending / symmetrical) chart pattern.
2
3use crate::indicators::pattern_swing::{
4    approx_equal, recent_legs, SwingTracker, LEVEL_TOLERANCE, SWING_THRESHOLD,
5};
6use crate::ohlcv::Candle;
7use crate::traits::Indicator;
8
9/// Triangle — a consolidation pattern bounded by two converging trendlines,
10/// detected from the two most recent swing highs and lows.
11///
12/// Built on confirmed swing pivots (`SWING_THRESHOLD` = 5%); evaluated on every
13/// bar that confirms a new pivot once four pivots exist:
14///
15/// ```text
16/// ascending   : flat highs   + rising lows    → +1 (bullish bias)
17/// descending  : falling highs + flat lows      → -1 (bearish bias)
18/// symmetrical : falling highs + rising lows     → +1 if the last pivot is a low
19///                                                 (an up-bounce), else -1
20/// ```
21///
22/// "Flat" means the two highs (or lows) are within `LEVEL_TOLERANCE` (3%) of
23/// each other; "rising"/"falling" means they differ by more than that tolerance.
24/// The symmetrical case is directionally neutral, so its sign follows the
25/// momentum of the most recently confirmed swing. Output is `+1.0` / `-1.0` /
26/// `0.0`; never `None`.
27#[derive(Debug, Clone)]
28pub struct Triangle {
29    swing: SwingTracker,
30    has_emitted: bool,
31}
32
33impl Triangle {
34    /// Construct a new Triangle detector.
35    pub const fn new() -> Self {
36        Self {
37            swing: SwingTracker::new(SWING_THRESHOLD, 4),
38            has_emitted: false,
39        }
40    }
41}
42
43impl Default for Triangle {
44    fn default() -> Self {
45        Self::new()
46    }
47}
48
49impl Indicator for Triangle {
50    type Input = Candle;
51    type Output = f64;
52
53    #[inline]
54    fn update(&mut self, candle: Candle) -> Option<f64> {
55        let advanced = self.swing.update(candle);
56        let pivots = self.swing.pivots();
57        // Too few pivots to form the shape at all: the indicator cannot
58        // judge yet, which is what `None` means.
59        if pivots.len() < 4 {
60            return None;
61        }
62        self.has_emitted = true;
63        // Armed, but this bar did not close a new pivot, so there is
64        // nothing new to match against.
65        if !advanced {
66            return Some(0.0);
67        }
68        let (high_old, high_new, low_old, low_new) = recent_legs(pivots);
69        let flat_highs = approx_equal(high_old, high_new, LEVEL_TOLERANCE);
70        let flat_lows = approx_equal(low_old, low_new, LEVEL_TOLERANCE);
71        let rising_lows = low_new > low_old * (1.0 + LEVEL_TOLERANCE);
72        let falling_highs = high_new < high_old * (1.0 - LEVEL_TOLERANCE);
73        let last_is_high = pivots[pivots.len() - 1].direction > 0.0;
74
75        if flat_highs && rising_lows {
76            return Some(1.0); // ascending
77        }
78        if falling_highs && flat_lows {
79            return Some(-1.0); // descending
80        }
81        if falling_highs && rising_lows {
82            // symmetrical: lean with the latest swing's momentum.
83            return Some(if last_is_high { -1.0 } else { 1.0 });
84        }
85        Some(0.0)
86    }
87
88    fn reset(&mut self) {
89        self.swing.reset();
90        self.has_emitted = false;
91    }
92
93    #[inline]
94    fn warmup_period(&self) -> usize {
95        // Four confirmed pivots; the earliest confirmation of the fourth is bar 5.
96        5
97    }
98
99    #[inline]
100    fn is_ready(&self) -> bool {
101        self.has_emitted
102    }
103
104    #[inline]
105    fn name(&self) -> &'static str {
106        "Triangle"
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113    use crate::indicators::pattern_swing::candles_for_pivots;
114    use crate::traits::BatchExt;
115
116    fn run(pivots: &[f64]) -> Vec<f64> {
117        let mut indicator = Triangle::new();
118        candles_for_pivots(pivots)
119            .into_iter()
120            .filter_map(|c| indicator.update(c))
121            .collect()
122    }
123
124    #[test]
125    fn accessors_and_metadata() {
126        let indicator = Triangle::new();
127        assert_eq!(indicator.name(), "Triangle");
128        assert_eq!(indicator.warmup_period(), 5);
129        assert!(!indicator.is_ready());
130        assert!(!Triangle::default().is_ready());
131    }
132
133    #[test]
134    fn ascending_triangle_is_plus_one() {
135        // Flat highs (120, 120), rising lows (100 → 110).
136        let out = run(&[130.0, 100.0, 120.0, 110.0, 120.0]);
137        assert_eq!(*out.last().unwrap(), 1.0);
138    }
139
140    #[test]
141    fn descending_triangle_is_minus_one() {
142        // Falling highs (120 → 110), flat lows (100, 99).
143        let out = run(&[120.0, 100.0, 110.0, 99.0]);
144        assert_eq!(*out.last().unwrap(), -1.0);
145    }
146
147    #[test]
148    fn symmetrical_triangle_ending_low_is_plus_one() {
149        // Falling highs (120 → 113), rising lows (100 → 106); last pivot a low.
150        let out = run(&[120.0, 100.0, 113.0, 106.0]);
151        assert_eq!(*out.last().unwrap(), 1.0);
152    }
153
154    #[test]
155    fn symmetrical_triangle_ending_high_is_minus_one() {
156        // Same convergence but ending on a high pivot.
157        let out = run(&[130.0, 100.0, 120.0, 106.0, 113.0]);
158        assert_eq!(*out.last().unwrap(), -1.0);
159    }
160
161    #[test]
162    fn expanding_swings_are_not_a_triangle() {
163        // Rising highs and falling lows (broadening) → no converging triangle.
164        let out = run(&[110.0, 100.0, 130.0, 80.0]);
165        assert_eq!(*out.last().unwrap(), 0.0);
166    }
167
168    #[test]
169    fn reset_clears_state() {
170        let mut indicator = Triangle::new();
171        for c in candles_for_pivots(&[130.0, 100.0, 120.0]) {
172            let _ = indicator.update(c);
173        }
174        indicator.reset();
175        assert!(!indicator.is_ready());
176        let c = Candle::new(99.5, 100.0, 99.5, 99.5, 1.0, 0).unwrap();
177        assert_eq!(indicator.update(c), None);
178    }
179
180    #[test]
181    fn batch_equals_streaming() {
182        let candles = candles_for_pivots(&[130.0, 100.0, 120.0, 110.0, 120.0]);
183        let mut a = Triangle::new();
184        let mut b = Triangle::new();
185        assert_eq!(
186            a.batch(&candles),
187            candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
188        );
189    }
190}