Skip to main content

wickra_core/indicators/
starc_bands.rs

1//! STARC Bands (Stoller Average Range Channel).
2
3use crate::error::{Error, Result};
4use crate::indicators::atr::Atr;
5use crate::indicators::sma::Sma;
6use crate::ohlcv::Candle;
7use crate::traits::Indicator;
8
9/// STARC Bands output.
10#[derive(Debug, Clone, Copy, PartialEq)]
11pub struct StarcBandsOutput {
12    /// Upper band: `middle + multiplier · ATR`.
13    pub upper: f64,
14    /// Middle band: SMA of close.
15    pub middle: f64,
16    /// Lower band: `middle − multiplier · ATR`.
17    pub lower: f64,
18}
19
20/// STARC Bands (Stoller Average Range Channel): a close-SMA centerline with
21/// bands sized by ATR.
22///
23/// ```text
24/// middle = SMA(close, sma_period)
25/// upper  = middle + multiplier · ATR(atr_period)
26/// lower  = middle − multiplier · ATR(atr_period)
27/// ```
28///
29/// STARC and [`Keltner`](crate::Keltner) share the same skeleton — moving
30/// average plus an ATR offset — but Keltner's centerline is an `EMA` of the
31/// typical price while STARC uses an `SMA` of the close. The SMA gives a
32/// flatter, less reactive midline that traders use to pick the larger swing
33/// targets; Stoller's reference parameters are `SMA(6)` over the close with
34/// `ATR(15)` and a multiplier of `2.0`.
35///
36/// # Example
37///
38/// ```
39/// use wickra_core::{Candle, Indicator, StarcBands};
40///
41/// let mut indicator = StarcBands::new(6, 15, 2.0).unwrap();
42/// let mut last = None;
43/// for i in 0..40 {
44///     let base = 100.0 + f64::from(i);
45///     let candle =
46///         Candle::new(base, base + 2.0, base - 2.0, base + 1.0, 10.0, i64::from(i)).unwrap();
47///     last = indicator.update(candle);
48/// }
49/// assert!(last.is_some());
50/// ```
51#[derive(Debug, Clone)]
52pub struct StarcBands {
53    sma: Sma,
54    atr: Atr,
55    multiplier: f64,
56    sma_period: usize,
57    atr_period: usize,
58}
59
60impl StarcBands {
61    /// # Errors
62    /// Returns [`Error::PeriodZero`] / [`Error::NonPositiveMultiplier`] on
63    /// invalid inputs.
64    pub fn new(sma_period: usize, atr_period: usize, multiplier: f64) -> Result<Self> {
65        if !multiplier.is_finite() || multiplier <= 0.0 {
66            return Err(Error::NonPositiveMultiplier);
67        }
68        Ok(Self {
69            sma: Sma::new(sma_period)?,
70            atr: Atr::new(atr_period)?,
71            multiplier,
72            sma_period,
73            atr_period,
74        })
75    }
76
77    /// Stoller's classic configuration: SMA(6), ATR(15), multiplier 2.0.
78    pub fn classic() -> Self {
79        Self::new(6, 15, 2.0).expect("classic STARC parameters are valid")
80    }
81
82    /// Configured `(sma_period, atr_period, multiplier)`.
83    pub const fn parameters(&self) -> (usize, usize, f64) {
84        (self.sma_period, self.atr_period, self.multiplier)
85    }
86}
87
88impl Indicator for StarcBands {
89    type Input = Candle;
90    type Output = StarcBandsOutput;
91
92    #[inline]
93    fn update(&mut self, candle: Candle) -> Option<StarcBandsOutput> {
94        // Feed both unconditionally so SMA and ATR warm up in parallel.
95        let mid = self.sma.update(candle.close);
96        let atr = self.atr.update(candle);
97        let (mid, atr) = (mid?, atr?);
98        Some(StarcBandsOutput {
99            upper: mid + self.multiplier * atr,
100            middle: mid,
101            lower: mid - self.multiplier * atr,
102        })
103    }
104
105    fn reset(&mut self) {
106        self.sma.reset();
107        self.atr.reset();
108    }
109
110    #[inline]
111    fn warmup_period(&self) -> usize {
112        self.sma_period.max(self.atr_period)
113    }
114
115    #[inline]
116    fn is_ready(&self) -> bool {
117        self.sma.is_ready() && self.atr.is_ready()
118    }
119
120    #[inline]
121    fn name(&self) -> &'static str {
122        "StarcBands"
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129    use crate::traits::BatchExt;
130    use approx::assert_relative_eq;
131
132    fn c(h: f64, l: f64, cl: f64) -> Candle {
133        Candle::new(cl, h, l, cl, 1.0, 0).unwrap()
134    }
135
136    #[test]
137    fn rejects_invalid_input() {
138        assert!(StarcBands::new(0, 14, 2.0).is_err());
139        assert!(StarcBands::new(6, 0, 2.0).is_err());
140        assert!(StarcBands::new(6, 14, 0.0).is_err());
141        assert!(StarcBands::new(6, 14, -1.0).is_err());
142        assert!(StarcBands::new(6, 14, f64::NAN).is_err());
143    }
144
145    #[test]
146    fn accessors_and_metadata() {
147        let s = StarcBands::new(6, 15, 2.0).unwrap();
148        let (sp, ap, m) = s.parameters();
149        assert_eq!(sp, 6);
150        assert_eq!(ap, 15);
151        assert_relative_eq!(m, 2.0, epsilon = 1e-12);
152        assert_eq!(s.warmup_period(), 15);
153        assert_eq!(s.name(), "StarcBands");
154    }
155
156    #[test]
157    fn flat_market_collapses_bands() {
158        let candles: Vec<Candle> = (0..50).map(|_| c(10.0, 10.0, 10.0)).collect();
159        let mut s = StarcBands::new(6, 15, 2.0).unwrap();
160        let last = s.batch(&candles).into_iter().flatten().last().unwrap();
161        assert_relative_eq!(last.upper, last.middle, epsilon = 1e-9);
162        assert_relative_eq!(last.lower, last.middle, epsilon = 1e-9);
163    }
164
165    #[test]
166    fn upper_above_middle_above_lower() {
167        let candles: Vec<Candle> = (0..80)
168            .map(|i| {
169                let m = 100.0 + (f64::from(i) * 0.2).sin() * 5.0;
170                c(m + 1.0, m - 1.0, m)
171            })
172            .collect();
173        let mut s = StarcBands::classic();
174        for o in s.batch(&candles).into_iter().flatten() {
175            assert!(o.upper >= o.middle);
176            assert!(o.middle >= o.lower);
177        }
178    }
179
180    #[test]
181    fn batch_equals_streaming() {
182        let candles: Vec<Candle> = (0..40)
183            .map(|i| c(f64::from(i) + 1.0, f64::from(i) - 1.0, f64::from(i)))
184            .collect();
185        let mut a = StarcBands::classic();
186        let mut b = StarcBands::classic();
187        assert_eq!(
188            a.batch(&candles),
189            candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
190        );
191    }
192
193    #[test]
194    fn reset_clears_state() {
195        let candles: Vec<Candle> = (0..30)
196            .map(|i| c(f64::from(i) + 1.0, f64::from(i) - 1.0, f64::from(i)))
197            .collect();
198        let mut s = StarcBands::classic();
199        s.batch(&candles);
200        assert!(s.is_ready());
201        s.reset();
202        assert!(!s.is_ready());
203        assert_eq!(s.update(candles[0]), None);
204    }
205
206    /// STARC must equal feeding independent SMA(close) and ATR siblings and
207    /// combining them.
208    #[test]
209    fn matches_independent_sma_and_atr() {
210        let candles: Vec<Candle> = (0..60)
211            .map(|i| {
212                let m = 100.0 + (f64::from(i) * 0.2).sin() * 5.0;
213                c(m + 1.5, m - 1.5, m)
214            })
215            .collect();
216        let mut s = StarcBands::new(6, 15, 2.0).unwrap();
217        let mut sma = Sma::new(6).unwrap();
218        let mut atr = Atr::new(15).unwrap();
219        for candle in &candles {
220            let got = s.update(*candle);
221            let mid = sma.update(candle.close);
222            let a = atr.update(*candle);
223            if let (Some(m), Some(av)) = (mid, a) {
224                let o = got.expect("STARC emits once both ready");
225                assert_relative_eq!(o.middle, m, epsilon = 1e-9);
226                assert_relative_eq!(o.upper, m + 2.0 * av, epsilon = 1e-9);
227                assert_relative_eq!(o.lower, m - 2.0 * av, epsilon = 1e-9);
228            } else {
229                assert!(got.is_none());
230            }
231        }
232    }
233}