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#[cfg(test)]
169mod tests {
170    use rstest::rstest;
171
172    use super::*;
173    use crate::stubs::kvo_345;
174
175    #[rstest]
176    fn test_name_returns_expected_string(kvo_345: KlingerVolumeOscillator) {
177        assert_eq!(kvo_345.name(), "KlingerVolumeOscillator");
178    }
179
180    #[rstest]
181    fn test_str_repr_returns_expected_string(kvo_345: KlingerVolumeOscillator) {
182        assert_eq!(
183            format!("{kvo_345}"),
184            "KlingerVolumeOscillator(3,4,5,SIMPLE)"
185        );
186    }
187
188    #[rstest]
189    fn test_period_returns_expected_value(kvo_345: KlingerVolumeOscillator) {
190        assert_eq!(kvo_345.fast_period, 3);
191        assert_eq!(kvo_345.slow_period, 4);
192        assert_eq!(kvo_345.signal_period, 5);
193    }
194
195    #[rstest]
196    fn test_initialized_without_inputs_returns_false(kvo_345: KlingerVolumeOscillator) {
197        assert!(!kvo_345.initialized());
198    }
199
200    #[rstest]
201    fn test_value_with_all_higher_inputs_returns_expected_value(
202        mut kvo_345: KlingerVolumeOscillator,
203    ) {
204        let high_values = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
205        let low_values = [0.9, 1.9, 2.9, 3.9, 4.9, 5.9, 6.9, 7.9, 8.9, 9.9];
206        let close_values = [1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 7.1, 8.1, 9.1, 10.1];
207        let volume_values = [
208            100.0, 200.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0,
209        ];
210
211        for i in 0..10 {
212            kvo_345.update_raw(
213                high_values[i],
214                low_values[i],
215                close_values[i],
216                volume_values[i],
217            );
218        }
219
220        assert!(kvo_345.initialized());
221        assert_eq!(kvo_345.value, 50.0);
222    }
223
224    #[rstest]
225    fn test_reset_successfully_returns_indicator_to_fresh_state(
226        mut kvo_345: KlingerVolumeOscillator,
227    ) {
228        kvo_345.update_raw(1.00020, 1.00030, 1.00040, 1.00050);
229        kvo_345.update_raw(1.00030, 1.00040, 1.00050, 1.00060);
230        kvo_345.update_raw(1.00050, 1.00060, 1.00070, 1.00080);
231
232        kvo_345.reset();
233
234        assert!(!kvo_345.initialized());
235        assert_eq!(kvo_345.value, 0.0);
236        assert_eq!(kvo_345.hlc3, 0.0);
237        assert_eq!(kvo_345.previous_hlc3, 0.0);
238    }
239}