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    #[must_use]
85    pub fn new(period: usize, ma_type: Option<MovingAverageType>, atr_floor: Option<f64>) -> Self {
86        Self {
87            period,
88            ma_type: ma_type.unwrap_or(MovingAverageType::Simple),
89            atr_floor: atr_floor.unwrap_or(0.0),
90            value: 0.0,
91            value_cumulative: 0.0,
92            atr: AverageTrueRange::new(
93                period,
94                Some(MovingAverageType::Exponential),
95                Some(false),
96                atr_floor,
97            ),
98            average_volume: MovingAverageFactory::create(
99                ma_type.unwrap_or(MovingAverageType::Simple),
100                period,
101            ),
102            has_inputs: false,
103            initialized: false,
104        }
105    }
106
107    pub fn update_raw(&mut self, high: f64, low: f64, close: f64, volume: f64) {
108        self.atr.update_raw(high, low, close);
109        self.average_volume.update_raw(volume);
110
111        if !self.initialized {
112            self.has_inputs = true;
113            if self.atr.initialized {
114                self.initialized = true;
115            }
116        }
117
118        if self.average_volume.value() == 0.0 || self.atr.value == 0.0 {
119            self.value = 0.0;
120            return;
121        }
122
123        let relative_volume = volume / self.average_volume.value();
124        let buy_pressure = ((close - low) / self.atr.value) * relative_volume;
125        let sell_pressure = ((high - close) / self.atr.value) * relative_volume;
126
127        self.value = buy_pressure - sell_pressure;
128        self.value_cumulative += self.value;
129    }
130}
131
132////////////////////////////////////////////////////////////////////////////////
133// Tests
134////////////////////////////////////////////////////////////////////////////////
135#[cfg(test)]
136mod tests {
137    use rstest::rstest;
138
139    use super::*;
140    use crate::stubs::{bar_ethusdt_binance_minute_bid, pressure_10};
141
142    #[rstest]
143    fn test_name_returns_expected_string(pressure_10: Pressure) {
144        assert_eq!(pressure_10.name(), "Pressure");
145    }
146
147    #[rstest]
148    fn test_str_repr_returns_expected_string(pressure_10: Pressure) {
149        assert_eq!(format!("{pressure_10}"), "Pressure(10,SIMPLE)");
150    }
151
152    #[rstest]
153    fn test_period_returns_expected_value(pressure_10: Pressure) {
154        assert_eq!(pressure_10.period, 10);
155    }
156
157    #[rstest]
158    fn test_initialized_without_inputs_returns_false(pressure_10: Pressure) {
159        assert!(!pressure_10.initialized());
160    }
161
162    #[rstest]
163    fn test_value_with_all_higher_inputs_returns_expected_value(mut pressure_10: Pressure) {
164        let high_values = [
165            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,
166        ];
167        let low_values = [
168            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,
169        ];
170        let close_values = [
171            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,
172        ];
173        let volume_values = [
174            100.0, 200.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0, 1100.0, 1200.0,
175            1300.0, 1400.0, 1500.0,
176        ];
177
178        for i in 0..15 {
179            pressure_10.update_raw(
180                high_values[i],
181                low_values[i],
182                close_values[i],
183                volume_values[i],
184            );
185        }
186
187        assert!(pressure_10.initialized());
188        assert_eq!(pressure_10.value, 4.377_880_184_331_797);
189        assert_eq!(pressure_10.value_cumulative, 23.231_207_409_222_474);
190    }
191
192    #[rstest]
193    fn test_handle_bar(mut pressure_10: Pressure, bar_ethusdt_binance_minute_bid: Bar) {
194        pressure_10.handle_bar(&bar_ethusdt_binance_minute_bid);
195        assert_eq!(pressure_10.value, -0.018_181_818_181_818_132);
196        assert_eq!(pressure_10.value_cumulative, -0.018_181_818_181_818_132);
197        assert!(pressure_10.has_inputs);
198        assert!(!pressure_10.initialized);
199    }
200
201    #[rstest]
202    fn test_reset_successfully_returns_indicator_to_fresh_state(mut pressure_10: Pressure) {
203        pressure_10.update_raw(1.00020, 1.00050, 1.00070, 100.0);
204        pressure_10.update_raw(1.00030, 1.00060, 1.00080, 200.0);
205        pressure_10.update_raw(1.00070, 1.00080, 1.00090, 300.0);
206
207        pressure_10.reset();
208
209        assert!(!pressure_10.initialized());
210        assert_eq!(pressure_10.value, 0.0);
211        assert_eq!(pressure_10.value_cumulative, 0.0);
212        assert!(!pressure_10.has_inputs);
213    }
214}