nautilus_indicators/momentum/
vhf.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::{
17    collections::VecDeque,
18    fmt::{Debug, Display},
19};
20
21use nautilus_model::data::Bar;
22
23use crate::{
24    average::{MovingAverageFactory, MovingAverageType},
25    indicator::{Indicator, MovingAverage},
26};
27
28#[repr(C)]
29#[derive(Debug)]
30#[cfg_attr(
31    feature = "python",
32    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.indicators", unsendable)
33)]
34pub struct VerticalHorizontalFilter {
35    pub period: usize,
36    pub ma_type: MovingAverageType,
37    pub value: f64,
38    pub initialized: bool,
39    ma: Box<dyn MovingAverage + Send + 'static>,
40    has_inputs: bool,
41    previous_close: f64,
42    prices: VecDeque<f64>,
43}
44
45impl Display for VerticalHorizontalFilter {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        write!(f, "{}({},{})", self.name(), self.period, self.ma_type,)
48    }
49}
50
51impl Indicator for VerticalHorizontalFilter {
52    fn name(&self) -> String {
53        stringify!(VerticalHorizontalFilter).to_string()
54    }
55
56    fn has_inputs(&self) -> bool {
57        self.has_inputs
58    }
59
60    fn initialized(&self) -> bool {
61        self.initialized
62    }
63
64    fn handle_bar(&mut self, bar: &Bar) {
65        self.update_raw((&bar.close).into());
66    }
67
68    fn reset(&mut self) {
69        self.prices.clear();
70        self.ma.reset();
71        self.previous_close = 0.0;
72        self.value = 0.0;
73        self.has_inputs = false;
74        self.initialized = false;
75    }
76}
77
78impl VerticalHorizontalFilter {
79    /// Creates a new [`VerticalHorizontalFilter`] instance.
80    #[must_use]
81    pub fn new(period: usize, ma_type: Option<MovingAverageType>) -> Self {
82        Self {
83            period,
84            ma_type: ma_type.unwrap_or(MovingAverageType::Simple),
85            value: 0.0,
86            previous_close: 0.0,
87            ma: MovingAverageFactory::create(ma_type.unwrap_or(MovingAverageType::Simple), period),
88            has_inputs: false,
89            initialized: false,
90            prices: VecDeque::with_capacity(period),
91        }
92    }
93
94    pub fn update_raw(&mut self, close: f64) {
95        if !self.has_inputs {
96            self.previous_close = close;
97        }
98        self.prices.push_back(close);
99
100        let max_price = self
101            .prices
102            .iter()
103            .copied()
104            .fold(f64::NEG_INFINITY, f64::max);
105
106        let min_price = self.prices.iter().copied().fold(f64::INFINITY, f64::min);
107
108        self.ma.update_raw(f64::abs(close - self.previous_close));
109        if self.initialized {
110            self.value = f64::abs(max_price - min_price) / self.period as f64 / self.ma.value();
111        }
112        self.previous_close = close;
113
114        self._check_initialized();
115    }
116
117    pub fn _check_initialized(&mut self) {
118        if !self.initialized {
119            self.has_inputs = true;
120            if self.ma.initialized() {
121                self.initialized = true;
122            }
123        }
124    }
125}
126
127////////////////////////////////////////////////////////////////////////////////
128// Tests
129////////////////////////////////////////////////////////////////////////////////
130#[cfg(test)]
131mod tests {
132    use nautilus_model::data::Bar;
133    use rstest::rstest;
134
135    use crate::{indicator::Indicator, momentum::vhf::VerticalHorizontalFilter, stubs::*};
136
137    #[rstest]
138    fn test_dema_initialized(vhf_10: VerticalHorizontalFilter) {
139        let display_str = format!("{vhf_10}");
140        assert_eq!(display_str, "VerticalHorizontalFilter(10,SIMPLE)");
141        assert_eq!(vhf_10.period, 10);
142        assert!(!vhf_10.initialized);
143        assert!(!vhf_10.has_inputs);
144    }
145
146    #[rstest]
147    fn test_value_with_one_input(mut vhf_10: VerticalHorizontalFilter) {
148        vhf_10.update_raw(1.0);
149        assert_eq!(vhf_10.value, 0.0);
150    }
151
152    #[rstest]
153    fn test_value_with_three_inputs(mut vhf_10: VerticalHorizontalFilter) {
154        vhf_10.update_raw(1.0);
155        vhf_10.update_raw(2.0);
156        vhf_10.update_raw(3.0);
157        assert_eq!(vhf_10.value, 0.0);
158    }
159
160    #[rstest]
161    fn test_value_with_ten_inputs(mut vhf_10: VerticalHorizontalFilter) {
162        vhf_10.update_raw(1.00000);
163        vhf_10.update_raw(1.00010);
164        vhf_10.update_raw(1.00020);
165        vhf_10.update_raw(1.00030);
166        vhf_10.update_raw(1.00040);
167        vhf_10.update_raw(1.00050);
168        vhf_10.update_raw(1.00040);
169        vhf_10.update_raw(1.00030);
170        vhf_10.update_raw(1.00020);
171        vhf_10.update_raw(1.00010);
172        vhf_10.update_raw(1.00000);
173        assert_eq!(vhf_10.value, 0.5);
174    }
175
176    #[rstest]
177    fn test_initialized_with_required_input(mut vhf_10: VerticalHorizontalFilter) {
178        for i in 1..10 {
179            vhf_10.update_raw(f64::from(i));
180        }
181        assert!(!vhf_10.initialized);
182        vhf_10.update_raw(10.0);
183        assert!(vhf_10.initialized);
184    }
185
186    #[rstest]
187    fn test_handle_bar(mut vhf_10: VerticalHorizontalFilter, bar_ethusdt_binance_minute_bid: Bar) {
188        vhf_10.handle_bar(&bar_ethusdt_binance_minute_bid);
189        assert_eq!(vhf_10.value, 0.0);
190        assert!(vhf_10.has_inputs);
191        assert!(!vhf_10.initialized);
192    }
193
194    #[rstest]
195    fn test_reset(mut vhf_10: VerticalHorizontalFilter) {
196        vhf_10.update_raw(1.0);
197        assert_eq!(vhf_10.prices.len(), 1);
198        vhf_10.reset();
199        assert_eq!(vhf_10.value, 0.0);
200        assert_eq!(vhf_10.prices.len(), 0);
201        assert!(!vhf_10.has_inputs);
202        assert!(!vhf_10.initialized);
203    }
204}