Skip to main content

nautilus_indicators/ratio/
spread_analyzer.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::Display;
17
18use nautilus_model::{data::QuoteTick, identifiers::InstrumentId};
19
20use crate::indicator::Indicator;
21
22/// An indicator which calculates the efficiency ratio across a rolling window.
23///
24/// The Kaufman Efficiency measures the ratio of the relative market speed in
25/// relation to the volatility, this could be thought of as a proxy for noise.
26#[repr(C)]
27#[derive(Debug)]
28#[cfg_attr(
29    feature = "python",
30    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.indicators")
31)]
32#[cfg_attr(
33    feature = "python",
34    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.indicators")
35)]
36pub struct SpreadAnalyzer {
37    pub capacity: usize,
38    pub instrument_id: InstrumentId,
39    pub current: f64,
40    pub average: f64,
41    pub initialized: bool,
42    has_inputs: bool,
43    spreads: Vec<f64>,
44}
45
46impl Display for SpreadAnalyzer {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        write!(
49            f,
50            "{}({},{})",
51            self.name(),
52            self.capacity,
53            self.instrument_id
54        )
55    }
56}
57
58impl Indicator for SpreadAnalyzer {
59    fn name(&self) -> String {
60        stringify!(SpreadAnalyzer).to_string()
61    }
62
63    fn has_inputs(&self) -> bool {
64        self.has_inputs
65    }
66    fn initialized(&self) -> bool {
67        self.initialized
68    }
69
70    fn handle_quote(&mut self, quote: &QuoteTick) {
71        if quote.instrument_id != self.instrument_id {
72            return;
73        }
74
75        // Check initialization
76        if !self.initialized {
77            self.has_inputs = true;
78
79            if self.spreads.len() == self.capacity {
80                self.initialized = true;
81            }
82        }
83
84        let bid: f64 = quote.bid_price.into();
85        let ask: f64 = quote.ask_price.into();
86        let spread = ask - bid;
87
88        self.current = spread;
89        self.spreads.push(spread);
90
91        // Update average spread
92        self.average =
93            fast_mean_iterated(&self.spreads, spread, self.average, self.capacity, false).unwrap();
94    }
95
96    fn reset(&mut self) {
97        self.current = 0.0;
98        self.average = 0.0;
99        self.spreads.clear();
100        self.initialized = false;
101        self.has_inputs = false;
102    }
103}
104
105impl SpreadAnalyzer {
106    /// Creates a new [`SpreadAnalyzer`] instance.
107    #[must_use]
108    pub fn new(capacity: usize, instrument_id: InstrumentId) -> Self {
109        Self {
110            capacity,
111            instrument_id,
112            current: 0.0,
113            average: 0.0,
114            initialized: false,
115            has_inputs: false,
116            spreads: Vec::with_capacity(capacity),
117        }
118    }
119}
120
121fn fast_mean_iterated(
122    values: &[f64],
123    next_value: f64,
124    current_value: f64,
125    expected_length: usize,
126    drop_left: bool,
127) -> Result<f64, &'static str> {
128    let length = values.len();
129
130    if length < expected_length {
131        return Ok(fast_mean(values));
132    }
133
134    if length != expected_length {
135        return Err("length of values must equal expected_length");
136    }
137
138    let value_to_drop = if drop_left {
139        values[0]
140    } else {
141        values[length - 1]
142    };
143
144    Ok(current_value + (next_value - value_to_drop) / length as f64)
145}
146
147fn fast_mean(values: &[f64]) -> f64 {
148    if values.is_empty() {
149        0.0
150    } else {
151        values.iter().sum::<f64>() / values.len() as f64
152    }
153}
154
155#[cfg(test)]
156mod tests {
157
158    use rstest::rstest;
159
160    use crate::{
161        indicator::Indicator,
162        ratio::spread_analyzer::SpreadAnalyzer,
163        stubs::{spread_analyzer_10, *},
164    };
165    #[rstest]
166    fn test_efficiency_ratio_initialized(spread_analyzer_10: SpreadAnalyzer) {
167        let display_str = format!("{spread_analyzer_10}");
168        assert_eq!(display_str, "SpreadAnalyzer(10,ETHUSDT-PERP.BINANCE)");
169        assert_eq!(spread_analyzer_10.capacity, 10);
170        assert!(!spread_analyzer_10.initialized);
171    }
172
173    #[rstest]
174    fn test_with_correct_number_of_required_inputs(mut spread_analyzer_10: SpreadAnalyzer) {
175        let bid_price: [&str; 10] = [
176            "100.50", "100.45", "100.55", "100.60", "100.52", "100.48", "100.53", "100.57",
177            "100.49", "100.51",
178        ];
179
180        let ask_price: [&str; 10] = [
181            "100.55", "100.50", "100.60", "100.65", "100.57", "100.53", "100.58", "100.62",
182            "100.54", "100.56",
183        ];
184
185        for i in 1..10 {
186            spread_analyzer_10.handle_quote(&stub_quote(bid_price[i], ask_price[i]));
187        }
188        assert!(!spread_analyzer_10.initialized);
189    }
190
191    #[rstest]
192    fn test_value_with_one_input(mut spread_analyzer_10: SpreadAnalyzer) {
193        spread_analyzer_10.handle_quote(&stub_quote("100.50", "100.55"));
194        assert_eq!(spread_analyzer_10.average, 0.049_999_999_999_997_16);
195    }
196
197    #[rstest]
198    fn test_value_with_all_higher_inputs_returns_expected_value(
199        mut spread_analyzer_10: SpreadAnalyzer,
200    ) {
201        let bid_price: [&str; 15] = [
202            "100.50", "100.45", "100.55", "100.60", "100.52", "100.48", "100.53", "100.57",
203            "100.49", "100.51", "100.54", "100.56", "100.58", "100.50", "100.52",
204        ];
205
206        let ask_price: [&str; 15] = [
207            "100.55", "100.50", "100.60", "100.65", "100.57", "100.53", "100.58", "100.62",
208            "100.54", "100.56", "100.59", "100.61", "100.63", "100.55", "100.57",
209        ];
210
211        for i in 0..10 {
212            spread_analyzer_10.handle_quote(&stub_quote(bid_price[i], ask_price[i]));
213        }
214
215        assert_eq!(spread_analyzer_10.average, 0.050_000_000_000_001_9);
216    }
217
218    #[rstest]
219    fn test_reset_successfully_returns_indicator_to_fresh_state(
220        mut spread_analyzer_10: SpreadAnalyzer,
221    ) {
222        spread_analyzer_10.handle_quote(&stub_quote("100.50", "100.55"));
223        spread_analyzer_10.reset();
224        assert!(!spread_analyzer_10.initialized());
225        assert_eq!(spread_analyzer_10.current, 0.0);
226        assert_eq!(spread_analyzer_10.average, 0.0);
227        assert!(!spread_analyzer_10.has_inputs);
228        assert!(!spread_analyzer_10.initialized);
229    }
230}