Skip to main content

nautilus_execution/
protection.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 nautilus_core::correctness::CorrectnessError;
17use nautilus_model::{
18    enums::{OrderSide, OrderType},
19    orders::{Order, OrderAny},
20    types::{Price, price::PriceRaw},
21};
22use thiserror::Error;
23
24/// Calculates the protection price for market and stop market orders using best bid or ask price.
25///
26/// Uses checked fixed-point arithmetic to preserve all stored price units.
27///
28/// # Returns
29/// A calculated protection price at the price increment's precision.
30///
31/// # Errors
32/// Returns an error if:
33/// - the order type is invalid.
34/// - best bid/ask is not provided when required for the order side.
35/// - the calculated price is outside the representable range.
36/// - the calculated price has fractional digits beyond the price increment's precision.
37pub fn protection_price_calculate(
38    price_increment: Price,
39    order: &OrderAny,
40    protection_points: u32,
41    bid: Option<Price>,
42    ask: Option<Price>,
43) -> Result<Price, ProtectionPriceError> {
44    let order_type = order.order_type();
45    if !matches!(order_type, OrderType::Market | OrderType::StopMarket) {
46        return Err(ProtectionPriceError::InvalidOrderType(order_type));
47    }
48
49    let offset = price_increment
50        .raw()
51        .checked_mul(PriceRaw::from(protection_points))
52        .ok_or(ProtectionPriceError::OffsetOverflow)?;
53
54    let raw = match order.order_side() {
55        OrderSide::Buy => ask
56            .ok_or(ProtectionPriceError::MissingAsk)?
57            .raw()
58            .checked_add(offset),
59        OrderSide::Sell => bid
60            .ok_or(ProtectionPriceError::MissingBid)?
61            .raw()
62            .checked_sub(offset),
63    }
64    .ok_or(ProtectionPriceError::PriceOverflow)?;
65
66    Ok(Price::from_raw_checked(raw, price_increment.precision)?)
67}
68
69/// An error calculating a market or stop market order's protection price.
70#[derive(Debug, PartialEq, Eq, Error)]
71pub enum ProtectionPriceError {
72    /// The order is neither a market order nor a stop market order.
73    #[error("Invalid `OrderType` {0} for protection price calculation")]
74    InvalidOrderType(OrderType),
75    /// A sell order has no bid price.
76    #[error("Bid required")]
77    MissingBid,
78    /// A buy order has no ask price.
79    #[error("Ask required")]
80    MissingAsk,
81    /// Multiplying the price increment by the protection points overflows.
82    #[error("Protection offset exceeds raw price bounds")]
83    OffsetOverflow,
84    /// Applying the protection offset to the quote overflows.
85    #[error("Protection price exceeds raw price bounds")]
86    PriceOverflow,
87    /// The raw price or precision fails validation, with a boxed [`CorrectnessError`] as its source.
88    #[error("{0}")]
89    InvalidPrice(#[source] Box<CorrectnessError>),
90}
91
92impl From<CorrectnessError> for ProtectionPriceError {
93    fn from(source: CorrectnessError) -> Self {
94        Self::InvalidPrice(Box::new(source))
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use nautilus_model::{
101        enums::{OrderSide, OrderType, TriggerType},
102        orders::builder::OrderTestBuilder,
103        types::{Quantity, fixed::FIXED_PRECISION},
104    };
105    use rstest::rstest;
106
107    use super::*;
108
109    fn build_stop_order(order_type: OrderType, side: OrderSide) -> OrderAny {
110        let mut builder = OrderTestBuilder::new(order_type);
111        builder
112            .instrument_id("BTCUSDT-PERP.BINANCE".into())
113            .side(side)
114            .quantity(Quantity::from(1))
115            .trigger_price(Price::new(100.0, 2))
116            .trigger_type(TriggerType::LastPrice);
117
118        if order_type == OrderType::StopLimit {
119            builder.price(Price::new(99.5, 2));
120        }
121
122        builder.build()
123    }
124
125    #[rstest]
126    #[case(OrderSide::Buy, "123.456821")]
127    #[case(OrderSide::Sell, "123.456761")]
128    fn test_protection_rejects_sub_increment_units(
129        #[case] side: OrderSide,
130        #[case] expected: &str,
131        #[values(5, 6)] quote_precision: u8,
132    ) {
133        let order = build_stop_order(OrderType::Market, side);
134        let mut quote = Price::from("123.456791");
135        quote.precision = quote_precision;
136        let increment = Price::from("0.00001");
137        let precision = increment.precision;
138        let raw = Price::from(expected).raw();
139        let scale = PriceRaw::pow(10, u32::from(FIXED_PRECISION - precision));
140        let remainder = raw % scale;
141
142        let error =
143            protection_price_calculate(increment, &order, 3, Some(quote), Some(quote)).unwrap_err();
144        let source = Price::from_raw_checked(raw, precision).unwrap_err();
145
146        assert_eq!(
147            error,
148            ProtectionPriceError::InvalidPrice(Box::new(source.clone()))
149        );
150        assert_eq!(
151            std::error::Error::source(&error)
152                .unwrap()
153                .downcast_ref::<Box<CorrectnessError>>()
154                .map(Box::as_ref),
155            Some(&source)
156        );
157        assert_eq!(
158            error.to_string(),
159            format!(
160                "Invalid fixed-point raw value {raw} for precision {precision}: \
161                 remainder {remainder} when divided by scale {scale}. \
162                 Raw value should be a multiple of {scale}. \
163                 This indicates data corruption or incorrect precision/scaling upstream"
164            )
165        );
166    }
167
168    #[rstest]
169    #[case(OrderSide::Buy, "123.456821")]
170    #[case(OrderSide::Sell, "123.456761")]
171    fn test_protection_preserves_sub_increment_units(
172        #[case] side: OrderSide,
173        #[case] expected: &str,
174    ) {
175        let order = build_stop_order(OrderType::Market, side);
176        let quote = Price::from("123.456791");
177
178        let price = protection_price_calculate(
179            Price::from("0.000010"),
180            &order,
181            3,
182            Some(quote),
183            Some(quote),
184        )
185        .unwrap();
186
187        assert_eq!(price, Price::from(expected));
188        assert_eq!(price.precision, 6);
189    }
190
191    #[rstest]
192    fn test_calculate_with_invalid_order_type() {
193        let order = OrderTestBuilder::new(OrderType::Limit)
194            .instrument_id("BTCUSDT-PERP.BINANCE".into())
195            .side(OrderSide::Buy)
196            .price(Price::new(100.0, 2))
197            .quantity(Quantity::from(1))
198            .build();
199
200        let result = protection_price_calculate(Price::new(0.01, 2), &order, 600, None, None);
201
202        let error = result.unwrap_err();
203
204        assert_eq!(
205            error,
206            ProtectionPriceError::InvalidOrderType(OrderType::Limit)
207        );
208        assert_eq!(
209            error.to_string(),
210            "Invalid `OrderType` LIMIT for protection price calculation"
211        );
212    }
213
214    #[rstest]
215    #[case(OrderSide::Buy, ProtectionPriceError::MissingAsk, "Ask required")]
216    #[case(OrderSide::Sell, ProtectionPriceError::MissingBid, "Bid required")]
217    fn test_calculate_requires_opposite_quote(
218        #[case] side: OrderSide,
219        #[case] expected_error: ProtectionPriceError,
220        #[case] expected: &str,
221    ) {
222        let order = build_stop_order(OrderType::StopMarket, side);
223        let price_increment = Price::new(0.01, 2);
224
225        let (bid, ask) = match side {
226            OrderSide::Buy => (Some(Price::new(99.5, 2)), None),
227            OrderSide::Sell => (None, Some(Price::new(100.5, 2))),
228        };
229
230        let error = protection_price_calculate(price_increment, &order, 25, bid, ask).unwrap_err();
231
232        assert_eq!(error, expected_error);
233        assert_eq!(error.to_string(), expected);
234    }
235
236    #[rstest]
237    fn test_protection_offset_overflow_precedes_missing_quote() {
238        let order = build_stop_order(OrderType::Market, OrderSide::Buy);
239
240        let error =
241            protection_price_calculate(Price::max(0), &order, u32::MAX, None, None).unwrap_err();
242
243        assert_eq!(error, ProtectionPriceError::OffsetOverflow);
244        assert_eq!(
245            error.to_string(),
246            "Protection offset exceeds raw price bounds"
247        );
248    }
249
250    #[rstest]
251    #[case(OrderSide::Buy)]
252    #[case(OrderSide::Sell)]
253    fn test_protection_price_overflow(#[case] side: OrderSide) {
254        let order = build_stop_order(OrderType::Market, side);
255        let increment = Price::max(0);
256        let points = u32::try_from(PriceRaw::MAX / increment.raw()).unwrap();
257
258        let error = protection_price_calculate(
259            increment,
260            &order,
261            points,
262            Some(Price::min(0)),
263            Some(Price::max(0)),
264        )
265        .unwrap_err();
266
267        assert_eq!(error, ProtectionPriceError::PriceOverflow);
268        assert_eq!(
269            error.to_string(),
270            "Protection price exceeds raw price bounds"
271        );
272    }
273
274    #[rstest]
275    fn test_protection_price_outside_domain_bounds() {
276        let order = build_stop_order(OrderType::Market, OrderSide::Buy);
277        let increment = Price::from_raw(1, FIXED_PRECISION);
278        let quote = Price::max(FIXED_PRECISION);
279        let source = Price::from_raw_checked(quote.raw() + 1, FIXED_PRECISION).unwrap_err();
280
281        let error =
282            protection_price_calculate(increment, &order, 1, None, Some(quote)).unwrap_err();
283
284        assert_eq!(error, ProtectionPriceError::InvalidPrice(Box::new(source)));
285    }
286
287    #[rstest]
288    #[case(OrderType::StopMarket)]
289    #[case(OrderType::Market)]
290    fn test_protection_price_buy(#[case] order_type: OrderType) {
291        let order = build_stop_order(order_type, OrderSide::Buy);
292
293        let protection_price = protection_price_calculate(
294            Price::new(0.01, 2),
295            &order,
296            50,
297            Some(Price::new(99.0, 2)),
298            Some(Price::new(101.0, 2)),
299        )
300        .unwrap();
301
302        assert_eq!(protection_price.as_f64(), 101.5);
303    }
304
305    #[rstest]
306    #[case(OrderType::StopMarket)]
307    #[case(OrderType::Market)]
308    fn test_protection_price_sell(#[case] order_type: OrderType) {
309        let order = build_stop_order(order_type, OrderSide::Sell);
310
311        let protection_price = protection_price_calculate(
312            Price::new(0.01, 2),
313            &order,
314            50,
315            Some(Price::new(99.0, 2)),
316            Some(Price::new(101.0, 2)),
317        )
318        .unwrap();
319
320        assert_eq!(protection_price.as_f64(), 98.5);
321    }
322
323    #[rstest]
324    fn test_protection_price_zero_points() {
325        let order = build_stop_order(OrderType::Market, OrderSide::Buy);
326
327        let protection_price = protection_price_calculate(
328            Price::new(0.01, 2),
329            &order,
330            0,
331            Some(Price::new(99.0, 2)),
332            Some(Price::new(101.0, 2)),
333        )
334        .unwrap();
335
336        // With 0 points, protection_price = ask + 0 = 101.0
337        assert_eq!(protection_price.as_f64(), 101.0);
338    }
339
340    #[rstest]
341    fn test_protection_price_sell_negative_result() {
342        let order = build_stop_order(OrderType::Market, OrderSide::Sell);
343
344        let protection_price = protection_price_calculate(
345            Price::new(0.01, 2),
346            &order,
347            1000,
348            Some(Price::new(5.0, 2)),
349            Some(Price::new(6.0, 2)),
350        )
351        .unwrap();
352
353        // protection_price = 5.0 - (1000 * 0.01) = 5.0 - 10.0 = -5.0
354        assert_eq!(protection_price.as_f64(), -5.0);
355    }
356
357    #[rstest]
358    fn test_protection_price_large_points() {
359        let order = build_stop_order(OrderType::Market, OrderSide::Buy);
360
361        let protection_price = protection_price_calculate(
362            Price::new(0.01, 2),
363            &order,
364            100_000,
365            Some(Price::new(50_000.0, 2)),
366            Some(Price::new(50_001.0, 2)),
367        )
368        .unwrap();
369
370        // protection_price = 50001.0 + (100_000 * 0.01) = 50001.0 + 1000.0 = 51001.0
371        assert_eq!(protection_price.as_f64(), 51001.0);
372    }
373
374    #[rstest]
375    #[case(OrderSide::Buy, "123.45682")]
376    #[case(OrderSide::Sell, "123.45667")]
377    fn test_protection_price_preserves_increment_precision(
378        #[case] side: OrderSide,
379        #[case] expected: &str,
380    ) {
381        let order = build_stop_order(OrderType::Market, side);
382        let (bid, ask) = match side {
383            OrderSide::Buy => (None, Some(Price::from("123.456790"))),
384            OrderSide::Sell => (Some(Price::from("123.456700")), None),
385        };
386
387        let price =
388            protection_price_calculate(Price::from("0.00001"), &order, 3, bid, ask).unwrap();
389
390        assert_eq!(price, Price::from(expected));
391        assert_eq!(price.precision, 5);
392    }
393}