nautilus_indicators/average/
dema.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, Formatter};
17
18use nautilus_model::{
19    data::{Bar, QuoteTick, TradeTick},
20    enums::PriceType,
21};
22
23use crate::{
24    average::ema::ExponentialMovingAverage,
25    indicator::{Indicator, MovingAverage},
26};
27
28/// The Double Exponential Moving Average attempts to a smoother average with less
29/// lag than the normal Exponential Moving Average (EMA)
30#[repr(C)]
31#[derive(Debug)]
32#[cfg_attr(
33    feature = "python",
34    pyo3::pyclass(module = "posei_trader.core.nautilus_pyo3.indicators")
35)]
36pub struct DoubleExponentialMovingAverage {
37    /// The rolling window period for the indicator (> 0).
38    pub period: usize,
39    /// The price type used for calculations.
40    pub price_type: PriceType,
41    /// The last indicator value.
42    pub value: f64,
43    /// The input count for the indicator.
44    pub count: usize,
45    pub initialized: bool,
46    has_inputs: bool,
47    ema1: ExponentialMovingAverage,
48    ema2: ExponentialMovingAverage,
49}
50
51impl Display for DoubleExponentialMovingAverage {
52    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
53        write!(f, "DoubleExponentialMovingAverage(period={})", self.period)
54    }
55}
56
57impl Indicator for DoubleExponentialMovingAverage {
58    fn name(&self) -> String {
59        stringify!(DoubleExponentialMovingAverage).to_string()
60    }
61
62    fn has_inputs(&self) -> bool {
63        self.has_inputs
64    }
65
66    fn initialized(&self) -> bool {
67        self.initialized
68    }
69
70    fn handle_quote(&mut self, quote: &QuoteTick) {
71        self.update_raw(quote.extract_price(self.price_type).into());
72    }
73
74    fn handle_trade(&mut self, trade: &TradeTick) {
75        self.update_raw((&trade.price).into());
76    }
77
78    fn handle_bar(&mut self, bar: &Bar) {
79        self.update_raw((&bar.close).into());
80    }
81
82    fn reset(&mut self) {
83        self.value = 0.0;
84        self.count = 0;
85        self.has_inputs = false;
86        self.initialized = false;
87
88        self.ema1.reset();
89        self.ema2.reset();
90    }
91}
92
93impl DoubleExponentialMovingAverage {
94    /// Creates a new [`DoubleExponentialMovingAverage`] instance.
95    ///
96    /// # Panics
97    ///
98    /// Panics if `period` is not a positive integer (> 0).
99    #[must_use]
100    pub fn new(period: usize, price_type: Option<PriceType>) -> Self {
101        assert!(
102            period > 0,
103            "DoubleExponentialMovingAverage: `period` must be a positive integer (> 0)"
104        );
105        Self {
106            period,
107            price_type: price_type.unwrap_or(PriceType::Last),
108            value: 0.0,
109            count: 0,
110            has_inputs: false,
111            initialized: false,
112            ema1: ExponentialMovingAverage::new(period, price_type),
113            ema2: ExponentialMovingAverage::new(period, price_type),
114        }
115    }
116}
117
118impl MovingAverage for DoubleExponentialMovingAverage {
119    fn value(&self) -> f64 {
120        self.value
121    }
122
123    fn count(&self) -> usize {
124        self.count
125    }
126
127    fn update_raw(&mut self, value: f64) {
128        if !self.has_inputs {
129            self.has_inputs = true;
130            self.value = value;
131        }
132
133        self.ema1.update_raw(value);
134        self.ema2.update_raw(self.ema1.value);
135
136        self.value = 2.0f64.mul_add(self.ema1.value, -self.ema2.value);
137        self.count += 1;
138
139        if !self.initialized && self.count >= self.period {
140            self.initialized = true;
141        }
142    }
143}
144
145////////////////////////////////////////////////////////////////////////////////
146// Tests
147////////////////////////////////////////////////////////////////////////////////
148#[cfg(test)]
149mod tests {
150    use nautilus_model::{
151        data::{Bar, QuoteTick, TradeTick},
152        enums::PriceType,
153    };
154    use rstest::rstest;
155
156    use crate::{
157        average::dema::DoubleExponentialMovingAverage,
158        indicator::{Indicator, MovingAverage},
159        stubs::*,
160    };
161
162    #[rstest]
163    fn test_dema_initialized(indicator_dema_10: DoubleExponentialMovingAverage) {
164        let display_str = format!("{indicator_dema_10}");
165        assert_eq!(display_str, "DoubleExponentialMovingAverage(period=10)");
166        assert_eq!(indicator_dema_10.period, 10);
167        assert!(!indicator_dema_10.initialized);
168        assert!(!indicator_dema_10.has_inputs);
169    }
170
171    #[rstest]
172    fn test_value_with_one_input(mut indicator_dema_10: DoubleExponentialMovingAverage) {
173        indicator_dema_10.update_raw(1.0);
174        assert_eq!(indicator_dema_10.value, 1.0);
175    }
176
177    #[rstest]
178    fn test_value_with_three_inputs(mut indicator_dema_10: DoubleExponentialMovingAverage) {
179        indicator_dema_10.update_raw(1.0);
180        indicator_dema_10.update_raw(2.0);
181        indicator_dema_10.update_raw(3.0);
182        assert_eq!(indicator_dema_10.value, 1.904_583_020_285_499_4);
183    }
184
185    #[rstest]
186    fn test_initialized_with_required_input(mut indicator_dema_10: DoubleExponentialMovingAverage) {
187        for i in 1..10 {
188            indicator_dema_10.update_raw(f64::from(i));
189        }
190        assert!(!indicator_dema_10.initialized);
191        indicator_dema_10.update_raw(10.0);
192        assert!(indicator_dema_10.initialized);
193    }
194
195    #[rstest]
196    fn test_handle_quote(
197        mut indicator_dema_10: DoubleExponentialMovingAverage,
198        stub_quote: QuoteTick,
199    ) {
200        indicator_dema_10.handle_quote(&stub_quote);
201        assert_eq!(indicator_dema_10.value, 1501.0);
202    }
203
204    #[rstest]
205    fn test_handle_trade(
206        mut indicator_dema_10: DoubleExponentialMovingAverage,
207        stub_trade: TradeTick,
208    ) {
209        indicator_dema_10.handle_trade(&stub_trade);
210        assert_eq!(indicator_dema_10.value, 1500.0);
211    }
212
213    #[rstest]
214    fn test_handle_bar(
215        mut indicator_dema_10: DoubleExponentialMovingAverage,
216        bar_ethusdt_binance_minute_bid: Bar,
217    ) {
218        indicator_dema_10.handle_bar(&bar_ethusdt_binance_minute_bid);
219        assert_eq!(indicator_dema_10.value, 1522.0);
220        assert!(indicator_dema_10.has_inputs);
221        assert!(!indicator_dema_10.initialized);
222    }
223
224    #[rstest]
225    fn test_reset(mut indicator_dema_10: DoubleExponentialMovingAverage) {
226        indicator_dema_10.update_raw(1.0);
227        assert_eq!(indicator_dema_10.count, 1);
228        assert!(indicator_dema_10.ema1.count() > 0);
229        assert!(indicator_dema_10.ema2.count() > 0);
230
231        indicator_dema_10.reset();
232
233        assert_eq!(indicator_dema_10.value, 0.0);
234        assert_eq!(indicator_dema_10.count, 0);
235        assert!(!indicator_dema_10.has_inputs);
236        assert!(!indicator_dema_10.initialized);
237
238        assert_eq!(indicator_dema_10.ema1.count(), 0);
239        assert_eq!(indicator_dema_10.ema2.count(), 0);
240    }
241
242    #[rstest]
243    #[should_panic(expected = "`period`")]
244    fn new_panics_on_zero_period() {
245        let _ = DoubleExponentialMovingAverage::new(0, None);
246    }
247
248    #[rstest]
249    fn test_new_with_minimum_valid_period() {
250        let dema = DoubleExponentialMovingAverage::new(1, None);
251        assert_eq!(dema.period, 1);
252        assert_eq!(dema.price_type, PriceType::Last);
253        assert_eq!(dema.count(), 0);
254        assert_eq!(dema.ema1.count(), 0);
255        assert_eq!(dema.ema2.count(), 0);
256        assert!(!dema.initialized());
257    }
258
259    #[rstest]
260    fn test_counters_are_in_sync(mut indicator_dema_10: DoubleExponentialMovingAverage) {
261        for i in 1..=indicator_dema_10.period {
262            indicator_dema_10.update_raw(i as f64); // ← FIX ❷
263            assert_eq!(
264                indicator_dema_10.count(),
265                i,
266                "outer count diverged at iteration {i}"
267            );
268            assert_eq!(
269                indicator_dema_10.ema1.count(),
270                i,
271                "ema1 count diverged at iteration {i}"
272            );
273            assert_eq!(
274                indicator_dema_10.ema2.count(),
275                i,
276                "ema2 count diverged at iteration {i}"
277            );
278        }
279        assert!(indicator_dema_10.initialized());
280    }
281
282    #[rstest]
283    fn test_inner_ema_values_are_reset(mut indicator_dema_10: DoubleExponentialMovingAverage) {
284        for i in 1..=3 {
285            indicator_dema_10.update_raw(f64::from(i));
286        }
287        assert_ne!(indicator_dema_10.ema1.value(), 0.0);
288        assert_ne!(indicator_dema_10.ema2.value(), 0.0);
289
290        indicator_dema_10.reset();
291
292        assert_eq!(indicator_dema_10.ema1.count(), 0);
293        assert_eq!(indicator_dema_10.ema2.count(), 0);
294        assert_eq!(indicator_dema_10.ema1.value(), 0.0);
295        assert_eq!(indicator_dema_10.ema2.value(), 0.0);
296    }
297
298    #[rstest]
299    fn test_counter_increments_via_handle_helpers(
300        mut indicator_dema_10: DoubleExponentialMovingAverage,
301        stub_quote: QuoteTick,
302        stub_trade: TradeTick,
303        bar_ethusdt_binance_minute_bid: Bar,
304    ) {
305        assert_eq!(indicator_dema_10.count(), 0);
306
307        indicator_dema_10.handle_quote(&stub_quote);
308        assert_eq!(indicator_dema_10.count(), 1);
309        assert_eq!(indicator_dema_10.ema1.count(), 1);
310        assert_eq!(indicator_dema_10.ema2.count(), 1);
311
312        indicator_dema_10.handle_trade(&stub_trade);
313        assert_eq!(indicator_dema_10.count(), 2);
314        assert_eq!(indicator_dema_10.ema1.count(), 2);
315        assert_eq!(indicator_dema_10.ema2.count(), 2);
316
317        indicator_dema_10.handle_bar(&bar_ethusdt_binance_minute_bid);
318        assert_eq!(indicator_dema_10.count(), 3);
319        assert_eq!(indicator_dema_10.ema1.count(), 3);
320        assert_eq!(indicator_dema_10.ema2.count(), 3);
321    }
322}