Skip to main content

nautilus_execution/
trailing.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_common::cache::Cache;
17use nautilus_core::correctness::CorrectnessError;
18use nautilus_model::{
19    enums::{OrderSide, OrderType, TrailingOffsetType, TriggerType},
20    orders::{Order, OrderAny},
21    types::Price,
22};
23use rust_decimal::{Decimal, RoundingStrategy};
24use thiserror::Error;
25
26/// Calculates the new trigger and limit prices for a trailing stop order.
27///
28/// `trigger_px` is an optional **override** for the trigger price already carried inside
29/// `order`.  If `Some(_)`, it takes priority over the value on the order itself, otherwise
30/// the function falls back to the value stored on the order.
31///
32/// `Default`, `BidAsk`, and `LastOrBidAsk` require both `bid` and `ask`.
33/// `LastOrBidAsk` evaluates the quote first, then requires `last`.
34/// `LastPrice` and `MarkPrice` use `last` as their reference. Other trigger types are unsupported.
35///
36/// # Returns
37/// A tuple with the *newly-set* trigger-price and limit-price (if any).
38/// `None` in either position means the respective price did **not** improve.
39///
40/// # Errors
41/// Returns an error if:
42/// - the order type, trigger type, or trailing offset type is invalid.
43/// - a required bid, ask, or last price is missing.
44/// - the calculated price cannot be represented as a [`Price`].
45pub fn trailing_stop_calculate(
46    price_increment: Price,
47    trigger_px: Option<Price>,
48    order: &OrderAny,
49    bid: Option<Price>,
50    ask: Option<Price>,
51    last: Option<Price>,
52) -> Result<(Option<Price>, Option<Price>), TrailingStopError> {
53    let order_side = order.order_side();
54
55    let (trigger_type, trailing_offset, trailing_offset_type, mut limit_price, limit_offset) =
56        match order {
57            OrderAny::TrailingStopMarket(order) => (
58                order.trigger_type,
59                order.trailing_offset,
60                order.trailing_offset_type,
61                None,
62                None,
63            ),
64            OrderAny::TrailingStopLimit(order) => (
65                order.trigger_type,
66                order.trailing_offset,
67                order.trailing_offset_type,
68                order.price,
69                Some(order.limit_offset),
70            ),
71            _ => return Err(TrailingStopError::InvalidOrderType(order.order_type())),
72        };
73
74    // Seed from the current trigger only (never the activation price): when the trigger has
75    // not yet materialized it stays `None` here so the offset candidate below becomes the
76    // initial trigger on the first update (matches v1 `TrailingStopCalculator`).
77    let mut trigger_price = trigger_px.or(order.trigger_price());
78
79    let maybe_move = |current: &mut Option<Price>,
80                      candidate: Price,
81                      better: fn(Price, Price) -> bool|
82     -> Option<Price> {
83        match current {
84            Some(p) if better(candidate, *p) => {
85                *current = Some(candidate);
86                Some(candidate)
87            }
88            None => {
89                *current = Some(candidate);
90                Some(candidate)
91            }
92            _ => None,
93        }
94    };
95
96    let better_price: fn(Price, Price) -> bool = match order_side {
97        OrderSide::Buy => |c, p| c < p,
98        OrderSide::Sell => |c, p| c > p,
99    };
100
101    let compute = |offset: Decimal, basis: Price| {
102        trailing_stop_calculate_with_last(
103            price_increment,
104            trailing_offset_type,
105            order_side,
106            offset,
107            basis,
108        )
109    };
110
111    let basis = match trigger_type {
112        TriggerType::LastPrice | TriggerType::MarkPrice => {
113            last.ok_or(TrailingStopError::MissingLast)?
114        }
115        TriggerType::Default | TriggerType::BidAsk | TriggerType::LastOrBidAsk => {
116            let (bid, ask) = (
117                bid.ok_or(TrailingStopError::MissingBid)?,
118                ask.ok_or(TrailingStopError::MissingAsk)?,
119            );
120
121            match order_side {
122                OrderSide::Buy => ask,
123                OrderSide::Sell => bid,
124            }
125        }
126        _ => return Err(TrailingStopError::UnsupportedTriggerType(trigger_type)),
127    };
128
129    let cand_trigger = compute(trailing_offset, basis)?;
130    let mut new_trigger_price = maybe_move(&mut trigger_price, cand_trigger, better_price);
131    let mut new_limit_price = None;
132
133    if let Some(limit_offset) = limit_offset {
134        let cand_limit = compute(limit_offset, basis)?;
135        new_limit_price = maybe_move(&mut limit_price, cand_limit, better_price);
136    }
137
138    if trigger_type != TriggerType::LastOrBidAsk {
139        return Ok((new_trigger_price, new_limit_price));
140    }
141
142    let last = last.ok_or(TrailingStopError::MissingLast)?;
143    let cand_trigger = compute(trailing_offset, last)?;
144    let updated = maybe_move(&mut trigger_price, cand_trigger, better_price);
145    if updated.is_some() {
146        new_trigger_price = updated;
147    }
148
149    if let Some(limit_offset) = limit_offset {
150        let cand_limit = compute(limit_offset, last)?;
151        let updated = maybe_move(&mut limit_price, cand_limit, better_price);
152        if updated.is_some() {
153            new_limit_price = updated;
154        }
155    }
156
157    Ok((new_trigger_price, new_limit_price))
158}
159
160/// Calculates the trailing stop price using the last traded price.
161///
162/// # Errors
163///
164/// Returns an error if the offset type is unsupported or the calculated price cannot be
165/// represented as a [`Price`].
166pub fn trailing_stop_calculate_with_last(
167    price_increment: Price,
168    trailing_offset_type: TrailingOffsetType,
169    side: OrderSide,
170    offset: Decimal,
171    last: Price,
172) -> Result<Price, TrailingStopError> {
173    let last = last.as_decimal();
174    let offset = match trailing_offset_type {
175        TrailingOffsetType::Price => offset,
176        TrailingOffsetType::BasisPoints => last * offset / Decimal::from(10_000),
177        TrailingOffsetType::Ticks => offset * price_increment.as_decimal(),
178        _ => {
179            return Err(TrailingStopError::UnsupportedOffsetType(
180                trailing_offset_type,
181            ));
182        }
183    };
184
185    let price = match side {
186        OrderSide::Buy => last + offset,
187        OrderSide::Sell => last - offset,
188    };
189
190    let rounded = Price::from_decimal_dp(price, price_increment.precision)?;
191    let increment_raw = price_increment.raw().abs();
192
193    if increment_raw == 0 || rounded.raw() % increment_raw == 0 {
194        return Ok(rounded);
195    }
196
197    // The increment is coarser than its precision, such as 0.25: use its nearest multiple
198    let increment = price_increment.as_decimal();
199    let nearest = price
200        .checked_div(increment)
201        .and_then(|increments| {
202            increments
203                .round_dp_with_strategy(0, RoundingStrategy::MidpointNearestEven)
204                .checked_mul(increment)
205        })
206        .unwrap_or(price);
207
208    Price::from_decimal_dp(nearest, price_increment.precision).map_err(Into::into)
209}
210
211/// Calculates the trailing stop price using bid and ask prices.
212///
213/// # Errors
214///
215/// Returns an error if the offset type is unsupported or the calculated price cannot be
216/// represented as a [`Price`].
217pub fn trailing_stop_calculate_with_bid_ask(
218    price_increment: Price,
219    trailing_offset_type: TrailingOffsetType,
220    side: OrderSide,
221    offset: Decimal,
222    bid: Price,
223    ask: Price,
224) -> Result<Price, TrailingStopError> {
225    let basis = match side {
226        OrderSide::Buy => ask,
227        OrderSide::Sell => bid,
228    };
229
230    trailing_stop_calculate_with_last(price_increment, trailing_offset_type, side, offset, basis)
231}
232
233/// An error calculating a trailing stop order's trigger or limit price.
234#[derive(Debug, PartialEq, Eq, Error)]
235pub enum TrailingStopError {
236    /// The order is neither a trailing stop market order nor a trailing stop limit order.
237    #[error("Invalid `OrderType` {0} for trailing stop calculation")]
238    InvalidOrderType(OrderType),
239    /// The trigger type has no supported market-price basis.
240    #[error("`TriggerType` {0} not currently supported")]
241    UnsupportedTriggerType(TriggerType),
242    /// The offset type has no supported price calculation.
243    #[error("`TrailingOffsetType` {0} not currently supported")]
244    UnsupportedOffsetType(TrailingOffsetType),
245    /// A `Default`, `BidAsk`, or `LastOrBidAsk` calculation has no `bid` price.
246    #[error("Bid required")]
247    MissingBid,
248    /// A `Default`, `BidAsk`, or `LastOrBidAsk` calculation has no `ask` price.
249    #[error("Ask required")]
250    MissingAsk,
251    /// A `LastPrice`, `MarkPrice`, or `LastOrBidAsk` calculation has no `last` price.
252    #[error("Last required")]
253    MissingLast,
254    /// A calculated price fails validation, with a boxed [`CorrectnessError`] as its source.
255    #[error("{0}")]
256    InvalidPrice(#[source] Box<CorrectnessError>),
257}
258
259impl From<CorrectnessError> for TrailingStopError {
260    fn from(source: CorrectnessError) -> Self {
261        Self::InvalidPrice(Box::new(source))
262    }
263}
264
265// Activation is not an order event, so copy only the activation fields into the cached order:
266// `replace_order` would append its last event to the cache database again, and copying the whole
267// order would overwrite a lifecycle state whose event is still queued for the execution engine.
268pub(crate) fn store_trailing_stop_activation(cache: &mut Cache, order: &OrderAny) {
269    let Some(mut cached) = cache.order_mut(&order.client_order_id()) else {
270        log::error!(
271            "Cannot store trailing stop activation: order {} not found",
272            order.client_order_id()
273        );
274        return;
275    };
276
277    match (&mut *cached, order) {
278        (OrderAny::TrailingStopMarket(cached), OrderAny::TrailingStopMarket(order)) => {
279            cached.activation_price = order.activation_price;
280            cached.is_activated = order.is_activated;
281        }
282        (OrderAny::TrailingStopLimit(cached), OrderAny::TrailingStopLimit(order)) => {
283            cached.activation_price = order.activation_price;
284            cached.is_activated = order.is_activated;
285        }
286        _ => {}
287    }
288}
289
290#[cfg(test)]
291mod tests {
292    use nautilus_model::{
293        enums::{OrderSide, OrderType, TrailingOffsetType, TriggerType},
294        orders::builder::OrderTestBuilder,
295        types::Quantity,
296    };
297    use rstest::rstest;
298    use rust_decimal::prelude::*;
299    use rust_decimal_macros::dec;
300
301    use super::*;
302
303    fn assert_optional_price(actual: Option<Price>, expected: Option<&str>) {
304        match (actual, expected) {
305            (Some(actual), Some(expected)) => assert_eq!(actual, Price::from(expected)),
306            (None, None) => {}
307            (actual, expected) => panic!("expected {expected:?}, was {actual:?}"),
308        }
309    }
310
311    #[rstest]
312    fn test_calculate_with_invalid_order_type() {
313        let order = OrderTestBuilder::new(OrderType::Market)
314            .instrument_id("BTCUSDT-PERP.BINANCE".into())
315            .side(OrderSide::Buy)
316            .quantity(Quantity::from(1))
317            .build();
318
319        let result = trailing_stop_calculate(Price::new(0.01, 2), None, &order, None, None, None);
320
321        let error = result.unwrap_err();
322
323        assert_eq!(
324            error,
325            TrailingStopError::InvalidOrderType(OrderType::Market)
326        );
327        assert_eq!(
328            error.to_string(),
329            "Invalid `OrderType` MARKET for trailing stop calculation"
330        );
331    }
332
333    #[rstest]
334    #[case(OrderSide::Buy)]
335    #[case(OrderSide::Sell)]
336    fn test_calculate_with_last_price_no_last(
337        #[case] side: OrderSide,
338        #[values(TriggerType::LastPrice, TriggerType::MarkPrice)] trigger_type: TriggerType,
339    ) {
340        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
341            .instrument_id("BTCUSDT-PERP.BINANCE".into())
342            .side(side)
343            .trigger_price(Price::new(100.0, 2))
344            .trailing_offset_type(TrailingOffsetType::Price)
345            .trailing_offset(dec!(1.0))
346            .trigger_type(trigger_type)
347            .quantity(Quantity::from(1))
348            .build();
349
350        let result = trailing_stop_calculate(Price::new(0.01, 2), None, &order, None, None, None);
351
352        let error = result.unwrap_err();
353
354        assert_eq!(error, TrailingStopError::MissingLast);
355        assert_eq!(error.to_string(), "Last required");
356    }
357
358    #[rstest]
359    #[case(None, None, TrailingStopError::MissingBid, "Bid required")]
360    #[case(None, Some("101.00"), TrailingStopError::MissingBid, "Bid required")]
361    #[case(Some("100.00"), None, TrailingStopError::MissingAsk, "Ask required")]
362    fn test_calculate_with_bid_ask_no_bid_ask(
363        #[case] bid: Option<&str>,
364        #[case] ask: Option<&str>,
365        #[case] expected: TrailingStopError,
366        #[case] expected_message: &str,
367        #[values(OrderSide::Buy, OrderSide::Sell)] side: OrderSide,
368        #[values(TriggerType::Default, TriggerType::BidAsk, TriggerType::LastOrBidAsk)]
369        trigger_type: TriggerType,
370    ) {
371        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
372            .instrument_id("BTCUSDT-PERP.BINANCE".into())
373            .side(side)
374            .trigger_price(Price::new(100.0, 2))
375            .trailing_offset_type(TrailingOffsetType::Price)
376            .trailing_offset(dec!(1.0))
377            .trigger_type(trigger_type)
378            .quantity(Quantity::from(1))
379            .build();
380
381        let result = trailing_stop_calculate(
382            Price::from("0.01"),
383            None,
384            &order,
385            bid.map(Price::from),
386            ask.map(Price::from),
387            None,
388        );
389
390        let error = result.unwrap_err();
391
392        assert_eq!(error, expected);
393        assert_eq!(error.to_string(), expected_message);
394    }
395
396    #[rstest]
397    fn test_calculate_with_unsupported_trigger_type() {
398        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
399            .instrument_id("BTCUSDT-PERP.BINANCE".into())
400            .side(OrderSide::Buy)
401            .trigger_price(Price::new(100.0, 2))
402            .trailing_offset_type(TrailingOffsetType::Price)
403            .trailing_offset(dec!(1.0))
404            .trigger_type(TriggerType::IndexPrice) // not supported by algo
405            .quantity(Quantity::from(1))
406            .build();
407
408        let result = trailing_stop_calculate(Price::new(0.01, 2), None, &order, None, None, None);
409
410        let error = result.unwrap_err();
411
412        assert_eq!(
413            error,
414            TrailingStopError::UnsupportedTriggerType(TriggerType::IndexPrice)
415        );
416        assert_eq!(
417            error.to_string(),
418            "`TriggerType` INDEX_PRICE not currently supported"
419        );
420    }
421
422    #[rstest]
423    #[should_panic(expected = "Trailing offset type not set")]
424    fn test_build_without_trailing_offset_type_panics() {
425        let _ = OrderTestBuilder::new(OrderType::TrailingStopMarket)
426            .instrument_id("BTCUSDT-PERP.BINANCE".into())
427            .side(OrderSide::Buy)
428            .trigger_price(Price::new(100.0, 2))
429            .trailing_offset(dec!(1.0))
430            .trigger_type(TriggerType::LastPrice)
431            .quantity(Quantity::from(1))
432            .build();
433    }
434
435    #[rstest]
436    #[case(OrderSide::Buy, 100.0, 1.0, 99.0, None)] // Last price 99 > trigger 98, no update needed
437    #[case(OrderSide::Buy, 100.0, 1.0, 98.0, Some("99.0"))] // Last price 98 < trigger 100, update to 98 + 1
438    #[case(OrderSide::Sell, 100.0, 1.0, 101.0, None)] // Last price 101 < trigger 102, no update needed
439    #[case(OrderSide::Sell, 100.0, 1.0, 102.0, Some("101.0"))] // Last price 102 > trigger 100, update to 102 - 1
440    fn test_trailing_stop_market_last_price(
441        #[case] side: OrderSide,
442        #[case] initial_trigger: f64,
443        #[case] offset: f64,
444        #[case] last_price: f64,
445        #[case] expected_trigger: Option<&str>,
446    ) {
447        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
448            .instrument_id("BTCUSDT-PERP.BINANCE".into())
449            .side(side)
450            .trigger_price(Price::new(initial_trigger, 2))
451            .trailing_offset_type(TrailingOffsetType::Price)
452            .trailing_offset(Decimal::from_f64(offset).unwrap())
453            .trigger_type(TriggerType::LastPrice)
454            .quantity(Quantity::from(1))
455            .build();
456
457        let result = trailing_stop_calculate(
458            Price::new(0.01, 2),
459            None,
460            &order,
461            None,
462            None,
463            Some(Price::new(last_price, 2)),
464        );
465
466        assert_optional_price(result.unwrap().0, expected_trigger);
467    }
468
469    #[rstest]
470    #[case(OrderSide::Buy, 1505.0, 1.0, 1480.0, 1479.0, Some("1481.0"))] // BUY uses ask as basis
471    #[case(OrderSide::Sell, 1495.0, 1.0, 1521.0, 1520.0, Some("1519.0"))] // SELL uses bid as basis
472    fn test_trailing_stop_market_default_uses_bid_ask(
473        #[case] side: OrderSide,
474        #[case] initial_trigger: f64,
475        #[case] offset: f64,
476        #[case] ask: f64,
477        #[case] bid: f64,
478        #[case] expected_trigger: Option<&str>,
479    ) {
480        // NOTE: TriggerType::Default is documented to behave like BID_ASK (quote-based), so it
481        // should not require a last-trade price and should trail using bid/ask.
482        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
483            .instrument_id("BTCUSDT-PERP.BINANCE".into())
484            .side(side)
485            .trigger_price(Price::new(initial_trigger, 2))
486            .trailing_offset_type(TrailingOffsetType::Price)
487            .trailing_offset(Decimal::from_f64(offset).unwrap())
488            .trigger_type(TriggerType::Default)
489            .quantity(Quantity::from(1))
490            .build();
491
492        let result = trailing_stop_calculate(
493            Price::new(0.01, 2),
494            None,
495            &order,
496            Some(Price::new(bid, 2)),
497            Some(Price::new(ask, 2)),
498            None, // no last-trade price available
499        );
500
501        assert_optional_price(result.unwrap().0, expected_trigger);
502    }
503
504    #[rstest]
505    #[case(OrderSide::Buy, 100.0, 50.0, 98.0, Some("98.49"))] // 50bp = 0.5% of 98 = 0.49
506    #[case(OrderSide::Buy, 100.0, 100.0, 97.0, Some("97.97"))] // 100bp = 1% of 97 = 0.97
507    #[case(OrderSide::Sell, 100.0, 50.0, 102.0, Some("101.49"))] // 50bp = 0.5% of 102 = 0.51
508    #[case(OrderSide::Sell, 100.0, 100.0, 103.0, Some("101.97"))] // 100bp = 1% of 103 = 1.03
509    fn test_trailing_stop_market_basis_points(
510        #[case] side: OrderSide,
511        #[case] initial_trigger: f64,
512        #[case] basis_points: f64,
513        #[case] last_price: f64,
514        #[case] expected_trigger: Option<&str>,
515    ) {
516        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
517            .instrument_id("BTCUSDT-PERP.BINANCE".into())
518            .side(side)
519            .trigger_price(Price::new(initial_trigger, 2))
520            .trailing_offset_type(TrailingOffsetType::BasisPoints)
521            .trailing_offset(Decimal::from_f64(basis_points).unwrap())
522            .trigger_type(TriggerType::LastPrice)
523            .quantity(Quantity::from(1))
524            .build();
525
526        let result = trailing_stop_calculate(
527            Price::new(0.01, 2),
528            None,
529            &order,
530            None,
531            None,
532            Some(Price::new(last_price, 2)),
533        );
534
535        assert_optional_price(result.unwrap().0, expected_trigger);
536    }
537
538    #[rstest]
539    #[case(OrderSide::Buy, 100.0, 1.0, 98.0, 99.0, None)] // Ask 99 > trigger 100, no update
540    #[case(OrderSide::Buy, 100.0, 1.0, 97.0, 98.0, Some("99.0"))] // Ask 98 < trigger 100, update to 98 + 1
541    #[case(OrderSide::Sell, 100.0, 1.0, 101.0, 102.0, None)] // Bid 101 < trigger 100, no update
542    #[case(OrderSide::Sell, 100.0, 1.0, 102.0, 103.0, Some("101.0"))] // Bid 102 > trigger 100, update to 102 - 1
543    fn test_trailing_stop_market_bid_ask(
544        #[case] side: OrderSide,
545        #[case] initial_trigger: f64,
546        #[case] offset: f64,
547        #[case] bid: f64,
548        #[case] ask: f64,
549        #[case] expected_trigger: Option<&str>,
550    ) {
551        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
552            .instrument_id("BTCUSDT-PERP.BINANCE".into())
553            .side(side)
554            .trigger_price(Price::new(initial_trigger, 2))
555            .trailing_offset_type(TrailingOffsetType::Price)
556            .trailing_offset(Decimal::from_f64(offset).unwrap())
557            .trigger_type(TriggerType::BidAsk)
558            .quantity(Quantity::from(1))
559            .build();
560
561        let result = trailing_stop_calculate(
562            Price::new(0.01, 2),
563            None,
564            &order,
565            Some(Price::new(bid, 2)),
566            Some(Price::new(ask, 2)),
567            None, // last price not needed for BidAsk trigger type
568        );
569
570        assert_optional_price(result.unwrap().0, expected_trigger);
571    }
572
573    #[rstest]
574    #[case(OrderSide::Buy, 100.0, 5, 98.0, Some("98.05"))] // 5 ticks * 0.01 = 0.05 offset
575    #[case(OrderSide::Buy, 100.0, 10, 97.0, Some("97.10"))] // 10 ticks * 0.01 = 0.10 offset
576    #[case(OrderSide::Sell, 100.0, 5, 102.0, Some("101.95"))] // 5 ticks * 0.01 = 0.05 offset
577    #[case(OrderSide::Sell, 100.0, 10, 103.0, Some("102.90"))] // 10 ticks * 0.01 = 0.10 offset
578    fn test_trailing_stop_market_ticks(
579        #[case] side: OrderSide,
580        #[case] initial_trigger: f64,
581        #[case] ticks: u32,
582        #[case] last_price: f64,
583        #[case] expected_trigger: Option<&str>,
584    ) {
585        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
586            .instrument_id("BTCUSDT-PERP.BINANCE".into())
587            .side(side)
588            .trigger_price(Price::new(initial_trigger, 2))
589            .trailing_offset_type(TrailingOffsetType::Ticks)
590            .trailing_offset(Decimal::from_u32(ticks).unwrap())
591            .trigger_type(TriggerType::LastPrice)
592            .quantity(Quantity::from(1))
593            .build();
594
595        let result = trailing_stop_calculate(
596            Price::new(0.01, 2),
597            None,
598            &order,
599            None,
600            None,
601            Some(Price::new(last_price, 2)),
602        );
603
604        assert_optional_price(result.unwrap().0, expected_trigger);
605    }
606
607    #[rstest]
608    #[case(OrderSide::Buy, 100.0, 1.0, 98.0, 97.0, 98.0, Some("99.0"))] // Last price gives higher trigger
609    #[case(OrderSide::Buy, 100.0, 1.0, 97.0, 96.0, 99.0, Some("98.0"))] // Bid/Ask gives higher trigger
610    #[case(OrderSide::Sell, 100.0, 1.0, 102.0, 102.0, 103.0, Some("101.0"))] // Last price gives lower trigger
611    #[case(OrderSide::Sell, 100.0, 1.0, 103.0, 101.0, 102.0, Some("102.0"))] // Bid/Ask gives lower trigger
612    fn test_trailing_stop_last_or_bid_ask(
613        #[case] side: OrderSide,
614        #[case] initial_trigger: f64,
615        #[case] offset: f64,
616        #[case] last_price: f64,
617        #[case] bid: f64,
618        #[case] ask: f64,
619        #[case] expected_trigger: Option<&str>,
620    ) {
621        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
622            .instrument_id("BTCUSDT-PERP.BINANCE".into())
623            .side(side)
624            .trigger_price(Price::new(initial_trigger, 2))
625            .trailing_offset_type(TrailingOffsetType::Price)
626            .trailing_offset(Decimal::from_f64(offset).unwrap())
627            .trigger_type(TriggerType::LastOrBidAsk)
628            .quantity(Quantity::from(1))
629            .build();
630
631        let result = trailing_stop_calculate(
632            Price::new(0.01, 2),
633            None,
634            &order,
635            Some(Price::new(bid, 2)),
636            Some(Price::new(ask, 2)),
637            Some(Price::new(last_price, 2)),
638        );
639
640        assert_optional_price(result.unwrap().0, expected_trigger);
641    }
642
643    #[rstest]
644    #[case(OrderSide::Buy, 100.0, 1.0, 98.0, Some("99.0"))]
645    #[case(OrderSide::Sell, 100.0, 1.0, 102.0, Some("101.0"))]
646    fn test_trailing_stop_market_last_price_move_in_favor(
647        #[case] side: OrderSide,
648        #[case] initial_trigger: f64,
649        #[case] offset: f64,
650        #[case] last_price: f64,
651        #[case] expected_trigger: Option<&str>,
652    ) {
653        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
654            .instrument_id("BTCUSDT-PERP.BINANCE".into())
655            .side(side)
656            .trigger_price(Price::new(initial_trigger, 2))
657            .trailing_offset_type(TrailingOffsetType::Price)
658            .trailing_offset(Decimal::from_f64(offset).unwrap())
659            .trigger_type(TriggerType::LastPrice)
660            .quantity(Quantity::from(1))
661            .build();
662
663        let (maybe_trigger, _) = trailing_stop_calculate(
664            Price::new(0.01, 2),
665            None,
666            &order,
667            None,
668            None,
669            Some(Price::new(last_price, 2)),
670        )
671        .unwrap();
672
673        assert_optional_price(maybe_trigger, expected_trigger);
674    }
675
676    #[rstest]
677    fn test_trailing_stop_limit_last_price_buy_improve_trigger_and_limit() {
678        let order = OrderTestBuilder::new(OrderType::TrailingStopLimit)
679            .instrument_id("BTCUSDT-PERP.BINANCE".into())
680            .side(OrderSide::Buy)
681            .trigger_price(Price::new(105.0, 2))
682            .price(Price::new(104.5, 2))
683            .trailing_offset_type(TrailingOffsetType::Price)
684            .trailing_offset(dec!(1.0))
685            .limit_offset(dec!(0.5))
686            .trigger_type(TriggerType::LastPrice)
687            .quantity(Quantity::from(1))
688            .build();
689
690        let (new_trigger, new_limit) = trailing_stop_calculate(
691            Price::new(0.01, 2),
692            None,
693            &order,
694            None,
695            None,
696            Some(Price::new(100.0, 2)),
697        )
698        .unwrap();
699
700        assert_eq!(new_trigger.unwrap(), Price::from("101.0"));
701        assert_eq!(new_limit.unwrap(), Price::from("100.5"));
702    }
703
704    #[rstest]
705    fn test_trailing_stop_limit_last_price_sell_improve() {
706        let order = OrderTestBuilder::new(OrderType::TrailingStopLimit)
707            .instrument_id("BTCUSDT-PERP.BINANCE".into())
708            .side(OrderSide::Sell)
709            .trigger_price(Price::new(95.0, 2))
710            .price(Price::new(95.5, 2))
711            .trailing_offset_type(TrailingOffsetType::Price)
712            .trailing_offset(dec!(1.0))
713            .limit_offset(dec!(0.5))
714            .trigger_type(TriggerType::LastPrice)
715            .quantity(Quantity::from(1))
716            .build();
717
718        let (new_trigger, new_limit) = trailing_stop_calculate(
719            Price::new(0.01, 2),
720            None,
721            &order,
722            None,
723            None,
724            Some(Price::new(100.0, 2)),
725        )
726        .unwrap();
727
728        assert_eq!(new_trigger.unwrap(), Price::from("99.0"));
729        assert_eq!(new_limit.unwrap(), Price::from("99.5"));
730    }
731
732    #[rstest]
733    #[case(OrderSide::Buy, 100.0, 1.0, 99.0)]
734    #[case(OrderSide::Sell, 100.0, 1.0, 101.0)]
735    fn test_no_update_when_candidate_worse(
736        #[case] side: OrderSide,
737        #[case] initial_trigger: f64,
738        #[case] offset: f64,
739        #[case] basis: f64,
740    ) {
741        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
742            .instrument_id("BTCUSDT-PERP.BINANCE".into())
743            .side(side)
744            .trigger_price(Price::new(initial_trigger, 2))
745            .trailing_offset_type(TrailingOffsetType::Price)
746            .trailing_offset(Decimal::from_f64(offset).unwrap())
747            .trigger_type(TriggerType::LastPrice)
748            .quantity(Quantity::from(1))
749            .build();
750
751        let (maybe_trigger, _) = trailing_stop_calculate(
752            Price::new(0.01, 2),
753            None,
754            &order,
755            None,
756            None,
757            Some(Price::new(basis, 2)),
758        )
759        .unwrap();
760
761        assert!(maybe_trigger.is_none());
762    }
763
764    #[rstest]
765    #[case(
766        TrailingOffsetType::Price,
767        OrderSide::Buy,
768        dec!(1.25),
769        Price::from("98.00"),
770        Price::from("99.25")
771    )]
772    #[case(
773        TrailingOffsetType::BasisPoints,
774        OrderSide::Buy,
775        dec!(50),
776        Price::from("98.00"),
777        Price::from("98.49")
778    )]
779    #[case(
780        TrailingOffsetType::Ticks,
781        OrderSide::Sell,
782        dec!(5),
783        Price::from("102.00"),
784        Price::from("101.95")
785    )]
786    fn test_calculate_with_last_uses_decimal_math(
787        #[case] trailing_offset_type: TrailingOffsetType,
788        #[case] side: OrderSide,
789        #[case] offset: Decimal,
790        #[case] last: Price,
791        #[case] expected: Price,
792    ) {
793        let price = trailing_stop_calculate_with_last(
794            Price::from("0.01"),
795            trailing_offset_type,
796            side,
797            offset,
798            last,
799        )
800        .unwrap();
801
802        assert_eq!(price, expected);
803    }
804
805    #[rstest]
806    #[case::basis_points_sell(
807        "0.25",
808        TrailingOffsetType::BasisPoints,
809        OrderSide::Sell,
810        dec!(33),
811        "1500.00",
812        "1495.00"
813    )]
814    #[case::basis_points_buy(
815        "0.25",
816        TrailingOffsetType::BasisPoints,
817        OrderSide::Buy,
818        dec!(33),
819        "1500.25",
820        "1505.25"
821    )]
822    #[case::price_offset(
823        "0.25",
824        TrailingOffsetType::Price,
825        OrderSide::Sell,
826        dec!(0.30),
827        "1500.00",
828        "1499.75"
829    )]
830    #[case::midpoint_to_even_increment(
831        "0.50",
832        TrailingOffsetType::Price,
833        OrderSide::Sell,
834        dec!(0.25),
835        "100.50",
836        "100.00"
837    )]
838    #[case::offset_under_half_increment(
839        "0.25",
840        TrailingOffsetType::Price,
841        OrderSide::Sell,
842        dec!(0.10),
843        "1500.00",
844        "1500.00"
845    )]
846    #[case::negative_price(
847        "0.25",
848        TrailingOffsetType::Price,
849        OrderSide::Sell,
850        dec!(0.30),
851        "-10.00",
852        "-10.25"
853    )]
854    #[case::decimal_increment(
855        "0.01",
856        TrailingOffsetType::BasisPoints,
857        OrderSide::Sell,
858        dec!(1.25),
859        "100.00",
860        "99.99"
861    )]
862    #[case::decimal_increment_midpoint(
863        "0.01",
864        TrailingOffsetType::Price,
865        OrderSide::Sell,
866        dec!(0.005),
867        "100.00",
868        "100.00"
869    )]
870    #[case::decimal_increment_offset_under_half(
871        "0.01",
872        TrailingOffsetType::Price,
873        OrderSide::Sell,
874        dec!(0.004),
875        "100.00",
876        "100.00"
877    )]
878    #[case::zero_increment(
879        "0.00",
880        TrailingOffsetType::Price,
881        OrderSide::Sell,
882        dec!(0.30),
883        "1500.00",
884        "1499.70"
885    )]
886    fn test_calculate_with_last_rounds_to_price_increment(
887        #[case] price_increment: &str,
888        #[case] trailing_offset_type: TrailingOffsetType,
889        #[case] side: OrderSide,
890        #[case] offset: Decimal,
891        #[case] last: &str,
892        #[case] expected: &str,
893    ) {
894        let price = trailing_stop_calculate_with_last(
895            Price::from(price_increment),
896            trailing_offset_type,
897            side,
898            offset,
899            Price::from(last),
900        )
901        .unwrap();
902
903        assert_eq!(price, Price::from(expected));
904    }
905
906    #[rstest]
907    #[case(
908        TrailingOffsetType::Price,
909        OrderSide::Sell,
910        dec!(1.25),
911        Price::from("102.00"),
912        Price::from("103.00"),
913        Price::from("100.75")
914    )]
915    #[case(
916        TrailingOffsetType::BasisPoints,
917        OrderSide::Sell,
918        dec!(50),
919        Price::from("102.00"),
920        Price::from("103.00"),
921        Price::from("101.49")
922    )]
923    #[case(
924        TrailingOffsetType::Ticks,
925        OrderSide::Buy,
926        dec!(5),
927        Price::from("102.00"),
928        Price::from("103.00"),
929        Price::from("103.05")
930    )]
931    fn test_calculate_with_bid_ask_uses_decimal_math(
932        #[case] trailing_offset_type: TrailingOffsetType,
933        #[case] side: OrderSide,
934        #[case] offset: Decimal,
935        #[case] bid: Price,
936        #[case] ask: Price,
937        #[case] expected: Price,
938    ) {
939        let price = trailing_stop_calculate_with_bid_ask(
940            Price::from("0.01"),
941            trailing_offset_type,
942            side,
943            offset,
944            bid,
945            ask,
946        )
947        .unwrap();
948
949        assert_eq!(price, expected);
950    }
951
952    #[rstest]
953    fn test_trailing_stop_limit_basis_points_buy_improve() {
954        let order = OrderTestBuilder::new(OrderType::TrailingStopLimit)
955            .instrument_id("BTCUSDT-PERP.BINANCE".into())
956            .side(OrderSide::Buy)
957            .trigger_price(Price::new(110.0, 2))
958            .price(Price::new(109.5, 2))
959            .trailing_offset_type(TrailingOffsetType::BasisPoints)
960            .trailing_offset(dec!(50))
961            .limit_offset(dec!(25))
962            .trigger_type(TriggerType::LastPrice)
963            .quantity(Quantity::from(1))
964            .build();
965
966        let (new_trigger, new_limit) = trailing_stop_calculate(
967            Price::new(0.01, 2),
968            None,
969            &order,
970            None,
971            None,
972            Some(Price::new(98.0, 2)),
973        )
974        .unwrap();
975
976        assert_eq!(new_trigger.unwrap(), Price::from("98.49"));
977        assert_eq!(new_limit.unwrap(), Price::from("98.24"));
978    }
979
980    #[rstest]
981    #[case(OrderSide::Buy, "105.00", "100.00", "101.00")]
982    #[case(OrderSide::Sell, "95.00", "100.00", "99.00")]
983    fn test_trigger_override_takes_precedence(
984        #[case] side: OrderSide,
985        #[case] stored: &str,
986        #[case] override_price: &str,
987        #[case] last: &str,
988    ) {
989        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
990            .instrument_id("BTCUSDT-PERP.BINANCE".into())
991            .side(side)
992            .trigger_price(Price::from(stored))
993            .trailing_offset_type(TrailingOffsetType::Price)
994            .trailing_offset(dec!(1))
995            .trigger_type(TriggerType::LastPrice)
996            .quantity(Quantity::from(1))
997            .build();
998
999        let result = trailing_stop_calculate(
1000            Price::from("0.01"),
1001            Some(Price::from(override_price)),
1002            &order,
1003            None,
1004            None,
1005            Some(Price::from(last)),
1006        )
1007        .unwrap();
1008
1009        assert_eq!(result, (None, None));
1010    }
1011
1012    #[rstest]
1013    #[case(OrderSide::Buy, "100.00", "105.00", None, Some("100.50"))]
1014    #[case(OrderSide::Buy, "105.00", "100.00", Some("101.00"), None)]
1015    #[case(OrderSide::Sell, "100.00", "95.00", None, Some("99.50"))]
1016    #[case(OrderSide::Sell, "95.00", "100.00", Some("99.00"), None)]
1017    fn test_trailing_limit_prices_improve_independently(
1018        #[case] side: OrderSide,
1019        #[case] trigger: &str,
1020        #[case] limit: &str,
1021        #[case] expected_trigger: Option<&str>,
1022        #[case] expected_limit: Option<&str>,
1023    ) {
1024        let order = OrderTestBuilder::new(OrderType::TrailingStopLimit)
1025            .instrument_id("BTCUSDT-PERP.BINANCE".into())
1026            .side(side)
1027            .trigger_price(Price::from(trigger))
1028            .price(Price::from(limit))
1029            .trailing_offset_type(TrailingOffsetType::Price)
1030            .trailing_offset(dec!(1))
1031            .limit_offset(dec!(0.5))
1032            .trigger_type(TriggerType::LastPrice)
1033            .quantity(Quantity::from(1))
1034            .build();
1035
1036        let result = trailing_stop_calculate(
1037            Price::from("0.01"),
1038            None,
1039            &order,
1040            None,
1041            None,
1042            Some(Price::from("100.00")),
1043        )
1044        .unwrap();
1045
1046        assert_eq!(
1047            result,
1048            (
1049                expected_trigger.map(Price::from),
1050                expected_limit.map(Price::from)
1051            )
1052        );
1053    }
1054
1055    #[rstest]
1056    #[case(OrderSide::Buy, "110.00", "98.00", "99.00", "98.50")]
1057    #[case(OrderSide::Buy, "110.00", "103.00", "102.00", "101.50")]
1058    #[case(OrderSide::Sell, "90.00", "103.00", "102.00", "102.50")]
1059    #[case(OrderSide::Sell, "90.00", "98.00", "99.00", "99.50")]
1060    fn test_trailing_limit_last_or_bid_ask_keeps_best_prices(
1061        #[case] side: OrderSide,
1062        #[case] initial: &str,
1063        #[case] last: &str,
1064        #[case] expected_trigger: &str,
1065        #[case] expected_limit: &str,
1066    ) {
1067        let order = OrderTestBuilder::new(OrderType::TrailingStopLimit)
1068            .instrument_id("BTCUSDT-PERP.BINANCE".into())
1069            .side(side)
1070            .trigger_price(Price::from(initial))
1071            .price(Price::from(initial))
1072            .trailing_offset_type(TrailingOffsetType::Price)
1073            .trailing_offset(dec!(1))
1074            .limit_offset(dec!(0.5))
1075            .trigger_type(TriggerType::LastOrBidAsk)
1076            .quantity(Quantity::from(1))
1077            .build();
1078
1079        let result = trailing_stop_calculate(
1080            Price::from("0.01"),
1081            None,
1082            &order,
1083            Some(Price::from("100.00")),
1084            Some(Price::from("101.00")),
1085            Some(Price::from(last)),
1086        )
1087        .unwrap();
1088
1089        assert_eq!(
1090            result,
1091            (
1092                Some(Price::from(expected_trigger)),
1093                Some(Price::from(expected_limit))
1094            )
1095        );
1096    }
1097
1098    #[rstest]
1099    #[case(OrderSide::Buy, TriggerType::LastPrice, "99.00", "98.50")]
1100    #[case(OrderSide::Buy, TriggerType::MarkPrice, "99.00", "98.50")]
1101    #[case(OrderSide::Buy, TriggerType::Default, "102.00", "101.50")]
1102    #[case(OrderSide::Buy, TriggerType::BidAsk, "102.00", "101.50")]
1103    #[case(OrderSide::Buy, TriggerType::LastOrBidAsk, "99.00", "98.50")]
1104    #[case(OrderSide::Sell, TriggerType::LastPrice, "97.00", "97.50")]
1105    #[case(OrderSide::Sell, TriggerType::MarkPrice, "97.00", "97.50")]
1106    #[case(OrderSide::Sell, TriggerType::Default, "99.00", "99.50")]
1107    #[case(OrderSide::Sell, TriggerType::BidAsk, "99.00", "99.50")]
1108    #[case(OrderSide::Sell, TriggerType::LastOrBidAsk, "99.00", "99.50")]
1109    fn test_trailing_prices_initialize_from_market(
1110        #[case] side: OrderSide,
1111        #[case] trigger_type: TriggerType,
1112        #[case] expected_trigger: &str,
1113        #[case] expected_limit: &str,
1114        #[values(OrderType::TrailingStopMarket, OrderType::TrailingStopLimit)]
1115        order_type: OrderType,
1116    ) {
1117        let order = OrderTestBuilder::new(order_type)
1118            .instrument_id("BTCUSDT-PERP.BINANCE".into())
1119            .side(side)
1120            .activation_price(Price::from("150.00"))
1121            .trailing_offset_type(TrailingOffsetType::Price)
1122            .trailing_offset(dec!(1))
1123            .limit_offset(dec!(0.5))
1124            .trigger_type(trigger_type)
1125            .quantity(Quantity::from(1))
1126            .build();
1127
1128        let result = trailing_stop_calculate(
1129            Price::from("0.01"),
1130            None,
1131            &order,
1132            Some(Price::from("100.00")),
1133            Some(Price::from("101.00")),
1134            Some(Price::from("98.00")),
1135        )
1136        .unwrap();
1137
1138        let limit =
1139            (order_type == OrderType::TrailingStopLimit).then(|| Price::from(expected_limit));
1140
1141        assert_eq!(result, (Some(Price::from(expected_trigger)), limit));
1142        assert_eq!(result.0.map(|price| price.precision), Some(2));
1143        assert_eq!(result.1.map(|price| price.precision), limit.map(|_| 2));
1144    }
1145
1146    #[rstest]
1147    #[case(OrderType::TrailingStopMarket)]
1148    #[case(OrderType::TrailingStopLimit)]
1149    fn test_last_or_bid_ask_checks_quote_calculation_before_last(#[case] order_type: OrderType) {
1150        let order = OrderTestBuilder::new(order_type)
1151            .instrument_id("BTCUSDT-PERP.BINANCE".into())
1152            .side(OrderSide::Buy)
1153            .trailing_offset_type(TrailingOffsetType::PriceTier)
1154            .trailing_offset(dec!(1))
1155            .limit_offset(dec!(0.5))
1156            .trigger_type(TriggerType::LastOrBidAsk)
1157            .quantity(Quantity::from(1))
1158            .build();
1159
1160        let error = trailing_stop_calculate(
1161            Price::from("0.01"),
1162            None,
1163            &order,
1164            Some(Price::from("100.00")),
1165            Some(Price::from("101.00")),
1166            None,
1167        )
1168        .unwrap_err();
1169
1170        assert_eq!(
1171            error,
1172            TrailingStopError::UnsupportedOffsetType(TrailingOffsetType::PriceTier)
1173        );
1174        assert_eq!(
1175            error.to_string(),
1176            "`TrailingOffsetType` PRICE_TIER not currently supported"
1177        );
1178    }
1179
1180    #[rstest]
1181    #[case(OrderType::TrailingStopMarket)]
1182    #[case(OrderType::TrailingStopLimit)]
1183    fn test_last_or_bid_ask_requires_last(#[case] order_type: OrderType) {
1184        let order = OrderTestBuilder::new(order_type)
1185            .instrument_id("BTCUSDT-PERP.BINANCE".into())
1186            .side(OrderSide::Buy)
1187            .trailing_offset_type(TrailingOffsetType::Price)
1188            .trailing_offset(dec!(1))
1189            .limit_offset(dec!(0.5))
1190            .trigger_type(TriggerType::LastOrBidAsk)
1191            .quantity(Quantity::from(1))
1192            .build();
1193
1194        let error = trailing_stop_calculate(
1195            Price::from("0.01"),
1196            None,
1197            &order,
1198            Some(Price::from("100.00")),
1199            Some(Price::from("101.00")),
1200            None,
1201        )
1202        .unwrap_err();
1203
1204        assert_eq!(error, TrailingStopError::MissingLast);
1205        assert_eq!(error.to_string(), "Last required");
1206    }
1207
1208    #[rstest]
1209    fn test_calculate_with_unsupported_offset_type() {
1210        let last_error = trailing_stop_calculate_with_last(
1211            Price::from("0.01"),
1212            TrailingOffsetType::PriceTier,
1213            OrderSide::Buy,
1214            dec!(1),
1215            Price::from("100.00"),
1216        )
1217        .unwrap_err();
1218        let quote_error = trailing_stop_calculate_with_bid_ask(
1219            Price::from("0.01"),
1220            TrailingOffsetType::PriceTier,
1221            OrderSide::Sell,
1222            dec!(2),
1223            Price::from("101.00"),
1224            Price::from("102.00"),
1225        )
1226        .unwrap_err();
1227
1228        assert_eq!(
1229            last_error,
1230            TrailingStopError::UnsupportedOffsetType(TrailingOffsetType::PriceTier)
1231        );
1232        assert_eq!(quote_error, last_error);
1233    }
1234
1235    #[rstest]
1236    fn test_calculate_price_error_preserves_source() {
1237        let increment = Price::from("0.01");
1238        let quote = Price::max(0);
1239        let source =
1240            Price::from_decimal_dp(quote.as_decimal() + dec!(1), increment.precision).unwrap_err();
1241        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
1242            .instrument_id("BTCUSDT-PERP.BINANCE".into())
1243            .side(OrderSide::Buy)
1244            .trailing_offset_type(TrailingOffsetType::Price)
1245            .trailing_offset(dec!(1))
1246            .trigger_type(TriggerType::LastPrice)
1247            .quantity(Quantity::from(1))
1248            .build();
1249
1250        let errors = [
1251            trailing_stop_calculate(increment, None, &order, None, None, Some(quote)).unwrap_err(),
1252            trailing_stop_calculate_with_last(
1253                increment,
1254                TrailingOffsetType::Price,
1255                OrderSide::Buy,
1256                dec!(1),
1257                quote,
1258            )
1259            .unwrap_err(),
1260            trailing_stop_calculate_with_bid_ask(
1261                increment,
1262                TrailingOffsetType::Price,
1263                OrderSide::Buy,
1264                dec!(1),
1265                Price::from("100.00"),
1266                quote,
1267            )
1268            .unwrap_err(),
1269        ];
1270
1271        for error in errors {
1272            assert_eq!(
1273                error,
1274                TrailingStopError::InvalidPrice(Box::new(source.clone()))
1275            );
1276            assert_eq!(error.to_string(), source.to_string());
1277            assert_eq!(
1278                std::error::Error::source(&error)
1279                    .unwrap()
1280                    .downcast_ref::<Box<CorrectnessError>>()
1281                    .map(Box::as_ref),
1282                Some(&source)
1283            );
1284        }
1285    }
1286}