Skip to main content

wickra_core/indicators/
chandelier_exit.rs

1//! Chandelier Exit.
2
3use std::collections::VecDeque;
4
5use crate::error::{Error, Result};
6use crate::indicators::atr::Atr;
7use crate::ohlcv::Candle;
8use crate::traits::Indicator;
9
10/// Chandelier Exit output: the long-side and short-side trailing stops.
11#[derive(Debug, Clone, Copy, PartialEq)]
12pub struct ChandelierExitOutput {
13    /// Long-position stop: `highest_high − multiplier · ATR`.
14    pub long_stop: f64,
15    /// Short-position stop: `lowest_low + multiplier · ATR`.
16    pub short_stop: f64,
17}
18
19/// Chandelier Exit — Chuck LeBeau's ATR trailing stop, hung from the highest
20/// high (for longs) or the lowest low (for shorts) of the lookback window.
21///
22/// ```text
23/// long_stop  = highest_high(period) − multiplier · ATR(period)
24/// short_stop = lowest_low(period)   + multiplier · ATR(period)
25/// ```
26///
27/// A long position is exited when price closes below `long_stop`; a short
28/// when it closes above `short_stop`. Because the stop hangs a fixed number
29/// of ATRs off the extreme of the window — like a chandelier off a ceiling —
30/// it follows price up but never loosens. LeBeau's classic configuration is a
31/// `22`-bar window with a `3.0` multiplier.
32///
33/// # Example
34///
35/// ```
36/// use wickra_core::{Candle, Indicator, ChandelierExit};
37///
38/// let mut indicator = ChandelierExit::new(22, 3.0).unwrap();
39/// let mut last = None;
40/// for i in 0..80 {
41///     let base = 100.0 + f64::from(i);
42///     let candle =
43///         Candle::new(base, base + 2.0, base - 2.0, base + 1.0, 10.0, i64::from(i)).unwrap();
44///     last = indicator.update(candle);
45/// }
46/// assert!(last.is_some());
47/// ```
48#[derive(Debug, Clone)]
49pub struct ChandelierExit {
50    period: usize,
51    multiplier: f64,
52    atr: Atr,
53    highs: VecDeque<f64>,
54    lows: VecDeque<f64>,
55}
56
57impl ChandelierExit {
58    /// Construct a Chandelier Exit with an explicit window and band multiplier.
59    ///
60    /// # Errors
61    /// Returns [`Error::PeriodZero`] if `period == 0` and
62    /// [`Error::NonPositiveMultiplier`] if `multiplier` is not strictly
63    /// positive and finite.
64    pub fn new(period: usize, multiplier: f64) -> Result<Self> {
65        if !multiplier.is_finite() || multiplier <= 0.0 {
66            return Err(Error::NonPositiveMultiplier);
67        }
68        Ok(Self {
69            period,
70            multiplier,
71            atr: Atr::new(period)?,
72            highs: VecDeque::with_capacity(period),
73            lows: VecDeque::with_capacity(period),
74        })
75    }
76
77    /// LeBeau's classic configuration: a `22`-bar window, `3.0` multiplier.
78    pub fn classic() -> Self {
79        Self::new(22, 3.0).expect("classic Chandelier Exit params are valid")
80    }
81
82    /// Configured `(period, multiplier)`.
83    pub const fn params(&self) -> (usize, f64) {
84        (self.period, self.multiplier)
85    }
86}
87
88impl Indicator for ChandelierExit {
89    type Input = Candle;
90    type Output = ChandelierExitOutput;
91
92    fn update(&mut self, candle: Candle) -> Option<ChandelierExitOutput> {
93        let atr = self.atr.update(candle);
94        if self.highs.len() == self.period {
95            self.highs.pop_front();
96            self.lows.pop_front();
97        }
98        self.highs.push_back(candle.high);
99        self.lows.push_back(candle.low);
100        if self.highs.len() < self.period {
101            return None;
102        }
103        // ATR(period) becomes ready on exactly the candle that fills the
104        // highest-high / lowest-low window, so this never discards a value.
105        let atr = atr?;
106        let highest = self.highs.iter().copied().fold(f64::NEG_INFINITY, f64::max);
107        let lowest = self.lows.iter().copied().fold(f64::INFINITY, f64::min);
108        Some(ChandelierExitOutput {
109            long_stop: highest - self.multiplier * atr,
110            short_stop: lowest + self.multiplier * atr,
111        })
112    }
113
114    fn reset(&mut self) {
115        self.atr.reset();
116        self.highs.clear();
117        self.lows.clear();
118    }
119
120    fn warmup_period(&self) -> usize {
121        self.period
122    }
123
124    fn is_ready(&self) -> bool {
125        self.highs.len() == self.period
126    }
127
128    fn name(&self) -> &'static str {
129        "ChandelierExit"
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136    use crate::traits::BatchExt;
137    use approx::assert_relative_eq;
138
139    fn c(high: f64, low: f64, close: f64, ts: i64) -> Candle {
140        Candle::new(f64::midpoint(high, low), high, low, close, 1.0, ts).unwrap()
141    }
142
143    #[test]
144    fn reference_values_flat_market() {
145        // Flat candles H=11, L=9, C=10 -> TR=2 -> ATR=2; HH=11, LL=9.
146        // long_stop  = 11 - 3·2 = 5;  short_stop = 9 + 3·2 = 15.
147        let candles: Vec<Candle> = (0..20).map(|i| c(11.0, 9.0, 10.0, i)).collect();
148        let mut ce = ChandelierExit::new(5, 3.0).unwrap();
149        let last = ce.batch(&candles).into_iter().flatten().last().unwrap();
150        assert_relative_eq!(last.long_stop, 5.0, epsilon = 1e-12);
151        assert_relative_eq!(last.short_stop, 15.0, epsilon = 1e-12);
152    }
153
154    #[test]
155    fn long_stop_below_highest_short_stop_above_lowest() {
156        let candles: Vec<Candle> = (0..120)
157            .map(|i| {
158                let mid = 100.0 + (i as f64 * 0.2).sin() * 9.0;
159                c(mid + 1.5, mid - 1.5, mid + 0.4, i)
160            })
161            .collect();
162        let mut ce = ChandelierExit::classic();
163        for (i, o) in ce.batch(&candles).into_iter().enumerate() {
164            if let Some(o) = o {
165                // The window's extremes bound the stops from one side.
166                let win = &candles[i + 1 - 22..=i];
167                let hh = win.iter().map(|c| c.high).fold(f64::NEG_INFINITY, f64::max);
168                let ll = win.iter().map(|c| c.low).fold(f64::INFINITY, f64::min);
169                assert!(o.long_stop <= hh + 1e-9);
170                assert!(o.short_stop >= ll - 1e-9);
171            }
172        }
173    }
174
175    #[test]
176    fn first_emission_matches_warmup_period() {
177        let candles: Vec<Candle> = (0..20)
178            .map(|i| {
179                let base = 100.0 + i as f64;
180                c(base + 1.0, base - 1.0, base, i)
181            })
182            .collect();
183        let mut ce = ChandelierExit::new(8, 3.0).unwrap();
184        let out = ce.batch(&candles);
185        assert_eq!(ce.warmup_period(), 8);
186        for (i, v) in out.iter().enumerate().take(7) {
187            assert!(v.is_none(), "index {i} must be None during warmup");
188        }
189        assert!(out[7].is_some(), "first value lands at warmup_period - 1");
190    }
191
192    #[test]
193    fn rejects_invalid_params() {
194        assert!(ChandelierExit::new(0, 3.0).is_err());
195        assert!(ChandelierExit::new(22, 0.0).is_err());
196        assert!(ChandelierExit::new(22, -1.0).is_err());
197        assert!(ChandelierExit::new(22, f64::NAN).is_err());
198    }
199
200    /// Cover the const accessor `params` (83-85) and the Indicator-impl
201    /// `name` body (128-130). `warmup_period` is exercised elsewhere.
202    #[test]
203    fn accessors_and_metadata() {
204        let ce = ChandelierExit::new(22, 3.0).unwrap();
205        let (p, m) = ce.params();
206        assert_eq!(p, 22);
207        assert!((m - 3.0).abs() < 1e-12);
208        assert_eq!(ce.name(), "ChandelierExit");
209    }
210
211    #[test]
212    fn reset_clears_state() {
213        let candles: Vec<Candle> = (0..40)
214            .map(|i| {
215                let base = 100.0 + i as f64;
216                c(base + 1.0, base - 1.0, base, i)
217            })
218            .collect();
219        let mut ce = ChandelierExit::classic();
220        ce.batch(&candles);
221        assert!(ce.is_ready());
222        ce.reset();
223        assert!(!ce.is_ready());
224        assert_eq!(ce.update(candles[0]), None);
225    }
226
227    #[test]
228    fn batch_equals_streaming() {
229        let candles: Vec<Candle> = (0..80)
230            .map(|i| {
231                let mid = 100.0 + (i as f64 * 0.3).sin() * 8.0;
232                c(mid + 1.5, mid - 1.5, mid + 0.5, i)
233            })
234            .collect();
235        let mut a = ChandelierExit::classic();
236        let mut b = ChandelierExit::classic();
237        assert_eq!(
238            a.batch(&candles),
239            candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
240        );
241    }
242}