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