Skip to main content

wickra_core/indicators/
true_range.rs

1//! True Range.
2
3use crate::ohlcv::Candle;
4use crate::traits::Indicator;
5
6/// True Range — the single-bar building block of every ATR-based indicator.
7///
8/// ```text
9/// TR = max( high − low, |high − close_prev|, |low − close_prev| )
10/// ```
11///
12/// True Range is the greatest of the bar's own range and the two gaps to the
13/// previous close, so it captures volatility that opens *between* bars rather
14/// than only within them. The first bar has no previous close and falls back
15/// to `high − low`. Where [`Atr`](crate::Atr) smooths this series, `TrueRange`
16/// exposes it raw, one value per bar.
17///
18/// # Example
19///
20/// ```
21/// use wickra_core::{Candle, Indicator, TrueRange};
22///
23/// let mut indicator = TrueRange::new();
24/// let mut last = None;
25/// for i in 0..80 {
26///     let base = 100.0 + f64::from(i);
27///     let candle =
28///         Candle::new(base, base + 2.0, base - 2.0, base + 1.0, 10.0, i64::from(i)).unwrap();
29///     last = indicator.update(candle);
30/// }
31/// assert!(last.is_some());
32/// ```
33#[derive(Debug, Clone, Default)]
34pub struct TrueRange {
35    prev_close: Option<f64>,
36    has_emitted: bool,
37}
38
39impl TrueRange {
40    /// Construct a new True Range indicator.
41    pub const fn new() -> Self {
42        Self {
43            prev_close: None,
44            has_emitted: false,
45        }
46    }
47}
48
49impl Indicator for TrueRange {
50    type Input = Candle;
51    type Output = f64;
52
53    #[inline]
54    fn update(&mut self, candle: Candle) -> Option<f64> {
55        let tr = candle.true_range(self.prev_close);
56        self.prev_close = Some(candle.close);
57        self.has_emitted = true;
58        Some(tr)
59    }
60
61    fn reset(&mut self) {
62        self.prev_close = None;
63        self.has_emitted = false;
64    }
65
66    #[inline]
67    fn warmup_period(&self) -> usize {
68        1
69    }
70
71    #[inline]
72    fn is_ready(&self) -> bool {
73        self.has_emitted
74    }
75
76    #[inline]
77    fn name(&self) -> &'static str {
78        "TrueRange"
79    }
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85    use crate::traits::BatchExt;
86    use approx::assert_relative_eq;
87
88    fn c(high: f64, low: f64, close: f64, ts: i64) -> Candle {
89        Candle::new(f64::midpoint(high, low), high, low, close, 1.0, ts).unwrap()
90    }
91
92    #[test]
93    fn reference_values() {
94        // Bar 1 has no previous close -> TR = high - low = 12 - 8 = 4.
95        // Bar 2: prev close 11, TR = max(10-9, |10-11|, |9-11|) = max(1, 1, 2) = 2.
96        let mut tr = TrueRange::new();
97        let out = tr.batch(&[c(12.0, 8.0, 11.0, 0), c(10.0, 9.0, 9.5, 1)]);
98        assert_relative_eq!(out[0].unwrap(), 4.0, epsilon = 1e-12);
99        assert_relative_eq!(out[1].unwrap(), 2.0, epsilon = 1e-12);
100    }
101
102    /// Cover the Indicator-impl `name` body (73-75).
103    #[test]
104    fn name_metadata() {
105        let tr = TrueRange::new();
106        assert_eq!(tr.name(), "TrueRange");
107    }
108
109    #[test]
110    fn emits_from_first_candle() {
111        let mut tr = TrueRange::new();
112        assert_eq!(tr.warmup_period(), 1);
113        assert!(!tr.is_ready());
114        assert!(tr.update(c(11.0, 9.0, 10.0, 0)).is_some());
115        assert!(tr.is_ready());
116    }
117
118    #[test]
119    fn never_negative() {
120        let candles: Vec<Candle> = (0..120)
121            .map(|i| {
122                let base = 100.0 + (i as f64 * 0.3).sin() * 5.0;
123                c(base + 1.0, base - 1.0, base, i)
124            })
125            .collect();
126        let mut tr = TrueRange::new();
127        for v in tr.batch(&candles).into_iter().flatten() {
128            assert!(v >= 0.0, "true range must be non-negative, got {v}");
129        }
130    }
131
132    #[test]
133    fn reset_clears_state() {
134        let mut tr = TrueRange::new();
135        tr.batch(&[c(12.0, 8.0, 10.0, 0), c(13.0, 9.0, 11.0, 1)]);
136        assert!(tr.is_ready());
137        tr.reset();
138        assert!(!tr.is_ready());
139        // After reset the next bar again has no previous close.
140        assert_relative_eq!(
141            tr.update(c(12.0, 8.0, 10.0, 0)).unwrap(),
142            4.0,
143            epsilon = 1e-12
144        );
145    }
146
147    #[test]
148    fn batch_equals_streaming() {
149        let candles: Vec<Candle> = (0..60)
150            .map(|i| {
151                let mid = 100.0 + (i as f64 * 0.3).sin() * 8.0;
152                c(mid + 1.5, mid - 1.5, mid + 0.5, i)
153            })
154            .collect();
155        let mut a = TrueRange::new();
156        let mut b = TrueRange::new();
157        assert_eq!(
158            a.batch(&candles),
159            candles.iter().map(|x| b.update(*x)).collect::<Vec<_>>()
160        );
161    }
162}