nautilus_indicators/momentum/
bb.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2024 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

use std::{
    collections::VecDeque,
    fmt::{Debug, Display},
};

use nautilus_model::data::{bar::Bar, quote::QuoteTick, trade::TradeTick};

use crate::{
    average::{MovingAverageFactory, MovingAverageType},
    indicator::{Indicator, MovingAverage},
};

#[repr(C)]
#[derive(Debug)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.indicators")
)]
pub struct BollingerBands {
    pub period: usize,
    pub k: f64,
    pub ma_type: MovingAverageType,
    pub upper: f64,
    pub middle: f64,
    pub lower: f64,
    pub initialized: bool,
    ma: Box<dyn MovingAverage + Send + 'static>,
    prices: VecDeque<f64>,
    has_inputs: bool,
}

impl Display for BollingerBands {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}({},{},{})",
            self.name(),
            self.period,
            self.k,
            self.ma_type,
        )
    }
}

impl Indicator for BollingerBands {
    fn name(&self) -> String {
        stringify!(BollingerBands).to_string()
    }

    fn has_inputs(&self) -> bool {
        self.has_inputs
    }

    fn initialized(&self) -> bool {
        self.initialized
    }

    fn handle_quote(&mut self, quote: &QuoteTick) {
        let bid = quote.bid_price.raw as f64;
        let ask = quote.ask_price.raw as f64;
        let mid = (bid + ask) / 2.0;
        self.update_raw(ask, bid, mid);
    }

    fn handle_trade(&mut self, trade: &TradeTick) {
        let price = trade.price.raw as f64;
        self.update_raw(price, price, price);
    }

    fn handle_bar(&mut self, bar: &Bar) {
        self.update_raw((&bar.high).into(), (&bar.low).into(), (&bar.close).into());
    }

    fn reset(&mut self) {
        self.ma.reset();
        self.prices.clear();
        self.upper = 0.0;
        self.middle = 0.0;
        self.lower = 0.0;
        self.has_inputs = false;
        self.initialized = false;
    }
}

impl BollingerBands {
    /// Creates a new [`BollingerBands`] instance.
    #[must_use]
    pub fn new(period: usize, k: f64, ma_type: Option<MovingAverageType>) -> Self {
        Self {
            period,
            k,
            ma_type: ma_type.unwrap_or(MovingAverageType::Simple),
            has_inputs: false,
            initialized: false,
            upper: 0.0,
            middle: 0.0,
            lower: 0.0,
            ma: MovingAverageFactory::create(ma_type.unwrap_or(MovingAverageType::Simple), period),
            prices: VecDeque::with_capacity(period),
        }
    }

    pub fn update_raw(&mut self, high: f64, low: f64, close: f64) {
        let typical = (high + low + close) / 3.0;
        self.prices.push_back(typical);
        self.ma.update_raw(typical);

        // Initialization logic
        if !self.initialized {
            self.has_inputs = true;
            if self.prices.len() >= self.period {
                self.initialized = true;
            }
        }

        // Calculate values
        let std = fast_std_with_mean(self.prices.clone(), self.ma.value());

        self.upper = self.k.mul_add(std, self.ma.value());
        self.middle = self.ma.value();
        self.lower = self.k.mul_add(-std, self.ma.value());
    }
}

#[must_use]
pub fn fast_std_with_mean(values: VecDeque<f64>, mean: f64) -> f64 {
    if values.is_empty() {
        return 0.0;
    }

    let mut std_dev = 0.0;
    for v in &values {
        let diff = v - mean;
        std_dev += diff * diff;
    }

    (std_dev / values.len() as f64).sqrt()
}

////////////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////////////
#[cfg(test)]
mod tests {
    use rstest::rstest;

    use super::*;
    use crate::stubs::bb_10;

    #[rstest]
    fn test_name_returns_expected_string(bb_10: BollingerBands) {
        assert_eq!(bb_10.name(), "BollingerBands");
    }

    #[rstest]
    fn test_str_repr_returns_expected_string(bb_10: BollingerBands) {
        assert_eq!(format!("{bb_10}"), "BollingerBands(10,0.1,SIMPLE)");
    }

    #[rstest]
    fn test_period_returns_expected_value(bb_10: BollingerBands) {
        assert_eq!(bb_10.period, 10);
        assert_eq!(bb_10.k, 0.1);
    }

    #[rstest]
    fn test_initialized_without_inputs_returns_false(bb_10: BollingerBands) {
        assert!(!bb_10.initialized());
    }

    #[rstest]
    fn test_value_with_all_higher_inputs_returns_expected_value(mut bb_10: BollingerBands) {
        let high_values = [
            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,
        ];
        let low_values = [
            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,
        ];

        let close_values = [
            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,
            11.45,
        ];

        for i in 0..15 {
            bb_10.update_raw(high_values[i], low_values[i], close_values[i]);
        }

        assert!(bb_10.initialized());
        assert_eq!(bb_10.upper, 10.108_266_446_984_462);
        assert_eq!(bb_10.middle, 9.676_666_666_666_666);
        assert_eq!(bb_10.lower, 9.245_066_886_348_87);
    }

    #[rstest]
    fn test_reset_successfully_returns_indicator_to_fresh_state(mut bb_10: BollingerBands) {
        bb_10.update_raw(1.00020, 1.00050, 1.00030);
        bb_10.update_raw(1.00030, 1.00060, 1.00040);
        bb_10.update_raw(1.00070, 1.00080, 1.00075);

        bb_10.reset();

        assert!(!bb_10.initialized());
        assert_eq!(bb_10.upper, 0.0);
        assert_eq!(bb_10.middle, 0.0);
        assert_eq!(bb_10.lower, 0.0);
        assert_eq!(bb_10.prices.len(), 0);
    }
}