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    #[must_use]
82    pub fn new(period: usize, ma_type: Option<MovingAverageType>) -> Self {
83        Self {
84            period,
85            ma_type: ma_type.unwrap_or(MovingAverageType::Simple),
86            pos: 0.0,
87            neg: 0.0,
88            previous_high: 0.0,
89            previous_low: 0.0,
90            pos_ma: MovingAverageFactory::create(
91                ma_type.unwrap_or(MovingAverageType::Simple),
92                period,
93            ),
94            neg_ma: MovingAverageFactory::create(
95                ma_type.unwrap_or(MovingAverageType::Simple),
96                period,
97            ),
98            has_inputs: false,
99            initialized: false,
100        }
101    }
102
103    pub fn update_raw(&mut self, high: f64, low: f64) {
104        if !self.has_inputs {
105            self.previous_high = high;
106            self.previous_low = low;
107        }
108
109        let up = high - self.previous_high;
110        let dn = self.previous_low - low;
111
112        self.pos_ma
113            .update_raw(if up > dn && up > 0.0 { up } else { 0.0 });
114        self.neg_ma
115            .update_raw(if dn > up && dn > 0.0 { dn } else { 0.0 });
116        self.pos = self.pos_ma.value();
117        self.neg = self.neg_ma.value();
118
119        self.previous_high = high;
120        self.previous_low = low;
121
122        // Initialization logic
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////////////////////////////////////////////////////////////////////////////////
133// Tests
134////////////////////////////////////////////////////////////////////////////////
135#[cfg(test)]
136mod tests {
137    use rstest::rstest;
138
139    use super::*;
140    use crate::stubs::dm_10;
141
142    #[rstest]
143    fn test_name_returns_expected_string(dm_10: DirectionalMovement) {
144        assert_eq!(dm_10.name(), "DirectionalMovement");
145    }
146
147    #[rstest]
148    fn test_str_repr_returns_expected_string(dm_10: DirectionalMovement) {
149        assert_eq!(format!("{dm_10}"), "DirectionalMovement(10,SIMPLE)");
150    }
151
152    #[rstest]
153    fn test_period_returns_expected_value(dm_10: DirectionalMovement) {
154        assert_eq!(dm_10.period, 10);
155    }
156
157    #[rstest]
158    fn test_initialized_without_inputs_returns_false(dm_10: DirectionalMovement) {
159        assert!(!dm_10.initialized());
160    }
161
162    #[rstest]
163    fn test_value_with_all_higher_inputs_returns_expected_value(mut dm_10: DirectionalMovement) {
164        let high_values = [
165            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,
166        ];
167        let low_values = [
168            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,
169        ];
170
171        for i in 0..15 {
172            dm_10.update_raw(high_values[i], low_values[i]);
173        }
174
175        assert!(dm_10.initialized());
176        assert_eq!(dm_10.pos, 1.0);
177        assert_eq!(dm_10.neg, 0.0);
178    }
179
180    #[rstest]
181    fn test_reset_successfully_returns_indicator_to_fresh_state(mut dm_10: DirectionalMovement) {
182        dm_10.update_raw(1.00020, 1.00050);
183        dm_10.update_raw(1.00030, 1.00060);
184        dm_10.update_raw(1.00070, 1.00080);
185
186        dm_10.reset();
187
188        assert!(!dm_10.initialized());
189        assert_eq!(dm_10.pos, 0.0);
190        assert_eq!(dm_10.neg, 0.0);
191        assert_eq!(dm_10.previous_high, 0.0);
192        assert_eq!(dm_10.previous_low, 0.0);
193    }
194}