Skip to main content

nautilus_indicators/volatility/
kc.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 nautilus_model::data::Bar;
19
20use crate::{
21    average::{MovingAverageFactory, MovingAverageType},
22    indicator::{Indicator, MovingAverage},
23    volatility::atr::AverageTrueRange,
24};
25
26#[repr(C)]
27#[derive(Debug)]
28#[cfg_attr(
29    feature = "python",
30    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.indicators", unsendable)
31)]
32#[cfg_attr(
33    feature = "python",
34    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.indicators")
35)]
36pub struct KeltnerChannel {
37    pub period: usize,
38    pub k_multiplier: f64,
39    pub ma_type: MovingAverageType,
40    pub ma_type_atr: MovingAverageType,
41    pub use_previous: bool,
42    pub atr_floor: f64,
43    pub upper: f64,
44    pub middle: f64,
45    pub lower: f64,
46    pub initialized: bool,
47    has_inputs: bool,
48    ma: Box<dyn MovingAverage + Send + 'static>,
49    atr: AverageTrueRange,
50}
51
52impl Display for KeltnerChannel {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        write!(f, "{}({})", self.name(), self.period)
55    }
56}
57
58impl Indicator for KeltnerChannel {
59    fn name(&self) -> String {
60        stringify!(KeltnerChannel).to_string()
61    }
62
63    fn has_inputs(&self) -> bool {
64        self.has_inputs
65    }
66
67    fn initialized(&self) -> bool {
68        self.initialized
69    }
70
71    fn handle_bar(&mut self, bar: &Bar) {
72        self.update_raw((&bar.high).into(), (&bar.low).into(), (&bar.close).into());
73    }
74
75    fn reset(&mut self) {
76        self.ma.reset();
77        self.atr.reset();
78        self.upper = 0.0;
79        self.middle = 0.0;
80        self.lower = 0.0;
81        self.has_inputs = false;
82        self.initialized = false;
83    }
84}
85
86impl KeltnerChannel {
87    /// Creates a new [`KeltnerChannel`] instance.
88    #[must_use]
89    pub fn new(
90        period: usize,
91        k_multiplier: f64,
92        ma_type: Option<MovingAverageType>,
93        ma_type_atr: Option<MovingAverageType>,
94        use_previous: Option<bool>,
95        atr_floor: Option<f64>,
96    ) -> Self {
97        Self {
98            period,
99            k_multiplier,
100            ma_type: ma_type.unwrap_or(MovingAverageType::Simple),
101            ma_type_atr: ma_type_atr.unwrap_or(MovingAverageType::Simple),
102            use_previous: use_previous.unwrap_or(true),
103            atr_floor: atr_floor.unwrap_or(0.0),
104            upper: 0.0,
105            middle: 0.0,
106            lower: 0.0,
107            has_inputs: false,
108            initialized: false,
109            ma: MovingAverageFactory::create(ma_type.unwrap_or(MovingAverageType::Simple), period),
110            atr: AverageTrueRange::new(period, ma_type_atr, use_previous, atr_floor),
111        }
112    }
113
114    pub fn update_raw(&mut self, high: f64, low: f64, close: f64) {
115        let typical_price = (high + low + close) / 3.0;
116
117        self.ma.update_raw(typical_price);
118        self.atr.update_raw(high, low, close);
119
120        self.upper = self.atr.value.mul_add(self.k_multiplier, self.ma.value());
121        self.middle = self.ma.value();
122        self.lower = self.atr.value.mul_add(-self.k_multiplier, self.ma.value());
123
124        // Initialization Logic
125        if !self.initialized {
126            self.has_inputs = true;
127
128            if self.ma.initialized() {
129                self.initialized = true;
130            }
131        }
132    }
133}
134
135#[cfg(test)]
136mod tests {
137    use rstest::rstest;
138
139    use super::*;
140    use crate::stubs::kc_10;
141
142    #[rstest]
143    fn test_name_returns_expected_string(kc_10: KeltnerChannel) {
144        assert_eq!(kc_10.name(), "KeltnerChannel");
145    }
146
147    #[rstest]
148    fn test_str_repr_returns_expected_string(kc_10: KeltnerChannel) {
149        assert_eq!(format!("{kc_10}"), "KeltnerChannel(10)");
150    }
151
152    #[rstest]
153    fn test_period_returns_expected_value(kc_10: KeltnerChannel) {
154        assert_eq!(kc_10.period, 10);
155        assert_eq!(kc_10.k_multiplier, 2.0);
156    }
157
158    #[rstest]
159    fn test_initialized_without_inputs_returns_false(kc_10: KeltnerChannel) {
160        assert!(!kc_10.initialized());
161    }
162
163    #[rstest]
164    fn test_value_with_all_higher_inputs_returns_expected_value(mut kc_10: KeltnerChannel) {
165        let high_values = [
166            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,
167        ];
168        let low_values = [
169            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,
170        ];
171
172        let close_values = [
173            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,
174            11.45,
175        ];
176
177        for i in 0..15 {
178            kc_10.update_raw(high_values[i], low_values[i], close_values[i]);
179        }
180
181        assert!(kc_10.initialized());
182        assert_eq!(kc_10.upper, 13.436_666_666_666_666);
183        assert_eq!(kc_10.middle, 9.676_666_666_666_666);
184        assert_eq!(kc_10.lower, 5.916_666_666_666_666);
185    }
186
187    #[rstest]
188    fn test_reset_successfully_returns_indicator_to_fresh_state(mut kc_10: KeltnerChannel) {
189        kc_10.update_raw(1.00020, 1.00050, 1.00030);
190        kc_10.update_raw(1.00030, 1.00060, 1.00040);
191        kc_10.update_raw(1.00070, 1.00080, 1.00075);
192
193        kc_10.reset();
194
195        assert!(!kc_10.initialized());
196        assert!(!kc_10.has_inputs);
197        assert_eq!(kc_10.upper, 0.0);
198        assert_eq!(kc_10.middle, 0.0);
199        assert_eq!(kc_10.lower, 0.0);
200    }
201}