nautilus_indicators/momentum/
obv.rs

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