Skip to main content

nautilus_indicators/momentum/
bb.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::{Debug, Display};
17
18use arraydeque::{ArrayDeque, Wrapping};
19use nautilus_model::data::{Bar, QuoteTick, TradeTick};
20
21use crate::{
22    average::{MovingAverageFactory, MovingAverageType},
23    indicator::{Indicator, MovingAverage},
24};
25
26pub const MAX_PERIOD: usize = 1_024;
27
28#[repr(C)]
29#[derive(Debug)]
30#[cfg_attr(
31    feature = "python",
32    pyo3::pyclass(module = "nautilus_trader.indicators", unsendable)
33)]
34#[cfg_attr(
35    feature = "python",
36    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.indicators")
37)]
38pub struct BollingerBands {
39    pub period: usize,
40    pub k: f64,
41    pub ma_type: MovingAverageType,
42    pub upper: f64,
43    pub middle: f64,
44    pub lower: f64,
45    pub initialized: bool,
46    ma: Box<dyn MovingAverage + Send + 'static>,
47    prices: ArrayDeque<f64, MAX_PERIOD, Wrapping>,
48    has_inputs: bool,
49}
50
51impl Display for BollingerBands {
52    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
53        write!(
54            f,
55            "{}({},{},{})",
56            self.name(),
57            self.period,
58            self.k,
59            self.ma_type,
60        )
61    }
62}
63
64impl Indicator for BollingerBands {
65    fn name(&self) -> String {
66        stringify!(BollingerBands).into()
67    }
68
69    fn has_inputs(&self) -> bool {
70        self.has_inputs
71    }
72
73    fn initialized(&self) -> bool {
74        self.initialized
75    }
76
77    fn handle_quote(&mut self, quote: &QuoteTick) -> anyhow::Result<()> {
78        let bid = (&quote.bid_price).into();
79        let ask = (&quote.ask_price).into();
80        let mid = f64::midpoint(bid, ask);
81        self.update_raw(ask, bid, mid);
82        Ok(())
83    }
84
85    fn handle_trade(&mut self, trade: &TradeTick) {
86        let price = (&trade.price).into();
87        self.update_raw(price, price, price);
88    }
89
90    fn handle_bar(&mut self, bar: &Bar) {
91        self.update_raw((&bar.high).into(), (&bar.low).into(), (&bar.close).into());
92    }
93
94    fn reset(&mut self) {
95        self.ma.reset();
96        self.prices.clear();
97        self.upper = 0.0;
98        self.middle = 0.0;
99        self.lower = 0.0;
100        self.has_inputs = false;
101        self.initialized = false;
102    }
103}
104
105impl BollingerBands {
106    /// Creates a new [`BollingerBands`] instance.
107    ///
108    /// # Panics
109    ///
110    /// - If `period` is `0` or greater than `MAX_PERIOD`.
111    /// - If `k` is *not finite* or *≤ 0*.
112    #[must_use]
113    pub fn new(period: usize, k: f64, ma_type: Option<MovingAverageType>) -> Self {
114        assert!(
115            (1..=MAX_PERIOD).contains(&period),
116            "BollingerBands: period {period} out of range (1..={MAX_PERIOD})"
117        );
118        assert!(
119            k.is_finite() && k > 0.0,
120            "BollingerBands: k must be positive and finite (received {k})"
121        );
122
123        Self {
124            period,
125            k,
126            ma_type: ma_type.unwrap_or(MovingAverageType::Simple),
127            ma: MovingAverageFactory::create(ma_type.unwrap_or(MovingAverageType::Simple), period),
128            prices: ArrayDeque::new(),
129            has_inputs: false,
130            initialized: false,
131            upper: 0.0,
132            middle: 0.0,
133            lower: 0.0,
134        }
135    }
136
137    pub fn update_raw(&mut self, high: f64, low: f64, close: f64) {
138        let typical = (high + low + close) / 3.0;
139
140        if self.prices.len() == self.period {
141            let _ = self.prices.pop_front();
142        }
143        let _ = self.prices.push_back(typical);
144        self.ma.update_raw(typical);
145
146        if !self.initialized {
147            self.has_inputs = true;
148
149            if self.prices.len() >= self.period {
150                self.initialized = true;
151            }
152        }
153
154        let std = fast_std_with_mean(
155            self.prices.iter().rev().take(self.period).copied(),
156            self.ma.value(),
157        );
158
159        self.upper = self.k.mul_add(std, self.ma.value());
160        self.middle = self.ma.value();
161        self.lower = self.k.mul_add(-std, self.ma.value());
162    }
163}
164
165#[must_use]
166pub fn fast_std_with_mean<I>(values: I, mean: f64) -> f64
167where
168    I: IntoIterator<Item = f64>,
169{
170    let mut var_acc = 0.0_f64;
171    let mut count = 0_usize;
172
173    for v in values {
174        let diff = v - mean;
175        var_acc += diff * diff;
176        count += 1;
177    }
178
179    if count == 0 {
180        return 0.0;
181    }
182
183    let variance = var_acc / count as f64;
184    variance.sqrt()
185}
186
187#[cfg(test)]
188mod tests {
189    use nautilus_model::{
190        enums::AggressorSide,
191        identifiers::{InstrumentId, TradeId},
192        types::{Price, Quantity},
193    };
194    use rstest::rstest;
195
196    use super::*;
197    use crate::{
198        stubs::{bb_10, stub_quote},
199        testing::assert_approx_equal,
200    };
201
202    #[rstest]
203    fn test_name_returns_expected_string(bb_10: BollingerBands) {
204        assert_eq!(bb_10.name(), "BollingerBands");
205    }
206
207    #[rstest]
208    fn test_str_repr_returns_expected_string(bb_10: BollingerBands) {
209        assert_eq!(format!("{bb_10}"), "BollingerBands(10,0.1,SIMPLE)");
210    }
211
212    #[rstest]
213    fn test_period_returns_expected_value(bb_10: BollingerBands) {
214        assert_eq!(bb_10.period, 10);
215        assert_eq!(bb_10.k, 0.1);
216    }
217
218    #[rstest]
219    fn test_initialized_without_inputs_returns_false(bb_10: BollingerBands) {
220        assert!(!bb_10.initialized());
221    }
222
223    #[rstest]
224    fn test_value_with_all_higher_inputs_returns_expected_value(mut bb_10: BollingerBands) {
225        let high_values = [
226            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,
227        ];
228        let low_values = [
229            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,
230        ];
231        let close_values = [
232            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,
233            11.45,
234        ];
235
236        for i in 0..15 {
237            bb_10.update_raw(high_values[i], low_values[i], close_values[i]);
238        }
239
240        assert!(bb_10.initialized());
241        assert_approx_equal(bb_10.upper, 9.8844582289);
242        assert_approx_equal(bb_10.middle, 9.67666666667);
243        assert_approx_equal(bb_10.lower, 9.46887510444);
244    }
245
246    #[rstest]
247    fn test_reset_successfully_returns_indicator_to_fresh_state(mut bb_10: BollingerBands) {
248        bb_10.update_raw(1.00020, 1.00050, 1.00030);
249        bb_10.update_raw(1.00030, 1.00060, 1.00040);
250        bb_10.update_raw(1.00070, 1.00080, 1.00075);
251
252        bb_10.reset();
253
254        assert!(!bb_10.initialized());
255        assert_eq!(bb_10.upper, 0.0);
256        assert_eq!(bb_10.middle, 0.0);
257        assert_eq!(bb_10.lower, 0.0);
258        assert_eq!(bb_10.prices.len(), 0);
259    }
260
261    #[rstest]
262    #[should_panic(expected = "k must be positive")]
263    fn test_new_panics_on_zero_k() {
264        let _ = BollingerBands::new(10, 0.0, None);
265    }
266
267    #[rstest]
268    #[should_panic(expected = "k must be positive")]
269    fn test_new_panics_on_negative_k() {
270        let _ = BollingerBands::new(10, -2.0, None);
271    }
272
273    #[rstest]
274    #[should_panic(expected = "k must be positive")]
275    fn test_new_panics_on_nan_k() {
276        let _ = BollingerBands::new(10, f64::NAN, None);
277    }
278
279    #[rstest]
280    fn test_std_dev_uses_sliding_window() {
281        let mut bb = BollingerBands::new(3, 1.0, None);
282
283        for v in 1..=6 {
284            bb.update_raw(f64::from(v), f64::from(v), f64::from(v));
285        }
286
287        let expected_mid: f64 = (4.0 + 5.0 + 6.0) / 3.0;
288        let variance = (6.0 - expected_mid).mul_add(
289            6.0 - expected_mid,
290            (4.0 - expected_mid).mul_add(
291                4.0 - expected_mid,
292                (5.0 - expected_mid) * (5.0 - expected_mid),
293            ),
294        ) / 3.0;
295        let expected_std = variance.sqrt();
296
297        assert!((bb.middle - expected_mid).abs() < 1e-12);
298        assert!((bb.upper - (expected_mid + expected_std)).abs() < 1e-12);
299        assert!((bb.lower - (expected_mid - expected_std)).abs() < 1e-12);
300    }
301
302    #[rstest]
303    fn test_handle_trade_outputs_actual_price_units() {
304        let prices = ["10.00", "11.00", "12.00"];
305        let mut from_trades = BollingerBands::new(3, 1.0, None);
306        let mut from_raw = BollingerBands::new(3, 1.0, None);
307
308        for price in prices {
309            from_trades.handle_trade(&trade_tick(price));
310            let value: f64 = Price::from(price).into();
311            from_raw.update_raw(value, value, value);
312        }
313
314        let expected_mid = 11.0;
315        let expected_std = (2.0_f64 / 3.0).sqrt();
316
317        assert!(from_trades.initialized());
318        assert_approx_equal(from_trades.middle, expected_mid);
319        assert_approx_equal(from_trades.upper, expected_mid + expected_std);
320        assert_approx_equal(from_trades.lower, expected_mid - expected_std);
321        assert_approx_equal(from_trades.middle, from_raw.middle);
322        assert_approx_equal(from_trades.upper, from_raw.upper);
323        assert_approx_equal(from_trades.lower, from_raw.lower);
324    }
325
326    #[rstest]
327    fn test_handle_quote_outputs_actual_price_units() {
328        let quotes = [("10.00", "10.50"), ("11.00", "11.50"), ("12.00", "12.50")];
329        let mut from_quotes = BollingerBands::new(3, 1.0, None);
330        let mut from_raw = BollingerBands::new(3, 1.0, None);
331
332        for (bid, ask) in quotes {
333            let quote = stub_quote(bid, ask);
334            from_quotes.handle_quote(&quote).unwrap();
335            let bid_f64: f64 = (&quote.bid_price).into();
336            let ask_f64: f64 = (&quote.ask_price).into();
337            let mid = f64::midpoint(bid_f64, ask_f64);
338            from_raw.update_raw(ask_f64, bid_f64, mid);
339        }
340
341        let expected_mid = 11.25;
342        let expected_std = (2.0_f64 / 3.0).sqrt();
343
344        assert!(from_quotes.initialized());
345        assert_approx_equal(from_quotes.middle, expected_mid);
346        assert_approx_equal(from_quotes.upper, expected_mid + expected_std);
347        assert_approx_equal(from_quotes.lower, expected_mid - expected_std);
348        assert_approx_equal(from_quotes.middle, from_raw.middle);
349        assert_approx_equal(from_quotes.upper, from_raw.upper);
350        assert_approx_equal(from_quotes.lower, from_raw.lower);
351    }
352
353    fn trade_tick(price: &str) -> TradeTick {
354        TradeTick::new(
355            InstrumentId::from("ETHUSDT-PERP.BINANCE"),
356            Price::from(price),
357            Quantity::from("1.00000000"),
358            AggressorSide::Buy,
359            TradeId::from("1"),
360            1.into(),
361            0.into(),
362        )
363    }
364}