nautilus_indicators/momentum/
dm.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::{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 = "posei_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////////////////////////////////////////////////////////////////////////////////
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
195    #[rstest]
196    fn test_has_inputs_returns_true_after_first_update(mut dm_10: DirectionalMovement) {
197        assert!(!dm_10.has_inputs());
198        dm_10.update_raw(1.0, 0.9);
199        assert!(dm_10.has_inputs());
200    }
201
202    #[rstest]
203    fn test_value_with_all_lower_inputs_returns_expected_value(mut dm_10: DirectionalMovement) {
204        let high_values = [
205            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,
206        ];
207        let low_values = [
208            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,
209        ];
210
211        for i in 0..15 {
212            dm_10.update_raw(high_values[i], low_values[i]);
213        }
214
215        assert!(dm_10.initialized());
216        assert_eq!(dm_10.pos, 0.0);
217        assert_eq!(dm_10.neg, 1.0);
218    }
219}