Skip to main content

nautilus_indicators/momentum/
dm.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.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::{Debug, Display};
17
18use nautilus_model::data::Bar;
19
20use crate::{
21    average::{MovingAverageFactory, MovingAverageType},
22    indicator::{Indicator, MovingAverage},
23};
24
25#[repr(C)]
26#[derive(Debug)]
27#[cfg_attr(
28    feature = "python",
29    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.indicators", unsendable)
30)]
31#[cfg_attr(
32    feature = "python",
33    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.indicators")
34)]
35pub struct DirectionalMovement {
36    pub period: usize,
37    pub ma_type: MovingAverageType,
38    pub pos: f64,
39    pub neg: f64,
40    pub initialized: bool,
41    pos_ma: Box<dyn MovingAverage + Send + 'static>,
42    neg_ma: Box<dyn MovingAverage + Send + 'static>,
43    has_inputs: bool,
44    previous_high: f64,
45    previous_low: f64,
46}
47
48impl Display for DirectionalMovement {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        write!(f, "{}({},{})", self.name(), self.period, self.ma_type,)
51    }
52}
53
54impl Indicator for DirectionalMovement {
55    fn name(&self) -> String {
56        stringify!(DirectionalMovement).to_string()
57    }
58
59    fn has_inputs(&self) -> bool {
60        self.has_inputs
61    }
62
63    fn initialized(&self) -> bool {
64        self.initialized
65    }
66
67    fn handle_bar(&mut self, bar: &Bar) {
68        self.update_raw((&bar.high).into(), (&bar.low).into());
69    }
70
71    fn reset(&mut self) {
72        self.pos_ma.reset();
73        self.neg_ma.reset();
74        self.previous_high = 0.0;
75        self.previous_low = 0.0;
76        self.pos = 0.0;
77        self.neg = 0.0;
78        self.has_inputs = false;
79        self.initialized = false;
80    }
81}
82
83impl DirectionalMovement {
84    /// Creates a new [`DirectionalMovement`] instance.
85    ///
86    /// # Panics
87    ///
88    /// Panics if `period` is not positive (> 0).
89    #[must_use]
90    pub fn new(period: usize, ma_type: Option<MovingAverageType>) -> Self {
91        assert!(period > 0, "DirectionalMovement: period must be > 0");
92        let ma_type = ma_type.unwrap_or(MovingAverageType::Exponential);
93
94        Self {
95            period,
96            ma_type,
97            pos: 0.0,
98            neg: 0.0,
99            previous_high: 0.0,
100            previous_low: 0.0,
101            pos_ma: MovingAverageFactory::create(ma_type, period),
102            neg_ma: MovingAverageFactory::create(ma_type, period),
103            has_inputs: false,
104            initialized: false,
105        }
106    }
107
108    pub fn update_raw(&mut self, high: f64, low: f64) {
109        if !self.has_inputs {
110            self.previous_high = high;
111            self.previous_low = low;
112        }
113
114        let up = high - self.previous_high;
115        let dn = self.previous_low - low;
116
117        self.pos_ma
118            .update_raw(if up > dn && up > 0.0 { up } else { 0.0 });
119        self.neg_ma
120            .update_raw(if dn > up && dn > 0.0 { dn } else { 0.0 });
121        self.pos = self.pos_ma.value();
122        self.neg = self.neg_ma.value();
123
124        self.previous_high = high;
125        self.previous_low = low;
126
127        if !self.initialized {
128            self.has_inputs = true;
129
130            if self.neg_ma.initialized() {
131                self.initialized = true;
132            }
133        }
134    }
135}
136
137#[cfg(test)]
138mod tests {
139    use rstest::rstest;
140
141    use super::*;
142    use crate::stubs::dm_10;
143
144    #[rstest]
145    fn test_name_returns_expected_string(dm_10: DirectionalMovement) {
146        assert_eq!(dm_10.name(), "DirectionalMovement");
147    }
148
149    #[rstest]
150    fn test_str_repr_returns_expected_string(dm_10: DirectionalMovement) {
151        assert_eq!(format!("{dm_10}"), "DirectionalMovement(10,SIMPLE)");
152    }
153
154    #[rstest]
155    fn test_period_returns_expected_value(dm_10: DirectionalMovement) {
156        assert_eq!(dm_10.period, 10);
157    }
158
159    #[rstest]
160    fn test_initialized_without_inputs_returns_false(dm_10: DirectionalMovement) {
161        assert!(!dm_10.initialized());
162    }
163
164    #[rstest]
165    fn test_value_with_all_higher_inputs_returns_expected_value(mut dm_10: DirectionalMovement) {
166        let high_values = [
167            1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0,
168        ];
169        let low_values = [
170            0.9, 1.9, 2.9, 3.9, 4.9, 5.9, 6.9, 7.9, 8.9, 9.9, 10.1, 10.2, 10.3, 11.1, 11.4,
171        ];
172
173        for i in 0..15 {
174            dm_10.update_raw(high_values[i], low_values[i]);
175        }
176
177        assert!(dm_10.initialized());
178        assert_eq!(dm_10.pos, 1.0);
179        assert_eq!(dm_10.neg, 0.0);
180    }
181
182    #[rstest]
183    fn test_reset_successfully_returns_indicator_to_fresh_state(mut dm_10: DirectionalMovement) {
184        dm_10.update_raw(1.00020, 1.00050);
185        dm_10.update_raw(1.00030, 1.00060);
186        dm_10.update_raw(1.00070, 1.00080);
187
188        dm_10.reset();
189
190        assert!(!dm_10.initialized());
191        assert_eq!(dm_10.pos, 0.0);
192        assert_eq!(dm_10.neg, 0.0);
193        assert_eq!(dm_10.previous_high, 0.0);
194        assert_eq!(dm_10.previous_low, 0.0);
195    }
196
197    #[rstest]
198    fn test_has_inputs_returns_true_after_first_update(mut dm_10: DirectionalMovement) {
199        assert!(!dm_10.has_inputs());
200        dm_10.update_raw(1.0, 0.9);
201        assert!(dm_10.has_inputs());
202    }
203
204    #[rstest]
205    fn test_value_with_all_lower_inputs_returns_expected_value(mut dm_10: DirectionalMovement) {
206        let high_values = [
207            15.0, 14.0, 13.0, 12.0, 11.0, 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0,
208        ];
209        let low_values = [
210            14.9, 13.9, 12.9, 11.9, 10.9, 9.9, 8.9, 7.9, 6.9, 5.9, 4.9, 3.9, 2.9, 1.9, 0.9,
211        ];
212
213        for i in 0..15 {
214            dm_10.update_raw(high_values[i], low_values[i]);
215        }
216
217        assert!(dm_10.initialized());
218        assert_eq!(dm_10.pos, 0.0);
219        assert_eq!(dm_10.neg, 1.0);
220    }
221}