nautilus_indicators/momentum/
pressure.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 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)]
32pub struct Pressure {
33    pub period: usize,
34    pub ma_type: MovingAverageType,
35    pub atr_floor: f64,
36    pub value: f64,
37    pub value_cumulative: f64,
38    pub initialized: bool,
39    atr: AverageTrueRange,
40    average_volume: Box<dyn MovingAverage + Send + 'static>,
41    has_inputs: bool,
42}
43
44impl Display for Pressure {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        write!(f, "{}({},{})", self.name(), self.period, self.ma_type,)
47    }
48}
49
50impl Indicator for Pressure {
51    fn name(&self) -> String {
52        stringify!(Pressure).to_string()
53    }
54
55    fn has_inputs(&self) -> bool {
56        self.has_inputs
57    }
58
59    fn initialized(&self) -> bool {
60        self.initialized
61    }
62
63    fn handle_bar(&mut self, bar: &Bar) {
64        self.update_raw(
65            (&bar.high).into(),
66            (&bar.low).into(),
67            (&bar.close).into(),
68            (&bar.volume).into(),
69        );
70    }
71
72    fn reset(&mut self) {
73        self.atr.reset();
74        self.average_volume.reset();
75        self.value = 0.0;
76        self.value_cumulative = 0.0;
77        self.has_inputs = false;
78        self.initialized = false;
79    }
80}
81
82impl Pressure {
83    /// Creates a new [`Pressure`] instance.
84    ///
85    /// # Panics
86    ///
87    /// Panics if `period` is not positive (> 0).
88    #[must_use]
89    pub fn new(period: usize, ma_type: Option<MovingAverageType>, atr_floor: Option<f64>) -> Self {
90        assert!(period > 0, "Pressure: period must be > 0");
91        let ma_type = ma_type.unwrap_or(MovingAverageType::Exponential);
92        Self {
93            period,
94            ma_type,
95            atr_floor: atr_floor.unwrap_or(0.0),
96            value: 0.0,
97            value_cumulative: 0.0,
98            atr: AverageTrueRange::new(period, Some(ma_type), Some(false), atr_floor),
99            average_volume: MovingAverageFactory::create(ma_type, period),
100            has_inputs: false,
101            initialized: false,
102        }
103    }
104
105    pub fn update_raw(&mut self, high: f64, low: f64, close: f64, volume: f64) {
106        self.atr.update_raw(high, low, close);
107        self.average_volume.update_raw(volume);
108
109        self.has_inputs = true;
110
111        let avg_vol = self.average_volume.value();
112        if avg_vol == 0.0 {
113            self.value = 0.0;
114            return;
115        }
116
117        let atr_val = if self.atr.value > 0.0 {
118            self.atr.value
119        } else {
120            (high - low).abs().max(self.atr_floor)
121        };
122
123        if atr_val == 0.0 {
124            self.value = 0.0;
125            return;
126        }
127
128        let relative_volume = volume / avg_vol;
129        let buy_pressure = ((close - low) / atr_val) * relative_volume;
130        let sell_pressure = ((high - close) / atr_val) * relative_volume;
131
132        self.value = buy_pressure - sell_pressure;
133        self.value_cumulative += self.value;
134
135        if self.atr.initialized && self.average_volume.initialized() && !self.initialized {
136            self.initialized = true;
137        }
138    }
139}
140
141#[cfg(test)]
142mod tests {
143    use rstest::rstest;
144
145    use super::*;
146    use crate::stubs::{bar_ethusdt_binance_minute_bid, pressure_10};
147
148    #[rstest]
149    fn test_name_returns_expected_string(pressure_10: Pressure) {
150        assert_eq!(pressure_10.name(), "Pressure");
151    }
152
153    #[rstest]
154    fn test_str_repr_returns_expected_string() {
155        let pressure = Pressure::new(10, Some(MovingAverageType::Exponential), None);
156        assert_eq!(format!("{pressure}"), "Pressure(10,EXPONENTIAL)");
157    }
158
159    #[rstest]
160    fn test_period_returns_expected_value(pressure_10: Pressure) {
161        assert_eq!(pressure_10.period, 10);
162    }
163
164    #[rstest]
165    fn test_initialized_without_inputs_returns_false(pressure_10: Pressure) {
166        assert!(!pressure_10.initialized());
167    }
168
169    #[rstest]
170    fn test_value_with_all_higher_inputs_returns_expected_value() {
171        let mut pressure = Pressure::new(10, Some(MovingAverageType::Exponential), None);
172
173        let high_values = [
174            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,
175        ];
176        let low_values = [
177            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,
178        ];
179        let close_values = [
180            1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 7.1, 8.1, 9.1, 10.1, 11.1, 12.1, 13.1, 14.1, 15.1,
181        ];
182        let volume_values = [
183            100.0, 200.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0, 1100.0, 1200.0,
184            1300.0, 1400.0, 1500.0,
185        ];
186
187        let mut expected_cumulative = 0.0;
188        let mut expected_last = 0.0;
189
190        for i in 0..15 {
191            pressure.update_raw(
192                high_values[i],
193                low_values[i],
194                close_values[i],
195                volume_values[i],
196            );
197
198            let atr_val = if pressure.atr.value > 0.0 {
199                pressure.atr.value
200            } else {
201                (high_values[i] - low_values[i])
202                    .abs()
203                    .max(pressure.atr_floor)
204            };
205            let avg_vol = pressure.average_volume.value();
206            if avg_vol != 0.0 && atr_val != 0.0 {
207                let relative_volume = volume_values[i] / avg_vol;
208                let buy_pressure = ((close_values[i] - low_values[i]) / atr_val) * relative_volume;
209                let sell_pressure =
210                    ((high_values[i] - close_values[i]) / atr_val) * relative_volume;
211                let bar_value = buy_pressure - sell_pressure;
212                expected_cumulative += bar_value;
213                expected_last = bar_value;
214            }
215        }
216
217        assert!(pressure.initialized());
218        assert!((pressure.value - expected_last).abs() < 1e-6);
219        assert!((pressure.value_cumulative - expected_cumulative).abs() < 1e-6);
220    }
221
222    #[rstest]
223    fn test_handle_bar(mut pressure_10: Pressure, bar_ethusdt_binance_minute_bid: Bar) {
224        pressure_10.handle_bar(&bar_ethusdt_binance_minute_bid);
225        assert_eq!(pressure_10.value, -0.018_181_818_181_818_132);
226        assert_eq!(pressure_10.value_cumulative, -0.018_181_818_181_818_132);
227        assert!(pressure_10.has_inputs);
228        assert!(!pressure_10.initialized);
229    }
230
231    #[rstest]
232    fn test_reset_successfully_returns_indicator_to_fresh_state(mut pressure_10: Pressure) {
233        pressure_10.update_raw(1.00020, 1.00050, 1.00070, 100.0);
234        pressure_10.update_raw(1.00030, 1.00060, 1.00080, 200.0);
235        pressure_10.update_raw(1.00070, 1.00080, 1.00090, 300.0);
236
237        pressure_10.reset();
238
239        assert!(!pressure_10.initialized());
240        assert_eq!(pressure_10.value, 0.0);
241        assert_eq!(pressure_10.value_cumulative, 0.0);
242        assert!(!pressure_10.has_inputs);
243    }
244
245    #[rstest]
246    fn test_ma_type_default_and_override() {
247        let pressure_default = Pressure::new(10, None, None);
248        assert_eq!(pressure_default.ma_type, MovingAverageType::Exponential);
249
250        let pressure_simple = Pressure::new(10, Some(MovingAverageType::Simple), None);
251        assert_eq!(pressure_simple.ma_type, MovingAverageType::Simple);
252    }
253
254    #[rstest]
255    fn test_initialized_after_enough_inputs() {
256        let mut pressure = Pressure::new(3, Some(MovingAverageType::Exponential), None);
257        for _ in 0..3 {
258            pressure.update_raw(1.3, 1.0, 1.1, 100.0);
259        }
260        assert!(pressure.initialized());
261    }
262
263    #[rstest]
264    fn test_atr_floor_applied_to_zero_range() {
265        let mut pressure = Pressure::new(1, Some(MovingAverageType::Simple), Some(0.5));
266        pressure.update_raw(1.5, 1.0, 1.2, 100.0);
267        assert!((pressure.value + 0.2).abs() < 1e-6);
268        assert!(!pressure.value_cumulative.is_nan());
269    }
270}