nautilus_indicators/momentum/
dm.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 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)]
31pub struct DirectionalMovement {
32    pub period: usize,
33    pub ma_type: MovingAverageType,
34    pub pos: f64,
35    pub neg: f64,
36    pub initialized: bool,
37    pos_ma: Box<dyn MovingAverage + Send + 'static>,
38    neg_ma: Box<dyn MovingAverage + Send + 'static>,
39    has_inputs: bool,
40    previous_high: f64,
41    previous_low: f64,
42}
43
44impl Display for DirectionalMovement {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        write!(f, "{}({},{})", self.name(), self.period, self.ma_type,)
47    }
48}
49
50impl Indicator for DirectionalMovement {
51    fn name(&self) -> String {
52        stringify!(DirectionalMovement).to_string()
53    }
54
55    fn has_inputs(&self) -> bool {
56        self.has_inputs
57    }
58
59    fn initialized(&self) -> bool {
60        self.initialized
61    }
62
63    fn handle_bar(&mut self, bar: &Bar) {
64        self.update_raw((&bar.high).into(), (&bar.low).into());
65    }
66
67    fn reset(&mut self) {
68        self.pos_ma.reset();
69        self.neg_ma.reset();
70        self.previous_high = 0.0;
71        self.previous_low = 0.0;
72        self.pos = 0.0;
73        self.neg = 0.0;
74        self.has_inputs = false;
75        self.initialized = false;
76    }
77}
78
79impl DirectionalMovement {
80    /// Creates a new [`DirectionalMovement`] instance.
81    ///
82    /// # Panics
83    ///
84    /// Panics if `period` is not positive (> 0).
85    #[must_use]
86    pub fn new(period: usize, ma_type: Option<MovingAverageType>) -> Self {
87        assert!(period > 0, "DirectionalMovement: period must be > 0");
88        let ma_type = ma_type.unwrap_or(MovingAverageType::Exponential);
89
90        Self {
91            period,
92            ma_type,
93            pos: 0.0,
94            neg: 0.0,
95            previous_high: 0.0,
96            previous_low: 0.0,
97            pos_ma: MovingAverageFactory::create(ma_type, period),
98            neg_ma: MovingAverageFactory::create(ma_type, period),
99            has_inputs: false,
100            initialized: false,
101        }
102    }
103
104    pub fn update_raw(&mut self, high: f64, low: f64) {
105        if !self.has_inputs {
106            self.previous_high = high;
107            self.previous_low = low;
108        }
109
110        let up = high - self.previous_high;
111        let dn = self.previous_low - low;
112
113        self.pos_ma
114            .update_raw(if up > dn && up > 0.0 { up } else { 0.0 });
115        self.neg_ma
116            .update_raw(if dn > up && dn > 0.0 { dn } else { 0.0 });
117        self.pos = self.pos_ma.value();
118        self.neg = self.neg_ma.value();
119
120        self.previous_high = high;
121        self.previous_low = low;
122
123        if !self.initialized {
124            self.has_inputs = true;
125            if self.neg_ma.initialized() {
126                self.initialized = true;
127            }
128        }
129    }
130}
131
132#[cfg(test)]
133mod tests {
134    use rstest::rstest;
135
136    use super::*;
137    use crate::stubs::dm_10;
138
139    #[rstest]
140    fn test_name_returns_expected_string(dm_10: DirectionalMovement) {
141        assert_eq!(dm_10.name(), "DirectionalMovement");
142    }
143
144    #[rstest]
145    fn test_str_repr_returns_expected_string(dm_10: DirectionalMovement) {
146        assert_eq!(format!("{dm_10}"), "DirectionalMovement(10,SIMPLE)");
147    }
148
149    #[rstest]
150    fn test_period_returns_expected_value(dm_10: DirectionalMovement) {
151        assert_eq!(dm_10.period, 10);
152    }
153
154    #[rstest]
155    fn test_initialized_without_inputs_returns_false(dm_10: DirectionalMovement) {
156        assert!(!dm_10.initialized());
157    }
158
159    #[rstest]
160    fn test_value_with_all_higher_inputs_returns_expected_value(mut dm_10: DirectionalMovement) {
161        let high_values = [
162            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,
163        ];
164        let low_values = [
165            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,
166        ];
167
168        for i in 0..15 {
169            dm_10.update_raw(high_values[i], low_values[i]);
170        }
171
172        assert!(dm_10.initialized());
173        assert_eq!(dm_10.pos, 1.0);
174        assert_eq!(dm_10.neg, 0.0);
175    }
176
177    #[rstest]
178    fn test_reset_successfully_returns_indicator_to_fresh_state(mut dm_10: DirectionalMovement) {
179        dm_10.update_raw(1.00020, 1.00050);
180        dm_10.update_raw(1.00030, 1.00060);
181        dm_10.update_raw(1.00070, 1.00080);
182
183        dm_10.reset();
184
185        assert!(!dm_10.initialized());
186        assert_eq!(dm_10.pos, 0.0);
187        assert_eq!(dm_10.neg, 0.0);
188        assert_eq!(dm_10.previous_high, 0.0);
189        assert_eq!(dm_10.previous_low, 0.0);
190    }
191
192    #[rstest]
193    fn test_has_inputs_returns_true_after_first_update(mut dm_10: DirectionalMovement) {
194        assert!(!dm_10.has_inputs());
195        dm_10.update_raw(1.0, 0.9);
196        assert!(dm_10.has_inputs());
197    }
198
199    #[rstest]
200    fn test_value_with_all_lower_inputs_returns_expected_value(mut dm_10: DirectionalMovement) {
201        let high_values = [
202            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,
203        ];
204        let low_values = [
205            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,
206        ];
207
208        for i in 0..15 {
209            dm_10.update_raw(high_values[i], low_values[i]);
210        }
211
212        assert!(dm_10.initialized());
213        assert_eq!(dm_10.pos, 0.0);
214        assert_eq!(dm_10.neg, 1.0);
215    }
216}