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