Skip to main content

nautilus_indicators/momentum/
vhf.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::{
22    average::{MovingAverageFactory, MovingAverageType},
23    indicator::{Indicator, MovingAverage},
24};
25
26const MAX_PERIOD: usize = 1_024;
27
28#[repr(C)]
29#[derive(Debug)]
30#[cfg_attr(
31    feature = "python",
32    pyo3::pyclass(module = "nautilus_trader.indicators", unsendable)
33)]
34#[cfg_attr(
35    feature = "python",
36    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.indicators")
37)]
38pub struct VerticalHorizontalFilter {
39    pub period: usize,
40    pub ma_type: MovingAverageType,
41    pub value: f64,
42    pub initialized: bool,
43    ma: Box<dyn MovingAverage + Send + 'static>,
44    has_inputs: bool,
45    previous_close: f64,
46    prices: ArrayDeque<f64, MAX_PERIOD, Wrapping>,
47}
48
49impl Display for VerticalHorizontalFilter {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        write!(f, "{}({},{})", self.name(), self.period, self.ma_type)
52    }
53}
54
55impl Indicator for VerticalHorizontalFilter {
56    fn name(&self) -> String {
57        stringify!(VerticalHorizontalFilter).to_string()
58    }
59
60    fn has_inputs(&self) -> bool {
61        self.has_inputs
62    }
63
64    fn initialized(&self) -> bool {
65        self.initialized
66    }
67
68    fn handle_quote(&mut self, _quote: &QuoteTick) -> anyhow::Result<()> {
69        Ok(())
70    }
71
72    fn handle_trade(&mut self, _trade: &TradeTick) {}
73
74    fn handle_bar(&mut self, bar: &Bar) {
75        self.update_raw((&bar.close).into());
76    }
77
78    fn reset(&mut self) {
79        self.prices.clear();
80        self.ma.reset();
81        self.previous_close = 0.0;
82        self.value = 0.0;
83        self.has_inputs = false;
84        self.initialized = false;
85    }
86}
87
88impl VerticalHorizontalFilter {
89    /// Creates a new [`VerticalHorizontalFilter`] instance.
90    ///
91    /// # Panics
92    ///
93    /// This function panics if:
94    /// - `period` is less than or equal to 0.
95    /// - `period` exceeds `MAX_PERIOD`.
96    #[must_use]
97    pub fn new(period: usize, ma_type: Option<MovingAverageType>) -> Self {
98        assert!(
99            period > 0 && period <= MAX_PERIOD,
100            "VerticalHorizontalFilter: period {period} exceeds MAX_PERIOD ({MAX_PERIOD})"
101        );
102
103        let ma_kind = ma_type.unwrap_or(MovingAverageType::Simple);
104
105        Self {
106            period,
107            ma_type: ma_kind,
108            value: 0.0,
109            previous_close: 0.0,
110            ma: MovingAverageFactory::create(ma_kind, period),
111            has_inputs: false,
112            initialized: false,
113            prices: ArrayDeque::new(),
114        }
115    }
116
117    pub fn update_raw(&mut self, close: f64) {
118        if !self.has_inputs {
119            self.previous_close = close;
120        }
121
122        if self.prices.len() == self.period {
123            let _ = self.prices.pop_front();
124        }
125
126        let _ = self.prices.push_back(close);
127
128        let max_price = self
129            .prices
130            .iter()
131            .copied()
132            .fold(f64::NEG_INFINITY, f64::max);
133
134        let min_price = self.prices.iter().copied().fold(f64::INFINITY, f64::min);
135
136        self.ma.update_raw(f64::abs(close - self.previous_close));
137
138        if self.initialized {
139            self.value = f64::abs(max_price - min_price) / self.period as f64 / self.ma.value();
140        }
141
142        self.previous_close = close;
143        self.check_initialized();
144    }
145
146    pub fn check_initialized(&mut self) {
147        if !self.initialized {
148            self.has_inputs = true;
149
150            if self.ma.initialized() {
151                self.initialized = true;
152            }
153        }
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use nautilus_model::data::Bar;
160    use rstest::rstest;
161
162    use crate::{indicator::Indicator, momentum::vhf::VerticalHorizontalFilter, stubs::*};
163
164    #[rstest]
165    fn test_dema_initialized(vhf_10: VerticalHorizontalFilter) {
166        let display_str = format!("{vhf_10}");
167        assert_eq!(display_str, "VerticalHorizontalFilter(10,SIMPLE)");
168        assert_eq!(vhf_10.period, 10);
169        assert!(!vhf_10.initialized);
170        assert!(!vhf_10.has_inputs);
171    }
172
173    #[rstest]
174    fn test_value_with_one_input(mut vhf_10: VerticalHorizontalFilter) {
175        vhf_10.update_raw(1.0);
176        assert_eq!(vhf_10.value, 0.0);
177    }
178
179    #[rstest]
180    fn test_value_with_three_inputs(mut vhf_10: VerticalHorizontalFilter) {
181        vhf_10.update_raw(1.0);
182        vhf_10.update_raw(2.0);
183        vhf_10.update_raw(3.0);
184        assert_eq!(vhf_10.value, 0.0);
185    }
186
187    #[rstest]
188    fn test_value_with_ten_inputs(mut vhf_10: VerticalHorizontalFilter) {
189        vhf_10.update_raw(1.00000);
190        vhf_10.update_raw(1.00010);
191        vhf_10.update_raw(1.00020);
192        vhf_10.update_raw(1.00030);
193        vhf_10.update_raw(1.00040);
194        vhf_10.update_raw(1.00050);
195        vhf_10.update_raw(1.00040);
196        vhf_10.update_raw(1.00030);
197        vhf_10.update_raw(1.00020);
198        vhf_10.update_raw(1.00010);
199        vhf_10.update_raw(1.00000);
200        assert_eq!(vhf_10.value, 0.5);
201    }
202
203    #[rstest]
204    fn test_initialized_with_required_input(mut vhf_10: VerticalHorizontalFilter) {
205        for i in 1..10 {
206            vhf_10.update_raw(f64::from(i));
207        }
208        assert!(!vhf_10.initialized);
209        vhf_10.update_raw(10.0);
210        assert!(vhf_10.initialized);
211    }
212
213    #[rstest]
214    fn test_handle_bar(mut vhf_10: VerticalHorizontalFilter, bar_ethusdt_binance_minute_bid: Bar) {
215        vhf_10.handle_bar(&bar_ethusdt_binance_minute_bid);
216        assert_eq!(vhf_10.value, 0.0);
217        assert!(vhf_10.has_inputs);
218        assert!(!vhf_10.initialized);
219    }
220
221    #[rstest]
222    fn test_reset(mut vhf_10: VerticalHorizontalFilter) {
223        vhf_10.update_raw(1.0);
224        assert_eq!(vhf_10.prices.len(), 1);
225        vhf_10.reset();
226        assert_eq!(vhf_10.value, 0.0);
227        assert_eq!(vhf_10.prices.len(), 0);
228        assert!(!vhf_10.has_inputs);
229        assert!(!vhf_10.initialized);
230    }
231
232    #[rstest]
233    fn test_value_respects_period_window() {
234        let mut vhf = VerticalHorizontalFilter::new(3, None);
235
236        vhf.update_raw(100.0); // Early spike must leave the 3-period window
237        vhf.update_raw(1.0);
238        vhf.update_raw(2.0);
239        vhf.update_raw(3.0);
240        vhf.update_raw(4.0);
241
242        // Window is now [2, 3, 4]: |max - min| = 2, and the SMA(3) of the last
243        // three absolute price changes (1, 1, 1) is 1, so value = 2 / 3 / 1.
244        assert_eq!(vhf.value, 2.0 / 3.0);
245    }
246}