nautilus_indicators/momentum/
bb.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::{
17    collections::VecDeque,
18    fmt::{Debug, Display},
19};
20
21use nautilus_model::data::{Bar, QuoteTick, TradeTick};
22
23use crate::{
24    average::{MovingAverageFactory, MovingAverageType},
25    indicator::{Indicator, MovingAverage},
26};
27
28#[repr(C)]
29#[derive(Debug)]
30#[cfg_attr(
31    feature = "python",
32    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.indicators", unsendable)
33)]
34pub struct BollingerBands {
35    pub period: usize,
36    pub k: f64,
37    pub ma_type: MovingAverageType,
38    pub upper: f64,
39    pub middle: f64,
40    pub lower: f64,
41    pub initialized: bool,
42    ma: Box<dyn MovingAverage + Send + 'static>,
43    prices: VecDeque<f64>,
44    has_inputs: bool,
45}
46
47impl Display for BollingerBands {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        write!(
50            f,
51            "{}({},{},{})",
52            self.name(),
53            self.period,
54            self.k,
55            self.ma_type,
56        )
57    }
58}
59
60impl Indicator for BollingerBands {
61    fn name(&self) -> String {
62        stringify!(BollingerBands).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_quote(&mut self, quote: &QuoteTick) {
74        let bid = quote.bid_price.raw as f64;
75        let ask = quote.ask_price.raw as f64;
76        let mid = (bid + ask) / 2.0;
77        self.update_raw(ask, bid, mid);
78    }
79
80    fn handle_trade(&mut self, trade: &TradeTick) {
81        let price = trade.price.raw as f64;
82        self.update_raw(price, price, price);
83    }
84
85    fn handle_bar(&mut self, bar: &Bar) {
86        self.update_raw((&bar.high).into(), (&bar.low).into(), (&bar.close).into());
87    }
88
89    fn reset(&mut self) {
90        self.ma.reset();
91        self.prices.clear();
92        self.upper = 0.0;
93        self.middle = 0.0;
94        self.lower = 0.0;
95        self.has_inputs = false;
96        self.initialized = false;
97    }
98}
99
100impl BollingerBands {
101    /// Creates a new [`BollingerBands`] instance.
102    #[must_use]
103    pub fn new(period: usize, k: f64, ma_type: Option<MovingAverageType>) -> Self {
104        Self {
105            period,
106            k,
107            ma_type: ma_type.unwrap_or(MovingAverageType::Simple),
108            has_inputs: false,
109            initialized: false,
110            upper: 0.0,
111            middle: 0.0,
112            lower: 0.0,
113            ma: MovingAverageFactory::create(ma_type.unwrap_or(MovingAverageType::Simple), period),
114            prices: VecDeque::with_capacity(period),
115        }
116    }
117
118    pub fn update_raw(&mut self, high: f64, low: f64, close: f64) {
119        let typical = (high + low + close) / 3.0;
120        self.prices.push_back(typical);
121        self.ma.update_raw(typical);
122
123        // Initialization logic
124        if !self.initialized {
125            self.has_inputs = true;
126            if self.prices.len() >= self.period {
127                self.initialized = true;
128            }
129        }
130
131        // Calculate values
132        let std = fast_std_with_mean(self.prices.clone(), self.ma.value());
133
134        self.upper = self.k.mul_add(std, self.ma.value());
135        self.middle = self.ma.value();
136        self.lower = self.k.mul_add(-std, self.ma.value());
137    }
138}
139
140#[must_use]
141pub fn fast_std_with_mean(values: VecDeque<f64>, mean: f64) -> f64 {
142    if values.is_empty() {
143        return 0.0;
144    }
145
146    let mut std_dev = 0.0;
147    for v in &values {
148        let diff = v - mean;
149        std_dev += diff * diff;
150    }
151
152    (std_dev / values.len() as f64).sqrt()
153}
154
155////////////////////////////////////////////////////////////////////////////////
156// Tests
157////////////////////////////////////////////////////////////////////////////////
158#[cfg(test)]
159mod tests {
160    use rstest::rstest;
161
162    use super::*;
163    use crate::stubs::bb_10;
164
165    #[rstest]
166    fn test_name_returns_expected_string(bb_10: BollingerBands) {
167        assert_eq!(bb_10.name(), "BollingerBands");
168    }
169
170    #[rstest]
171    fn test_str_repr_returns_expected_string(bb_10: BollingerBands) {
172        assert_eq!(format!("{bb_10}"), "BollingerBands(10,0.1,SIMPLE)");
173    }
174
175    #[rstest]
176    fn test_period_returns_expected_value(bb_10: BollingerBands) {
177        assert_eq!(bb_10.period, 10);
178        assert_eq!(bb_10.k, 0.1);
179    }
180
181    #[rstest]
182    fn test_initialized_without_inputs_returns_false(bb_10: BollingerBands) {
183        assert!(!bb_10.initialized());
184    }
185
186    #[rstest]
187    fn test_value_with_all_higher_inputs_returns_expected_value(mut bb_10: BollingerBands) {
188        let high_values = [
189            1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0,
190        ];
191        let low_values = [
192            0.9, 1.9, 2.9, 3.9, 4.9, 5.9, 6.9, 7.9, 8.9, 9.9, 10.1, 10.2, 10.3, 11.1, 11.4,
193        ];
194
195        let close_values = [
196            0.95, 1.95, 2.95, 3.95, 4.95, 5.95, 6.95, 7.95, 8.95, 9.95, 10.05, 10.15, 10.25, 11.05,
197            11.45,
198        ];
199
200        for i in 0..15 {
201            bb_10.update_raw(high_values[i], low_values[i], close_values[i]);
202        }
203
204        assert!(bb_10.initialized());
205        assert_eq!(bb_10.upper, 10.108_266_446_984_462);
206        assert_eq!(bb_10.middle, 9.676_666_666_666_666);
207        assert_eq!(bb_10.lower, 9.245_066_886_348_87);
208    }
209
210    #[rstest]
211    fn test_reset_successfully_returns_indicator_to_fresh_state(mut bb_10: BollingerBands) {
212        bb_10.update_raw(1.00020, 1.00050, 1.00030);
213        bb_10.update_raw(1.00030, 1.00060, 1.00040);
214        bb_10.update_raw(1.00070, 1.00080, 1.00075);
215
216        bb_10.reset();
217
218        assert!(!bb_10.initialized());
219        assert_eq!(bb_10.upper, 0.0);
220        assert_eq!(bb_10.middle, 0.0);
221        assert_eq!(bb_10.lower, 0.0);
222        assert_eq!(bb_10.prices.len(), 0);
223    }
224}