nautilus_indicators/momentum/
kvo.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::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 = "nautilus_trader.core.nautilus_pyo3.indicators", unsendable)
30)]
31pub struct KlingerVolumeOscillator {
32    pub fast_period: usize,
33    pub slow_period: usize,
34    pub signal_period: usize,
35    pub ma_type: MovingAverageType,
36    pub value: f64,
37    pub initialized: bool,
38    fast_ma: Box<dyn MovingAverage + Send + 'static>,
39    slow_ma: Box<dyn MovingAverage + Send + 'static>,
40    signal_ma: Box<dyn MovingAverage + Send + 'static>,
41    has_inputs: bool,
42    hlc3: f64,
43    previous_hlc3: f64,
44}
45
46impl Display for KlingerVolumeOscillator {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        write!(
49            f,
50            "{}({},{},{},{})",
51            self.name(),
52            self.fast_period,
53            self.slow_period,
54            self.signal_period,
55            self.ma_type,
56        )
57    }
58}
59
60impl Indicator for KlingerVolumeOscillator {
61    fn name(&self) -> String {
62        stringify!(KlingerVolumeOscillator).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_bar(&mut self, bar: &Bar) {
74        self.update_raw(
75            (&bar.high).into(),
76            (&bar.low).into(),
77            (&bar.close).into(),
78            (&bar.volume).into(),
79        );
80    }
81
82    fn reset(&mut self) {
83        self.hlc3 = 0.0;
84        self.previous_hlc3 = 0.0;
85        self.fast_ma.reset();
86        self.slow_ma.reset();
87        self.signal_ma.reset();
88        self.value = 0.0;
89        self.has_inputs = false;
90        self.initialized = false;
91    }
92}
93
94impl KlingerVolumeOscillator {
95    /// Creates a new [`KlingerVolumeOscillator`] instance.
96    #[must_use]
97    pub fn new(
98        fast_period: usize,
99        slow_period: usize,
100        signal_period: usize,
101        ma_type: Option<MovingAverageType>,
102    ) -> Self {
103        Self {
104            fast_period,
105            slow_period,
106            signal_period,
107            ma_type: ma_type.unwrap_or(MovingAverageType::Simple),
108            value: 0.0,
109            fast_ma: MovingAverageFactory::create(
110                ma_type.unwrap_or(MovingAverageType::Simple),
111                fast_period,
112            ),
113            slow_ma: MovingAverageFactory::create(
114                ma_type.unwrap_or(MovingAverageType::Simple),
115                slow_period,
116            ),
117            signal_ma: MovingAverageFactory::create(
118                ma_type.unwrap_or(MovingAverageType::Simple),
119                signal_period,
120            ),
121            has_inputs: false,
122            hlc3: 0.0,
123            previous_hlc3: 0.0,
124            initialized: false,
125        }
126    }
127
128    pub fn update_raw(&mut self, high: f64, low: f64, close: f64, volume: f64) {
129        self.hlc3 = (high + low + close) / 3.0;
130        if self.hlc3 > self.previous_hlc3 {
131            self.fast_ma.update_raw(volume);
132            self.slow_ma.update_raw(volume);
133        } else if self.hlc3 < self.previous_hlc3 {
134            self.fast_ma.update_raw(-volume);
135            self.slow_ma.update_raw(-volume);
136        } else {
137            self.fast_ma.update_raw(0.0);
138            self.slow_ma.update_raw(0.0);
139        }
140
141        if self.slow_ma.initialized() {
142            self.signal_ma
143                .update_raw(self.fast_ma.value() - self.slow_ma.value());
144            self.value = self.signal_ma.value();
145        }
146
147        // initialization logic
148        if !self.initialized {
149            self.has_inputs = true;
150            if self.signal_ma.initialized() {
151                self.initialized = true;
152            }
153        }
154
155        self.previous_hlc3 = self.hlc3;
156    }
157
158    pub fn _check_initialized(&mut self) {
159        if !self.initialized {
160            self.has_inputs = true;
161            if self.signal_ma.initialized() {
162                self.initialized = true;
163            }
164        }
165    }
166}
167
168////////////////////////////////////////////////////////////////////////////////
169// Tests
170////////////////////////////////////////////////////////////////////////////////
171#[cfg(test)]
172mod tests {
173    use rstest::rstest;
174
175    use super::*;
176    use crate::stubs::kvo_345;
177
178    #[rstest]
179    fn test_name_returns_expected_string(kvo_345: KlingerVolumeOscillator) {
180        assert_eq!(kvo_345.name(), "KlingerVolumeOscillator");
181    }
182
183    #[rstest]
184    fn test_str_repr_returns_expected_string(kvo_345: KlingerVolumeOscillator) {
185        assert_eq!(
186            format!("{kvo_345}"),
187            "KlingerVolumeOscillator(3,4,5,SIMPLE)"
188        );
189    }
190
191    #[rstest]
192    fn test_period_returns_expected_value(kvo_345: KlingerVolumeOscillator) {
193        assert_eq!(kvo_345.fast_period, 3);
194        assert_eq!(kvo_345.slow_period, 4);
195        assert_eq!(kvo_345.signal_period, 5);
196    }
197
198    #[rstest]
199    fn test_initialized_without_inputs_returns_false(kvo_345: KlingerVolumeOscillator) {
200        assert!(!kvo_345.initialized());
201    }
202
203    #[rstest]
204    fn test_value_with_all_higher_inputs_returns_expected_value(
205        mut kvo_345: KlingerVolumeOscillator,
206    ) {
207        let high_values = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
208        let low_values = [0.9, 1.9, 2.9, 3.9, 4.9, 5.9, 6.9, 7.9, 8.9, 9.9];
209        let close_values = [1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 7.1, 8.1, 9.1, 10.1];
210        let volume_values = [
211            100.0, 200.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0,
212        ];
213
214        for i in 0..10 {
215            kvo_345.update_raw(
216                high_values[i],
217                low_values[i],
218                close_values[i],
219                volume_values[i],
220            );
221        }
222
223        assert!(kvo_345.initialized());
224        assert_eq!(kvo_345.value, 50.0);
225    }
226
227    #[rstest]
228    fn test_reset_successfully_returns_indicator_to_fresh_state(
229        mut kvo_345: KlingerVolumeOscillator,
230    ) {
231        kvo_345.update_raw(1.00020, 1.00030, 1.00040, 1.00050);
232        kvo_345.update_raw(1.00030, 1.00040, 1.00050, 1.00060);
233        kvo_345.update_raw(1.00050, 1.00060, 1.00070, 1.00080);
234
235        kvo_345.reset();
236
237        assert!(!kvo_345.initialized());
238        assert_eq!(kvo_345.value, 0.0);
239        assert_eq!(kvo_345.hlc3, 0.0);
240        assert_eq!(kvo_345.previous_hlc3, 0.0);
241    }
242}