Skip to main content

nautilus_indicators/momentum/
swings.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::Display;
17
18use arraydeque::{ArrayDeque, Wrapping};
19use nautilus_model::data::{Bar, QuoteTick, TradeTick};
20
21use crate::indicator::Indicator;
22
23const MAX_PERIOD: usize = 1_024;
24
25#[repr(C)]
26#[derive(Debug)]
27#[cfg_attr(
28    feature = "python",
29    pyo3::pyclass(module = "nautilus_trader.indicators")
30)]
31#[cfg_attr(
32    feature = "python",
33    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.indicators")
34)]
35pub struct Swings {
36    pub period: usize,
37    pub direction: i64,
38    pub changed: bool,
39    pub high_datetime: f64,
40    pub low_datetime: f64,
41    pub high_price: f64,
42    pub low_price: f64,
43    pub length: usize,
44    pub duration: usize,
45    pub since_high: usize,
46    pub since_low: usize,
47    high_inputs: ArrayDeque<f64, MAX_PERIOD, Wrapping>,
48    low_inputs: ArrayDeque<f64, MAX_PERIOD, Wrapping>,
49    has_inputs: bool,
50    initialized: bool,
51}
52
53impl Display for Swings {
54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55        write!(f, "{}({})", self.name(), self.period)
56    }
57}
58
59impl Indicator for Swings {
60    fn name(&self) -> String {
61        stringify!(Swings).to_string()
62    }
63
64    fn has_inputs(&self) -> bool {
65        self.has_inputs
66    }
67
68    fn initialized(&self) -> bool {
69        self.initialized
70    }
71
72    fn handle_quote(&mut self, _quote: &QuoteTick) -> anyhow::Result<()> {
73        Ok(())
74    }
75
76    fn handle_trade(&mut self, _trade: &TradeTick) {}
77
78    fn handle_bar(&mut self, bar: &Bar) {
79        self.update_raw((&bar.high).into(), (&bar.low).into(), bar.ts_init.as_f64());
80    }
81
82    fn reset(&mut self) {
83        self.high_inputs.clear();
84        self.low_inputs.clear();
85        self.has_inputs = false;
86        self.initialized = false;
87        self.direction = 0;
88        self.changed = false;
89        self.high_datetime = 0.0;
90        self.low_datetime = 0.0;
91        self.high_price = 0.0;
92        self.low_price = 0.0;
93        self.length = 0;
94        self.duration = 0;
95        self.since_high = 0;
96        self.since_low = 0;
97    }
98}
99
100impl Swings {
101    /// Creates a new [`Swings`] instance.
102    ///
103    /// # Panics
104    ///
105    /// This function panics if:
106    /// - `period` is less than or equal to 0.
107    /// - `period` exceeds the maximum allowed value of `MAX_PERIOD`.
108    #[must_use]
109    pub fn new(period: usize) -> Self {
110        assert!(
111            period > 0 && period <= MAX_PERIOD,
112            "Swings: period {period} exceeds MAX_PERIOD ({MAX_PERIOD})"
113        );
114
115        Self {
116            period,
117            high_inputs: ArrayDeque::new(),
118            low_inputs: ArrayDeque::new(),
119            has_inputs: false,
120            initialized: false,
121            direction: 0,
122            changed: false,
123            high_datetime: 0.0,
124            low_datetime: 0.0,
125            high_price: 0.0,
126            low_price: 0.0,
127            length: 0,
128            duration: 0,
129            since_high: 0,
130            since_low: 0,
131        }
132    }
133
134    pub fn update_raw(&mut self, high: f64, low: f64, timestamp: f64) {
135        self.changed = false;
136
137        if self.high_inputs.len() == self.period {
138            self.high_inputs.pop_front();
139        }
140
141        if self.low_inputs.len() == self.period {
142            self.low_inputs.pop_front();
143        }
144        let _ = self.high_inputs.push_back(high);
145        let _ = self.low_inputs.push_back(low);
146
147        let max_high = self.high_inputs.iter().fold(f64::MIN, |a, &b| a.max(b));
148        let min_low = self.low_inputs.iter().fold(f64::MAX, |a, &b| a.min(b));
149
150        let is_swing_high = high >= max_high && low >= min_low;
151        let is_swing_low = high <= max_high && low <= min_low;
152
153        if is_swing_high && is_swing_low {
154            if self.high_price == 0.0 {
155                self.high_price = high;
156                self.high_datetime = timestamp;
157            }
158            self.since_high += 1;
159            self.since_low += 1;
160        } else if is_swing_high {
161            if self.direction == -1 {
162                self.changed = true;
163            }
164
165            if high > self.high_price {
166                self.high_price = high;
167                self.high_datetime = timestamp;
168            }
169            self.direction = 1;
170            self.since_high = 0;
171            self.since_low += 1;
172        } else if is_swing_low {
173            if self.direction == 1 {
174                self.changed = true;
175            }
176
177            if self.high_price == 0.0 {
178                self.high_price = max_high;
179                self.high_datetime = timestamp;
180            }
181
182            if low < self.low_price || self.low_price == 0.0 {
183                self.low_price = low;
184                self.low_datetime = timestamp;
185            }
186            self.direction = -1;
187            self.since_high += 1;
188            self.since_low = 0;
189        } else {
190            self.since_high += 1;
191            self.since_low += 1;
192        }
193
194        self.has_inputs = true;
195
196        if self.high_price != 0.0 && self.low_price != 0.0 {
197            self.initialized = true;
198            self.length = ((self.high_price - self.low_price).abs().round()) as usize;
199
200            if self.direction == 1 {
201                self.duration = self.since_low;
202            } else if self.direction == -1 {
203                self.duration = self.since_high;
204            } else {
205                self.duration = 0;
206            }
207        }
208    }
209}
210
211#[cfg(test)]
212mod tests {
213    use rstest::rstest;
214
215    use super::*;
216    use crate::stubs::swings_10;
217
218    #[rstest]
219    fn test_name_returns_expected_string(swings_10: Swings) {
220        assert_eq!(swings_10.name(), "Swings");
221    }
222
223    #[rstest]
224    fn test_str_repr_returns_expected_string(swings_10: Swings) {
225        assert_eq!(format!("{swings_10}"), "Swings(10)");
226    }
227
228    #[rstest]
229    fn test_period_returns_expected_value(swings_10: Swings) {
230        assert_eq!(swings_10.period, 10);
231    }
232
233    #[rstest]
234    fn test_initialized_without_inputs_returns_false(swings_10: Swings) {
235        assert!(!swings_10.initialized());
236    }
237
238    #[rstest]
239    fn test_value_with_all_higher_inputs_returns_expected_value(mut swings_10: Swings) {
240        let high = [
241            0.9, 1.9, 2.9, 3.9, 4.9, 3.2, 6.9, 7.9, 8.9, 9.9, 1.1, 3.2, 10.3, 11.1, 11.4,
242        ];
243        let low = [
244            0.8, 1.8, 2.8, 3.8, 4.8, 3.1, 6.8, 7.8, 0.8, 9.8, 1.0, 3.1, 10.2, 11.0, 11.3,
245        ];
246        let time = [
247            1_643_723_400.0,
248            1_643_723_410.0,
249            1_643_723_420.0,
250            1_643_723_430.0,
251            1_643_723_440.0,
252            1_643_723_450.0,
253            1_643_723_460.0,
254            1_643_723_470.0,
255            1_643_723_480.0,
256            1_643_723_490.0,
257            1_643_723_500.0,
258            1_643_723_510.0,
259            1_643_723_520.0,
260            1_643_723_530.0,
261            1_643_723_540.0,
262        ];
263
264        for i in 0..15 {
265            swings_10.update_raw(high[i], low[i], time[i]);
266        }
267
268        assert_eq!(swings_10.direction, 1);
269        assert_eq!(swings_10.high_price, 11.4);
270        assert_eq!(swings_10.low_price, 0.0);
271        assert_eq!(swings_10.high_datetime, time[14]);
272        assert_eq!(swings_10.low_datetime, 0.0);
273        assert_eq!(swings_10.length, 0);
274        assert_eq!(swings_10.duration, 0);
275        assert_eq!(swings_10.since_high, 0);
276        assert_eq!(swings_10.since_low, 15);
277    }
278
279    #[rstest]
280    fn test_reset_successfully_returns_indicator_to_fresh_state(mut swings_10: Swings) {
281        let high = [1.0, 2.0, 3.0, 4.0, 5.0];
282        let low = [0.9, 1.9, 2.9, 3.9, 4.9];
283        let time = [
284            1_643_723_400.0,
285            1_643_723_410.0,
286            1_643_723_420.0,
287            1_643_723_430.0,
288            1_643_723_440.0,
289        ];
290
291        for i in 0..5 {
292            swings_10.update_raw(high[i], low[i], time[i]);
293        }
294
295        swings_10.reset();
296
297        assert!(!swings_10.initialized());
298        assert_eq!(swings_10.direction, 0);
299        assert_eq!(swings_10.high_price, 0.0);
300        assert_eq!(swings_10.low_price, 0.0);
301        assert_eq!(swings_10.high_datetime, 0.0);
302        assert_eq!(swings_10.low_datetime, 0.0);
303        assert_eq!(swings_10.length, 0);
304        assert_eq!(swings_10.duration, 0);
305        assert_eq!(swings_10.since_high, 0);
306        assert_eq!(swings_10.since_low, 0);
307        assert!(swings_10.high_inputs.is_empty());
308        assert!(swings_10.low_inputs.is_empty());
309    }
310
311    #[rstest]
312    fn test_changed_flag_flips() {
313        let mut swings = Swings::new(2);
314
315        swings.update_raw(1.0, 0.5, 1.0);
316        assert!(!swings.changed);
317
318        swings.update_raw(2.0, 1.5, 2.0);
319        assert!(!swings.changed);
320
321        swings.update_raw(0.0, -1.0, 3.0);
322        assert!(swings.changed);
323
324        swings.update_raw(-0.5, -1.5, 4.0);
325        assert!(!swings.changed);
326    }
327
328    #[rstest]
329    fn test_length_computation_after_initialization() {
330        let mut swings = Swings::new(2);
331        swings.update_raw(10.0, 9.0, 1.0);
332        swings.update_raw(8.0, 7.0, 2.0);
333        swings.update_raw(8.0, 7.5, 3.0);
334        assert_eq!(swings.length, 3);
335    }
336
337    #[rstest]
338    fn test_length_rounds_fractional_difference() {
339        let mut swings = Swings::new(2);
340        swings.update_raw(10.9, 10.7, 1.0);
341        swings.update_raw(9.7, 9.4, 2.0);
342        swings.update_raw(9.7, 9.4, 3.0);
343        assert_eq!(swings.length, 2);
344    }
345
346    #[rstest]
347    fn test_queue_eviction_does_not_exceed_capacity() {
348        let period = 3;
349        let mut swings = Swings::new(period);
350
351        let highs = [1.0, 2.0, 3.0, 4.0, 5.0];
352        let lows = [0.5, 1.5, 2.5, 3.5, 4.5];
353
354        for i in 0..highs.len() {
355            swings.update_raw(highs[i], lows[i], (i + 1) as f64);
356
357            assert!(swings.high_inputs.len() <= period);
358            assert!(swings.low_inputs.len() <= period);
359        }
360
361        assert_eq!(swings.high_inputs.len(), period);
362        assert_eq!(swings.low_inputs.len(), period);
363        assert_eq!(swings.high_inputs.front().copied(), Some(3.0));
364        assert_eq!(swings.low_inputs.front().copied(), Some(2.5));
365    }
366
367    #[rstest]
368    fn test_changed_flag_toggles_on_every_direction_flip() {
369        let mut swings = Swings::new(2);
370
371        swings.update_raw(1.0, 0.7, 1.0);
372        assert!(!swings.changed);
373        swings.update_raw(2.0, 1.7, 2.0);
374        assert!(!swings.changed);
375
376        swings.update_raw(0.0, -1.0, 3.0);
377        assert!(swings.changed);
378        swings.update_raw(-0.5, -1.5, 4.0);
379        assert!(!swings.changed);
380
381        swings.update_raw(2.5, 1.5, 5.0);
382        assert!(swings.changed);
383        swings.update_raw(3.0, 2.0, 6.0);
384        assert!(!swings.changed);
385    }
386
387    #[rstest]
388    fn test_length_precision_rounding() {
389        let mut swings = Swings::new(3);
390        swings.update_raw(10.49, 9.9, 1.0);
391        swings.update_raw(9.00, 8.0, 2.0);
392        swings.update_raw(9.00, 8.0, 3.0);
393        assert_eq!(swings.length, 2);
394
395        swings.reset();
396        swings.update_raw(10.5, 10.4, 10.0);
397        swings.update_raw(8.0, 7.5, 20.0);
398        swings.update_raw(8.0, 7.5, 30.0);
399        assert_eq!(swings.length, 3);
400
401        swings.reset();
402        swings.update_raw(10.8, 10.6, 40.0);
403        swings.update_raw(8.2, 7.4, 50.0);
404        swings.update_raw(8.2, 7.4, 60.0);
405        assert_eq!(swings.length, 3);
406    }
407}