Skip to main content

nautilus_indicators/volatility/
kp.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_core::correctness::FAILED;
19use nautilus_model::data::Bar;
20
21use super::kc::KeltnerChannel;
22use crate::{average::MovingAverageType, indicator::Indicator, support::is_valid_hlc};
23
24#[repr(C)]
25#[derive(Debug)]
26#[cfg_attr(
27    feature = "python",
28    pyo3::pyclass(module = "nautilus_trader.indicators", unsendable)
29)]
30#[cfg_attr(
31    feature = "python",
32    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.indicators")
33)]
34pub struct KeltnerPosition {
35    pub period: usize,
36    pub k_multiplier: f64,
37    pub ma_type: MovingAverageType,
38    pub ma_type_atr: MovingAverageType,
39    pub use_previous: bool,
40    pub atr_floor: f64,
41    pub value: f64,
42    pub initialized: bool,
43    has_inputs: bool,
44    kc: KeltnerChannel,
45}
46
47impl Display for KeltnerPosition {
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_multiplier,
55            self.ma_type,
56            self.ma_type_atr,
57            self.use_previous
58        )
59    }
60}
61
62impl Indicator for KeltnerPosition {
63    fn name(&self) -> String {
64        stringify!(KeltnerPosition).to_string()
65    }
66
67    fn has_inputs(&self) -> bool {
68        self.has_inputs
69    }
70
71    fn initialized(&self) -> bool {
72        self.initialized
73    }
74
75    fn handle_bar(&mut self, bar: &Bar) {
76        self.update_raw((&bar.high).into(), (&bar.low).into(), (&bar.close).into());
77    }
78
79    fn reset(&mut self) {
80        self.kc.reset();
81        self.value = 0.0;
82        self.has_inputs = false;
83        self.initialized = false;
84    }
85}
86
87impl KeltnerPosition {
88    /// Creates a new [`KeltnerPosition`] instance.
89    ///
90    /// # Panics
91    ///
92    /// Panics if `period` is outside `1..=MAX_PERIOD`, the multiplier is not positive and finite,
93    /// or the ATR floor is negative or non-finite.
94    #[must_use]
95    pub fn new(
96        period: usize,
97        k_multiplier: f64,
98        ma_type: Option<MovingAverageType>,
99        ma_type_atr: Option<MovingAverageType>,
100        use_previous: Option<bool>,
101        atr_floor: Option<f64>,
102    ) -> Self {
103        Self::new_checked(
104            period,
105            k_multiplier,
106            ma_type,
107            ma_type_atr,
108            use_previous,
109            atr_floor,
110        )
111        .expect(FAILED)
112    }
113
114    pub(crate) fn new_checked(
115        period: usize,
116        k_multiplier: f64,
117        ma_type: Option<MovingAverageType>,
118        ma_type_atr: Option<MovingAverageType>,
119        use_previous: Option<bool>,
120        atr_floor: Option<f64>,
121    ) -> anyhow::Result<Self> {
122        let kc = KeltnerChannel::new_checked(
123            period,
124            k_multiplier,
125            None,
126            ma_type,
127            ma_type_atr.or(Some(MovingAverageType::Simple)),
128            use_previous,
129            atr_floor,
130        )?;
131        Ok(Self {
132            period,
133            k_multiplier,
134            ma_type: ma_type.unwrap_or(MovingAverageType::Exponential),
135            ma_type_atr: ma_type_atr.unwrap_or(MovingAverageType::Simple),
136            use_previous: use_previous.unwrap_or(true),
137            atr_floor: atr_floor.unwrap_or(0.0),
138            value: 0.0,
139            has_inputs: false,
140            initialized: false,
141            kc,
142        })
143    }
144
145    pub fn update_raw(&mut self, high: f64, low: f64, close: f64) {
146        if !is_valid_hlc(high, low, close) {
147            return;
148        }
149
150        self.kc.update_raw(high, low, close);
151
152        // Initialization logic
153        if !self.initialized {
154            self.has_inputs = true;
155
156            if self.kc.initialized() {
157                self.initialized = true;
158            }
159        }
160
161        let k_width = (self.kc.upper - self.kc.lower) / 2.0;
162
163        if k_width > 0.0 {
164            self.value = (close - self.kc.middle) / k_width;
165        } else {
166            self.value = 0.0;
167        }
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use rstest::rstest;
174
175    use super::*;
176    use crate::{stubs::kp_10, testing::assert_approx_equal};
177
178    #[rstest]
179    fn test_name_returns_expected_string(kp_10: KeltnerPosition) {
180        assert_eq!(kp_10.name(), "KeltnerPosition");
181    }
182
183    #[rstest]
184    fn test_str_repr_returns_expected_string(kp_10: KeltnerPosition) {
185        assert_eq!(
186            format!("{kp_10}"),
187            "KeltnerPosition(10,2,SIMPLE,SIMPLE,true)"
188        );
189    }
190
191    #[rstest]
192    fn test_period_returns_expected_value(kp_10: KeltnerPosition) {
193        assert_eq!(kp_10.period, 10);
194        assert_eq!(kp_10.k_multiplier, 2.0);
195    }
196
197    #[rstest]
198    fn test_initialized_without_inputs_returns_false(kp_10: KeltnerPosition) {
199        assert!(!kp_10.initialized());
200    }
201
202    #[rstest]
203    fn test_value_with_all_higher_inputs_returns_expected_value(mut kp_10: KeltnerPosition) {
204        let high_values = [
205            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,
206        ];
207        let low_values = [
208            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,
209        ];
210
211        let close_values = [
212            0.95, 1.95, 2.95, 3.95, 4.95, 5.95, 6.95, 7.95, 8.95, 9.95, 10.55, 11.1, 12.0, 13.0,
213            14.0,
214        ];
215
216        for i in 0..15 {
217            kp_10.update_raw(high_values[i], low_values[i], close_values[i]);
218        }
219
220        assert!(kp_10.initialized());
221        assert_approx_equal(kp_10.value, 1.17533718690);
222    }
223
224    #[rstest]
225    fn test_reset_successfully_returns_indicator_to_fresh_state(mut kp_10: KeltnerPosition) {
226        for _ in 0..9 {
227            kp_10.update_raw(11.0, 9.0, 10.0);
228        }
229        kp_10.update_raw(11.0, 9.0, 10.5);
230        // The last typical price 61/6 lifts the simple centerline to 10 + 1/60;
231        // true range stays 2, so the half band width is 2 * 2
232        let middle = 10.0 + 1.0 / 60.0;
233        assert!(kp_10.initialized());
234        assert!((kp_10.kc.middle - middle).abs() < 1e-12);
235        assert!((kp_10.kc.upper - (middle + 4.0)).abs() < 1e-12);
236        assert!((kp_10.kc.lower - (middle - 4.0)).abs() < 1e-12);
237        assert!((kp_10.value - (10.5 - middle) / 4.0).abs() < 1e-12);
238
239        kp_10.reset();
240
241        assert!(!kp_10.initialized());
242        assert!(!kp_10.has_inputs);
243        assert_eq!(kp_10.value, 0.0);
244        assert_eq!(kp_10.kc.upper, 0.0);
245        assert_eq!(kp_10.kc.middle, 0.0);
246        assert_eq!(kp_10.kc.lower, 0.0);
247    }
248
249    #[rstest]
250    #[case(1.0, 2.0, 2.0)]
251    #[case(2.0, 1.0, 2.5)]
252    #[case(2.0, 1.0, f64::NAN)]
253    fn test_rejected_candle_leaves_state_unchanged(
254        #[case] high: f64,
255        #[case] low: f64,
256        #[case] close: f64,
257    ) {
258        let mut kp = KeltnerPosition::new(
259            1,
260            2.0,
261            Some(MovingAverageType::Simple),
262            Some(MovingAverageType::Simple),
263            None,
264            None,
265        );
266        kp.update_raw(2.0, 1.0, 1.5);
267        kp.update_raw(high, low, close);
268
269        assert!(kp.initialized());
270        assert_eq!(kp.kc.middle, 1.5);
271        assert_eq!(kp.value, 0.0);
272    }
273
274    #[rstest]
275    fn test_new_defaults_to_exponential_moving_average() {
276        let mut kp = KeltnerPosition::new(10, 2.0, None, None, None, None);
277        let high_values = [
278            100.75, 102.5, 102.0, 103.0, 104.0, 102.25, 101.25, 103.0, 105.75, 104.5, 106.0, 105.5,
279            107.25, 106.5, 108.25, 107.0, 109.0, 108.75, 110.0, 109.5,
280        ];
281        let low_values = [
282            99.5, 100.75, 100.25, 101.5, 102.5, 100.25, 100.0, 101.25, 104.0, 103.0, 104.5, 103.5,
283            106.0, 104.75, 106.5, 105.5, 107.5, 106.75, 108.75, 107.75,
284        ];
285        let close_values = [
286            100.0, 101.5, 100.75, 102.25, 103.0, 101.0, 100.5, 102.0, 104.5, 103.75, 105.0, 104.25,
287            106.5, 105.5, 107.0, 106.25, 108.0, 107.5, 109.25, 108.5,
288        ];
289
290        for i in 0..20 {
291            kp.update_raw(high_values[i], low_values[i], close_values[i]);
292        }
293
294        assert_eq!(kp.ma_type, MovingAverageType::Exponential);
295        assert_eq!(kp.ma_type_atr, MovingAverageType::Simple);
296        assert!(kp.initialized());
297        assert_approx_equal(kp.value, 0.364862661420);
298    }
299}