Skip to main content

nautilus_indicators/momentum/
obv.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;
20
21use crate::indicator::Indicator;
22
23const MAX_PERIOD: usize = 1_024;
24
25#[repr(C)]
26#[derive(Debug)]
27#[cfg_attr(
28    feature = "python",
29    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.indicators")
30)]
31#[cfg_attr(
32    feature = "python",
33    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.indicators")
34)]
35pub struct OnBalanceVolume {
36    pub period: usize,
37    pub value: f64,
38    pub initialized: bool,
39    has_inputs: bool,
40    obv: ArrayDeque<f64, MAX_PERIOD, Wrapping>,
41}
42
43impl Display for OnBalanceVolume {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        write!(f, "{}({})", self.name(), self.period)
46    }
47}
48
49impl Indicator for OnBalanceVolume {
50    fn name(&self) -> String {
51        stringify!(OnBalanceVolume).to_string()
52    }
53
54    fn has_inputs(&self) -> bool {
55        self.has_inputs
56    }
57
58    fn initialized(&self) -> bool {
59        self.initialized
60    }
61
62    fn handle_bar(&mut self, bar: &Bar) {
63        self.update_raw(
64            (&bar.open).into(),
65            (&bar.close).into(),
66            (&bar.volume).into(),
67        );
68    }
69
70    fn reset(&mut self) {
71        self.obv.clear();
72        self.value = 0.0;
73        self.has_inputs = false;
74        self.initialized = false;
75    }
76}
77
78impl OnBalanceVolume {
79    /// Creates a new [`OnBalanceVolume`] instance.
80    ///
81    /// # Panics
82    ///
83    /// This function panics if:
84    /// - `period` is greater than `MAX_PERIOD`.
85    #[must_use]
86    pub fn new(period: usize) -> Self {
87        assert!(
88            period <= MAX_PERIOD,
89            "OnBalanceVolume: period {period} exceeds MAX_PERIOD ({MAX_PERIOD})"
90        );
91
92        Self {
93            period,
94            value: 0.0,
95            obv: ArrayDeque::new(),
96            has_inputs: false,
97            initialized: false,
98        }
99    }
100
101    pub fn update_raw(&mut self, open: f64, close: f64, volume: f64) {
102        let delta = if close > open {
103            volume
104        } else if close < open {
105            -volume
106        } else {
107            0.0
108        };
109
110        let _ = self.obv.push_back(delta);
111
112        self.value = self.obv.iter().sum();
113
114        if !self.initialized {
115            self.has_inputs = true;
116
117            if (self.period == 0 && !self.obv.is_empty()) || self.obv.len() >= self.period {
118                self.initialized = true;
119            }
120        }
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use rstest::rstest;
127
128    use super::*;
129    use crate::stubs::obv_10;
130
131    #[rstest]
132    fn test_name_returns_expected_string(obv_10: OnBalanceVolume) {
133        assert_eq!(obv_10.name(), "OnBalanceVolume");
134    }
135
136    #[rstest]
137    fn test_str_repr_returns_expected_string(obv_10: OnBalanceVolume) {
138        assert_eq!(format!("{obv_10}"), "OnBalanceVolume(10)");
139    }
140
141    #[rstest]
142    fn test_period_returns_expected_value(obv_10: OnBalanceVolume) {
143        assert_eq!(obv_10.period, 10);
144    }
145
146    #[rstest]
147    fn test_initialized_without_inputs_returns_false(obv_10: OnBalanceVolume) {
148        assert!(!obv_10.initialized());
149    }
150
151    #[rstest]
152    fn test_value_with_all_higher_inputs_returns_expected_value(mut obv_10: OnBalanceVolume) {
153        let open_values = [
154            104.25, 105.50, 106.75, 108.00, 109.25, 110.50, 111.75, 113.00, 114.25, 115.50, 116.75,
155            118.00, 119.25, 120.50, 121.75,
156        ];
157
158        let close_values = [
159            105.50, 106.75, 108.00, 109.25, 110.50, 111.75, 113.00, 114.25, 115.50, 116.75, 118.00,
160            119.25, 120.50, 121.75, 123.00,
161        ];
162
163        let volume_values = [
164            1000.0, 1200.0, 1500.0, 1800.0, 2000.0, 2200.0, 2500.0, 2800.0, 3000.0, 3200.0, 3500.0,
165            3800.0, 4000.0, 4200.0, 4500.0,
166        ];
167
168        for i in 0..15 {
169            obv_10.update_raw(open_values[i], close_values[i], volume_values[i]);
170        }
171
172        assert!(obv_10.initialized());
173        assert_eq!(obv_10.value, 41200.0);
174    }
175
176    #[rstest]
177    fn test_reset_successfully_returns_indicator_to_fresh_state(mut obv_10: OnBalanceVolume) {
178        obv_10.update_raw(1.00020, 1.00050, 1000.0);
179        obv_10.update_raw(1.00030, 1.00060, 1200.0);
180        obv_10.update_raw(1.00070, 1.00080, 1500.0);
181
182        obv_10.reset();
183
184        assert!(!obv_10.initialized());
185        assert_eq!(obv_10.value, 0.0);
186        assert_eq!(obv_10.obv.len(), 0);
187        assert!(!obv_10.has_inputs);
188        assert!(!obv_10.initialized);
189    }
190}