nautilus_indicators/average/
rma.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Posei Systems Pty Ltd. All rights reserved.
3//  https://poseitrader.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::fmt::Display;
17
18use nautilus_model::{
19    data::{Bar, QuoteTick, TradeTick},
20    enums::PriceType,
21};
22
23use crate::indicator::{Indicator, MovingAverage};
24
25#[repr(C)]
26#[derive(Debug)]
27#[cfg_attr(
28    feature = "python",
29    pyo3::pyclass(module = "posei_trader.core.nautilus_pyo3.indicators")
30)]
31pub struct WilderMovingAverage {
32    pub period: usize,
33    pub price_type: PriceType,
34    pub alpha: f64,
35    pub value: f64,
36    pub count: usize,
37    pub initialized: bool,
38    has_inputs: bool,
39}
40
41impl Display for WilderMovingAverage {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        write!(f, "{}({})", self.name(), self.period)
44    }
45}
46
47impl Indicator for WilderMovingAverage {
48    fn name(&self) -> String {
49        stringify!(WilderMovingAverage).to_string()
50    }
51
52    fn has_inputs(&self) -> bool {
53        self.has_inputs
54    }
55    fn initialized(&self) -> bool {
56        self.initialized
57    }
58
59    fn handle_quote(&mut self, quote: &QuoteTick) {
60        self.update_raw(quote.extract_price(self.price_type).into());
61    }
62
63    fn handle_trade(&mut self, t: &TradeTick) {
64        self.update_raw((&t.price).into());
65    }
66
67    fn handle_bar(&mut self, b: &Bar) {
68        self.update_raw((&b.close).into());
69    }
70
71    fn reset(&mut self) {
72        self.value = 0.0;
73        self.count = 0;
74        self.has_inputs = false;
75        self.initialized = false;
76    }
77}
78
79impl WilderMovingAverage {
80    /// Creates a new [`WilderMovingAverage`] instance.
81    ///
82    /// # Panics
83    ///
84    /// Panics if `period` is not positive (> 0).
85    #[must_use]
86    pub fn new(period: usize, price_type: Option<PriceType>) -> Self {
87        // The Wilder Moving Average is The Wilder's Moving Average is simply
88        // an Exponential Moving Average (EMA) with a modified alpha.
89        // alpha = 1 / period
90        assert!(
91            period > 0,
92            "WilderMovingAverage: period must be > 0 (received {period})"
93        );
94        Self {
95            period,
96            price_type: price_type.unwrap_or(PriceType::Last),
97            alpha: 1.0 / period as f64,
98            value: 0.0,
99            count: 0,
100            initialized: false,
101            has_inputs: false,
102        }
103    }
104}
105
106impl MovingAverage for WilderMovingAverage {
107    fn value(&self) -> f64 {
108        self.value
109    }
110    fn count(&self) -> usize {
111        self.count
112    }
113
114    fn update_raw(&mut self, price: f64) {
115        if !self.has_inputs {
116            self.has_inputs = true;
117            self.value = price;
118            self.count = 1;
119            self.initialized = self.count >= self.period;
120            return;
121        }
122
123        self.value = self.alpha.mul_add(price, (1.0 - self.alpha) * self.value);
124        self.count += 1;
125        if !self.initialized && self.count >= self.period {
126            self.initialized = true;
127        }
128    }
129}
130
131////////////////////////////////////////////////////////////////////////////////
132// Tests
133////////////////////////////////////////////////////////////////////////////////
134#[cfg(test)]
135mod tests {
136    use nautilus_model::{
137        data::{Bar, QuoteTick, TradeTick},
138        enums::PriceType,
139    };
140    use rstest::rstest;
141
142    use crate::{
143        average::rma::WilderMovingAverage,
144        indicator::{Indicator, MovingAverage},
145        stubs::*,
146    };
147
148    #[rstest]
149    fn test_rma_initialized(indicator_rma_10: WilderMovingAverage) {
150        let rma = indicator_rma_10;
151        let display_str = format!("{rma}");
152        assert_eq!(display_str, "WilderMovingAverage(10)");
153        assert_eq!(rma.period, 10);
154        assert_eq!(rma.price_type, PriceType::Mid);
155        assert_eq!(rma.alpha, 0.1);
156        assert!(!rma.initialized);
157    }
158
159    #[rstest]
160    #[should_panic(expected = "WilderMovingAverage: period must be > 0")]
161    fn test_new_with_zero_period_panics() {
162        let _ = WilderMovingAverage::new(0, None);
163    }
164
165    #[rstest]
166    fn test_one_value_input(indicator_rma_10: WilderMovingAverage) {
167        let mut rma = indicator_rma_10;
168        rma.update_raw(1.0);
169        assert_eq!(rma.count, 1);
170        assert_eq!(rma.value, 1.0);
171    }
172
173    #[rstest]
174    fn test_rma_update_raw(indicator_rma_10: WilderMovingAverage) {
175        let mut rma = indicator_rma_10;
176        rma.update_raw(1.0);
177        rma.update_raw(2.0);
178        rma.update_raw(3.0);
179        rma.update_raw(4.0);
180        rma.update_raw(5.0);
181        rma.update_raw(6.0);
182        rma.update_raw(7.0);
183        rma.update_raw(8.0);
184        rma.update_raw(9.0);
185        rma.update_raw(10.0);
186
187        assert!(rma.has_inputs());
188        assert!(rma.initialized());
189        assert_eq!(rma.count, 10);
190        assert_eq!(rma.value, 4.486_784_401);
191    }
192
193    #[rstest]
194    fn test_reset(indicator_rma_10: WilderMovingAverage) {
195        let mut rma = indicator_rma_10;
196        rma.update_raw(1.0);
197        assert_eq!(rma.count, 1);
198        rma.reset();
199        assert_eq!(rma.count, 0);
200        assert_eq!(rma.value, 0.0);
201        assert!(!rma.initialized);
202    }
203
204    #[rstest]
205    fn test_handle_quote_tick_single(indicator_rma_10: WilderMovingAverage, stub_quote: QuoteTick) {
206        let mut rma = indicator_rma_10;
207        rma.handle_quote(&stub_quote);
208        assert!(rma.has_inputs());
209        assert_eq!(rma.value, 1501.0);
210    }
211
212    #[rstest]
213    fn test_handle_quote_tick_multi(mut indicator_rma_10: WilderMovingAverage) {
214        let tick1 = stub_quote("1500.0", "1502.0");
215        let tick2 = stub_quote("1502.0", "1504.0");
216
217        indicator_rma_10.handle_quote(&tick1);
218        indicator_rma_10.handle_quote(&tick2);
219        assert_eq!(indicator_rma_10.count, 2);
220        assert_eq!(indicator_rma_10.value, 1_501.2);
221    }
222
223    #[rstest]
224    fn test_handle_trade_tick(indicator_rma_10: WilderMovingAverage, stub_trade: TradeTick) {
225        let mut rma = indicator_rma_10;
226        rma.handle_trade(&stub_trade);
227        assert!(rma.has_inputs());
228        assert_eq!(rma.value, 1500.0);
229    }
230
231    #[rstest]
232    fn handle_handle_bar(
233        mut indicator_rma_10: WilderMovingAverage,
234        bar_ethusdt_binance_minute_bid: Bar,
235    ) {
236        indicator_rma_10.handle_bar(&bar_ethusdt_binance_minute_bid);
237        assert!(indicator_rma_10.has_inputs);
238        assert!(!indicator_rma_10.initialized);
239        assert_eq!(indicator_rma_10.value, 1522.0);
240    }
241
242    #[rstest]
243    #[should_panic(expected = "WilderMovingAverage: period must be > 0")]
244    fn invalid_period_panics() {
245        let _ = WilderMovingAverage::new(0, None);
246    }
247
248    #[rstest]
249    #[case(1.0)]
250    #[case(123.456)]
251    #[case(9_876.543_21)]
252    fn first_tick_seeding_parity(#[case] seed_price: f64) {
253        let mut rma = WilderMovingAverage::new(10, None);
254
255        rma.update_raw(seed_price);
256
257        assert_eq!(rma.count(), 1);
258        assert_eq!(rma.value(), seed_price);
259        assert!(!rma.initialized());
260    }
261
262    #[rstest]
263    fn numeric_parity_with_reference_series() {
264        let mut rma = WilderMovingAverage::new(10, None);
265
266        for price in 1_u32..=10 {
267            rma.update_raw(f64::from(price));
268        }
269
270        assert!(rma.initialized());
271        assert_eq!(rma.count(), 10);
272        let expected = 4.486_784_401_f64;
273        assert!((rma.value() - expected).abs() < 1e-12);
274    }
275
276    /// Period = 1 should act as a pure 1-tick MA (α = 1) and be initialized immediately.
277    #[rstest]
278    fn test_rma_period_one_behaviour() {
279        let mut rma = WilderMovingAverage::new(1, None);
280
281        // First tick seeds and immediately initializes
282        rma.update_raw(42.0);
283        assert!(rma.initialized());
284        assert_eq!(rma.count(), 1);
285        assert!((rma.value() - 42.0).abs() < 1e-12);
286
287        // With α = 1 the next tick fully replaces the previous value
288        rma.update_raw(100.0);
289        assert_eq!(rma.count(), 2);
290        assert!((rma.value() - 100.0).abs() < 1e-12);
291    }
292
293    /// Very large period: `initialized()` must remain `false` until enough samples arrive.
294    #[rstest]
295    fn test_rma_large_period_not_initialized() {
296        let mut rma = WilderMovingAverage::new(1_000, None);
297
298        for p in 1_u32..=999 {
299            rma.update_raw(f64::from(p));
300        }
301
302        assert_eq!(rma.count(), 999);
303        assert!(!rma.initialized());
304    }
305
306    #[rstest]
307    fn test_reset_reseeds_properly() {
308        let mut rma = WilderMovingAverage::new(10, None);
309
310        rma.update_raw(10.0);
311        assert!(rma.has_inputs());
312        assert_eq!(rma.count(), 1);
313
314        rma.reset();
315        assert_eq!(rma.count(), 0);
316        assert!(!rma.has_inputs());
317        assert!(!rma.initialized());
318
319        rma.update_raw(20.0);
320        assert_eq!(rma.count(), 1);
321        assert!((rma.value() - 20.0).abs() < 1e-12);
322    }
323
324    #[rstest]
325    fn test_default_price_type_is_last() {
326        let rma = WilderMovingAverage::new(5, None);
327        assert_eq!(rma.price_type, PriceType::Last);
328    }
329
330    #[rstest]
331    fn test_update_with_nan_propagates() {
332        let mut rma = WilderMovingAverage::new(10, None);
333        rma.update_raw(f64::NAN);
334
335        assert!(rma.value().is_nan());
336        assert!(rma.has_inputs());
337        assert_eq!(rma.count(), 1);
338    }
339}