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    #[inline]
93    fn update(&mut self, candle: Candle) -> Option<ChandelierExitOutput> {
94        let atr = self.atr.update(candle);
95        if self.highs.len() == self.period {
96            self.highs.pop_front();
97            self.lows.pop_front();
98        }
99        self.highs.push_back(candle.high);
100        self.lows.push_back(candle.low);
101        if self.highs.len() < self.period {
102            return None;
103        }
104        // ATR(period) becomes ready on exactly the candle that fills the
105        // highest-high / lowest-low window, so this never discards a value.
106        let atr = atr?;
107        let highest = self.highs.iter().copied().fold(f64::NEG_INFINITY, f64::max);
108        let lowest = self.lows.iter().copied().fold(f64::INFINITY, f64::min);
109        Some(ChandelierExitOutput {
110            long_stop: highest - self.multiplier * atr,
111            short_stop: lowest + self.multiplier * atr,
112        })
113    }
114
115    fn reset(&mut self) {
116        self.atr.reset();
117        self.highs.clear();
118        self.lows.clear();
119    }
120
121    #[inline]
122    fn warmup_period(&self) -> usize {
123        self.period
124    }
125
126    #[inline]
127    fn is_ready(&self) -> bool {
128        self.highs.len() == self.period
129    }
130
131    #[inline]
132    fn name(&self) -> &'static str {
133        "ChandelierExit"
134    }
135}
136
137#[cfg(test)]
138mod tests {
139    use super::*;
140    use crate::traits::BatchExt;
141    use approx::assert_relative_eq;
142
143    fn c(high: f64, low: f64, close: f64, ts: i64) -> Candle {
144        Candle::new(f64::midpoint(high, low), high, low, close, 1.0, ts).unwrap()
145    }
146
147    #[test]
148    fn reference_values_flat_market() {
149        // Flat candles H=11, L=9, C=10 -> TR=2 -> ATR=2; HH=11, LL=9.
150        // long_stop  = 11 - 3·2 = 5;  short_stop = 9 + 3·2 = 15.
151        let candles: Vec<Candle> = (0..20).map(|i| c(11.0, 9.0, 10.0, i)).collect();
152        let mut ce = ChandelierExit::new(5, 3.0).unwrap();
153        let last = ce.batch(&candles).into_iter().flatten().last().unwrap();
154        assert_relative_eq!(last.long_stop, 5.0, epsilon = 1e-12);
155        assert_relative_eq!(last.short_stop, 15.0, epsilon = 1e-12);
156    }
157
158    #[test]
159    fn long_stop_below_highest_short_stop_above_lowest() {
160        let candles: Vec<Candle> = (0..120)
161            .map(|i| {
162                let mid = 100.0 + (i as f64 * 0.2).sin() * 9.0;
163                c(mid + 1.5, mid - 1.5, mid + 0.4, i)
164            })
165            .collect();
166        let mut ce = ChandelierExit::classic();
167        for (i, o) in ce.batch(&candles).into_iter().enumerate() {
168            if let Some(o) = o {
169                // The window's extremes bound the stops from one side.
170                let win = &candles[i + 1 - 22..=i];
171                let hh = win.iter().map(|c| c.high).fold(f64::NEG_INFINITY, f64::max);
172                let ll = win.iter().map(|c| c.low).fold(f64::INFINITY, f64::min);
173                assert!(o.long_stop <= hh + 1e-9);
174                assert!(o.short_stop >= ll - 1e-9);
175            }
176        }
177    }
178
179    #[test]
180    fn first_emission_matches_warmup_period() {
181        let candles: Vec<Candle> = (0..20)
182            .map(|i| {
183                let base = 100.0 + i as f64;
184                c(base + 1.0, base - 1.0, base, i)
185            })
186            .collect();
187        let mut ce = ChandelierExit::new(8, 3.0).unwrap();
188        let out = ce.batch(&candles);
189        assert_eq!(ce.warmup_period(), 8);
190        for (i, v) in out.iter().enumerate().take(7) {
191            assert!(v.is_none(), "index {i} must be None during warmup");
192        }
193        assert!(out[7].is_some(), "first value lands at warmup_period - 1");
194    }
195
196    #[test]
197    fn rejects_invalid_params() {
198        assert!(ChandelierExit::new(0, 3.0).is_err());
199        assert!(ChandelierExit::new(22, 0.0).is_err());
200        assert!(ChandelierExit::new(22, -1.0).is_err());
201        assert!(ChandelierExit::new(22, f64::NAN).is_err());
202    }
203
204    /// Cover the const accessor `params` (83-85) and the Indicator-impl
205    /// `name` body (128-130). `warmup_period` is exercised elsewhere.
206    #[test]
207    fn accessors_and_metadata() {
208        let ce = ChandelierExit::new(22, 3.0).unwrap();
209        let (p, m) = ce.params();
210        assert_eq!(p, 22);
211        assert!((m - 3.0).abs() < 1e-12);
212        assert_eq!(ce.name(), "ChandelierExit");
213    }
214
215    #[test]
216    fn reset_clears_state() {
217        let candles: Vec<Candle> = (0..40)
218            .map(|i| {
219                let base = 100.0 + i as f64;
220                c(base + 1.0, base - 1.0, base, i)
221            })
222            .collect();
223        let mut ce = ChandelierExit::classic();
224        ce.batch(&candles);
225        assert!(ce.is_ready());
226        ce.reset();
227        assert!(!ce.is_ready());
228        assert_eq!(ce.update(candles[0]), None);
229    }
230
231    #[test]
232    fn batch_equals_streaming() {
233        let candles: Vec<Candle> = (0..80)
234            .map(|i| {
235                let mid = 100.0 + (i as f64 * 0.3).sin() * 8.0;
236                c(mid + 1.5, mid - 1.5, mid + 0.5, i)
237            })
238            .collect();
239        let mut a = ChandelierExit::classic();
240        let mut b = ChandelierExit::classic();
241        assert_eq!(
242            a.batch(&candles),
243            candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
244        );
245    }
246}