Skip to main content

nautilus_model/orders/
trailing_stop_market.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::{
17    fmt::Display,
18    ops::{Deref, DerefMut},
19};
20
21use indexmap::IndexMap;
22use nautilus_core::{
23    UUID4, UnixNanos,
24    correctness::{CorrectnessError, FAILED},
25};
26use rust_decimal::Decimal;
27use serde::{Deserialize, Serialize};
28use ustr::Ustr;
29
30use super::{Order, OrderAny, OrderCore};
31use crate::{
32    enums::{
33        ContingencyType, LiquiditySide, OrderSide, OrderStatus, OrderType, PositionSide,
34        TimeInForce, TrailingOffsetType, TriggerType,
35    },
36    events::{OrderEventAny, OrderInitialized, OrderUpdated},
37    identifiers::{
38        AccountId, ClientOrderId, ExecAlgorithmId, InstrumentId, OrderListId, PositionId,
39        StrategyId, Symbol, TradeId, TraderId, Venue, VenueOrderId,
40    },
41    orders::{OrderError, check_display_qty, check_time_in_force},
42    types::{Currency, Money, Price, Quantity, quantity::check_positive_quantity},
43};
44
45#[derive(Clone, Debug, Serialize, Deserialize)]
46#[cfg_attr(
47    feature = "python",
48    pyo3::pyclass(module = "nautilus_trader.core.nautilus_pyo3.model", from_py_object)
49)]
50#[cfg_attr(
51    feature = "python",
52    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
53)]
54pub struct TrailingStopMarketOrder {
55    core: OrderCore,
56    pub activation_price: Option<Price>,
57    pub trigger_price: Price,
58    pub trigger_type: TriggerType,
59    pub trailing_offset: Decimal,
60    pub trailing_offset_type: TrailingOffsetType,
61    pub expire_time: Option<UnixNanos>,
62    pub display_qty: Option<Quantity>,
63    pub trigger_instrument_id: Option<InstrumentId>,
64    pub is_activated: bool,
65    pub is_triggered: bool,
66    pub ts_triggered: Option<UnixNanos>,
67}
68
69impl TrailingStopMarketOrder {
70    /// Creates a new [`TrailingStopMarketOrder`] instance.
71    ///
72    /// # Errors
73    ///
74    /// Returns an error if:
75    /// - The `quantity` is not positive.
76    /// - The `display_qty` (when provided) exceeds `quantity`.
77    /// - The `time_in_force` is `GTD` **and** `expire_time` is `None` or zero.
78    #[expect(clippy::too_many_arguments)]
79    pub fn new_checked(
80        trader_id: TraderId,
81        strategy_id: StrategyId,
82        instrument_id: InstrumentId,
83        client_order_id: ClientOrderId,
84        order_side: OrderSide,
85        quantity: Quantity,
86        trigger_price: Price,
87        trigger_type: TriggerType,
88        trailing_offset: Decimal,
89        trailing_offset_type: TrailingOffsetType,
90        time_in_force: TimeInForce,
91        expire_time: Option<UnixNanos>,
92        reduce_only: bool,
93        quote_quantity: bool,
94        display_qty: Option<Quantity>,
95        emulation_trigger: Option<TriggerType>,
96        trigger_instrument_id: Option<InstrumentId>,
97        contingency_type: Option<ContingencyType>,
98        order_list_id: Option<OrderListId>,
99        linked_order_ids: Option<Vec<ClientOrderId>>,
100        parent_order_id: Option<ClientOrderId>,
101        exec_algorithm_id: Option<ExecAlgorithmId>,
102        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
103        exec_spawn_id: Option<ClientOrderId>,
104        tags: Option<Vec<Ustr>>,
105        init_id: UUID4,
106        ts_init: UnixNanos,
107    ) -> Result<Self, OrderError> {
108        check_positive_quantity(quantity, stringify!(quantity))?;
109        check_display_qty(display_qty, quantity)?;
110        check_time_in_force(time_in_force, expire_time)?;
111
112        let init_order = OrderInitialized::new(
113            trader_id,
114            strategy_id,
115            instrument_id,
116            client_order_id,
117            order_side,
118            OrderType::TrailingStopMarket,
119            quantity,
120            time_in_force,
121            /*post_only=*/ false,
122            reduce_only,
123            quote_quantity,
124            /*is_close=*/ false,
125            init_id,
126            ts_init,
127            ts_init,
128            /*price=*/ None,
129            Some(trigger_price),
130            Some(trigger_type),
131            /*limit_offset=*/ None,
132            Some(trailing_offset),
133            Some(trailing_offset_type),
134            expire_time,
135            display_qty,
136            emulation_trigger,
137            trigger_instrument_id,
138            contingency_type,
139            order_list_id,
140            linked_order_ids,
141            parent_order_id,
142            exec_algorithm_id,
143            exec_algorithm_params,
144            exec_spawn_id,
145            tags,
146        );
147
148        Ok(Self {
149            core: OrderCore::new(init_order),
150            activation_price: None,
151            trigger_price,
152            trigger_type,
153            trailing_offset,
154            trailing_offset_type,
155            expire_time,
156            display_qty,
157            trigger_instrument_id,
158            is_activated: false,
159            is_triggered: false,
160            ts_triggered: None,
161        })
162    }
163
164    /// Creates a new [`TrailingStopMarketOrder`] instance.
165    ///
166    /// # Panics
167    ///
168    /// Panics if any order validation fails (see [`TrailingStopMarketOrder::new_checked`]).
169    #[expect(clippy::too_many_arguments)]
170    #[must_use]
171    pub fn new(
172        trader_id: TraderId,
173        strategy_id: StrategyId,
174        instrument_id: InstrumentId,
175        client_order_id: ClientOrderId,
176        order_side: OrderSide,
177        quantity: Quantity,
178        trigger_price: Price,
179        trigger_type: TriggerType,
180        trailing_offset: Decimal,
181        trailing_offset_type: TrailingOffsetType,
182        time_in_force: TimeInForce,
183        expire_time: Option<UnixNanos>,
184        reduce_only: bool,
185        quote_quantity: bool,
186        display_qty: Option<Quantity>,
187        emulation_trigger: Option<TriggerType>,
188        trigger_instrument_id: Option<InstrumentId>,
189        contingency_type: Option<ContingencyType>,
190        order_list_id: Option<OrderListId>,
191        linked_order_ids: Option<Vec<ClientOrderId>>,
192        parent_order_id: Option<ClientOrderId>,
193        exec_algorithm_id: Option<ExecAlgorithmId>,
194        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
195        exec_spawn_id: Option<ClientOrderId>,
196        tags: Option<Vec<Ustr>>,
197        init_id: UUID4,
198        ts_init: UnixNanos,
199    ) -> Self {
200        Self::new_checked(
201            trader_id,
202            strategy_id,
203            instrument_id,
204            client_order_id,
205            order_side,
206            quantity,
207            trigger_price,
208            trigger_type,
209            trailing_offset,
210            trailing_offset_type,
211            time_in_force,
212            expire_time,
213            reduce_only,
214            quote_quantity,
215            display_qty,
216            emulation_trigger,
217            trigger_instrument_id,
218            contingency_type,
219            order_list_id,
220            linked_order_ids,
221            parent_order_id,
222            exec_algorithm_id,
223            exec_algorithm_params,
224            exec_spawn_id,
225            tags,
226            init_id,
227            ts_init,
228        )
229        .unwrap_or_else(|e| panic!("{FAILED}: {e}"))
230    }
231
232    #[must_use]
233    pub fn has_activation_price(&self) -> bool {
234        self.activation_price.is_some()
235    }
236
237    pub fn set_activated(&mut self) {
238        debug_assert!(!self.is_activated, "double activation");
239        self.is_activated = true;
240    }
241}
242
243impl PartialEq for TrailingStopMarketOrder {
244    fn eq(&self, other: &Self) -> bool {
245        self.client_order_id == other.client_order_id
246    }
247}
248
249impl Deref for TrailingStopMarketOrder {
250    type Target = OrderCore;
251    fn deref(&self) -> &Self::Target {
252        &self.core
253    }
254}
255
256impl DerefMut for TrailingStopMarketOrder {
257    fn deref_mut(&mut self) -> &mut Self::Target {
258        &mut self.core
259    }
260}
261
262impl Order for TrailingStopMarketOrder {
263    fn into_any(self) -> OrderAny {
264        OrderAny::TrailingStopMarket(self)
265    }
266
267    fn status(&self) -> OrderStatus {
268        self.status
269    }
270
271    fn trader_id(&self) -> TraderId {
272        self.trader_id
273    }
274
275    fn strategy_id(&self) -> StrategyId {
276        self.strategy_id
277    }
278
279    fn instrument_id(&self) -> InstrumentId {
280        self.instrument_id
281    }
282
283    fn symbol(&self) -> Symbol {
284        self.instrument_id.symbol
285    }
286
287    fn venue(&self) -> Venue {
288        self.instrument_id.venue
289    }
290
291    fn client_order_id(&self) -> ClientOrderId {
292        self.client_order_id
293    }
294
295    fn venue_order_id(&self) -> Option<VenueOrderId> {
296        self.venue_order_id
297    }
298
299    fn position_id(&self) -> Option<PositionId> {
300        self.position_id
301    }
302
303    fn account_id(&self) -> Option<AccountId> {
304        self.account_id
305    }
306
307    fn last_trade_id(&self) -> Option<TradeId> {
308        self.last_trade_id
309    }
310
311    fn order_side(&self) -> OrderSide {
312        self.side
313    }
314
315    fn order_type(&self) -> OrderType {
316        self.order_type
317    }
318
319    fn quantity(&self) -> Quantity {
320        self.quantity
321    }
322
323    fn time_in_force(&self) -> TimeInForce {
324        self.time_in_force
325    }
326
327    fn expire_time(&self) -> Option<UnixNanos> {
328        self.expire_time
329    }
330
331    fn price(&self) -> Option<Price> {
332        None
333    }
334
335    fn trigger_price(&self) -> Option<Price> {
336        Some(self.trigger_price)
337    }
338
339    fn activation_price(&self) -> Option<Price> {
340        self.activation_price
341    }
342
343    fn trigger_type(&self) -> Option<TriggerType> {
344        Some(self.trigger_type)
345    }
346
347    fn liquidity_side(&self) -> Option<LiquiditySide> {
348        self.liquidity_side
349    }
350
351    fn is_post_only(&self) -> bool {
352        false
353    }
354
355    fn is_reduce_only(&self) -> bool {
356        self.is_reduce_only
357    }
358
359    fn is_quote_quantity(&self) -> bool {
360        self.is_quote_quantity
361    }
362
363    fn has_price(&self) -> bool {
364        false
365    }
366
367    fn display_qty(&self) -> Option<Quantity> {
368        self.display_qty
369    }
370
371    fn limit_offset(&self) -> Option<Decimal> {
372        None
373    }
374
375    fn trailing_offset(&self) -> Option<Decimal> {
376        Some(self.trailing_offset)
377    }
378
379    fn trailing_offset_type(&self) -> Option<TrailingOffsetType> {
380        Some(self.trailing_offset_type)
381    }
382
383    fn emulation_trigger(&self) -> Option<TriggerType> {
384        self.emulation_trigger
385    }
386
387    fn trigger_instrument_id(&self) -> Option<InstrumentId> {
388        self.trigger_instrument_id
389    }
390
391    fn contingency_type(&self) -> Option<ContingencyType> {
392        self.contingency_type
393    }
394
395    fn order_list_id(&self) -> Option<OrderListId> {
396        self.order_list_id
397    }
398
399    fn linked_order_ids(&self) -> Option<&[ClientOrderId]> {
400        self.linked_order_ids.as_deref()
401    }
402
403    fn parent_order_id(&self) -> Option<ClientOrderId> {
404        self.parent_order_id
405    }
406
407    fn exec_algorithm_id(&self) -> Option<ExecAlgorithmId> {
408        self.exec_algorithm_id
409    }
410
411    fn exec_algorithm_params(&self) -> Option<&IndexMap<Ustr, Ustr>> {
412        self.exec_algorithm_params.as_ref()
413    }
414
415    fn exec_spawn_id(&self) -> Option<ClientOrderId> {
416        self.exec_spawn_id
417    }
418
419    fn tags(&self) -> Option<&[Ustr]> {
420        self.tags.as_deref()
421    }
422
423    fn filled_qty(&self) -> Quantity {
424        self.filled_qty
425    }
426
427    fn leaves_qty(&self) -> Quantity {
428        self.leaves_qty
429    }
430
431    fn overfill_qty(&self) -> Quantity {
432        self.overfill_qty
433    }
434
435    fn avg_px(&self) -> Option<f64> {
436        self.avg_px
437    }
438
439    fn slippage(&self) -> Option<f64> {
440        self.slippage
441    }
442
443    fn init_id(&self) -> UUID4 {
444        self.init_id
445    }
446
447    fn ts_init(&self) -> UnixNanos {
448        self.ts_init
449    }
450
451    fn ts_submitted(&self) -> Option<UnixNanos> {
452        self.ts_submitted
453    }
454
455    fn ts_accepted(&self) -> Option<UnixNanos> {
456        self.ts_accepted
457    }
458
459    fn ts_closed(&self) -> Option<UnixNanos> {
460        self.ts_closed
461    }
462
463    fn ts_last(&self) -> UnixNanos {
464        self.ts_last
465    }
466
467    fn events(&self) -> Vec<&OrderEventAny> {
468        self.events.iter().collect()
469    }
470
471    fn venue_order_ids(&self) -> Vec<&VenueOrderId> {
472        self.venue_order_ids.iter().collect()
473    }
474
475    fn trade_ids(&self) -> Vec<&TradeId> {
476        self.trade_ids.iter().collect()
477    }
478
479    fn commissions(&self) -> &IndexMap<Currency, Money> {
480        &self.commissions
481    }
482
483    fn apply(&mut self, event: OrderEventAny) -> Result<(), OrderError> {
484        let was_filled = matches!(event, OrderEventAny::Filled(_));
485        let is_order_triggered = matches!(event, OrderEventAny::Triggered(_));
486        let ts_event = if is_order_triggered {
487            Some(event.ts_event())
488        } else {
489            None
490        };
491
492        self.core.apply(event.clone())?;
493
494        if let OrderEventAny::Updated(ref event) = event {
495            self.update(event);
496        }
497
498        if is_order_triggered {
499            self.is_triggered = true;
500            self.ts_triggered = ts_event;
501        }
502
503        if was_filled {
504            self.core.set_slippage(self.trigger_price);
505        }
506
507        Ok(())
508    }
509
510    fn update(&mut self, event: &OrderUpdated) {
511        assert!(event.price.is_none(), "{}", OrderError::InvalidOrderEvent);
512
513        if let Some(trigger_price) = event.trigger_price {
514            self.trigger_price = trigger_price;
515        }
516
517        self.quantity = event.quantity;
518        self.leaves_qty = self.quantity.saturating_sub(self.filled_qty);
519    }
520
521    fn is_triggered(&self) -> Option<bool> {
522        Some(self.is_triggered)
523    }
524
525    fn set_position_id(&mut self, position_id: Option<PositionId>) {
526        self.position_id = position_id;
527    }
528
529    fn set_quantity(&mut self, quantity: Quantity) {
530        self.quantity = quantity;
531    }
532
533    fn set_leaves_qty(&mut self, leaves_qty: Quantity) {
534        self.leaves_qty = leaves_qty;
535    }
536
537    fn set_emulation_trigger(&mut self, emulation_trigger: Option<TriggerType>) {
538        self.emulation_trigger = emulation_trigger;
539    }
540
541    fn set_is_quote_quantity(&mut self, is_quote_quantity: bool) {
542        self.is_quote_quantity = is_quote_quantity;
543    }
544
545    fn set_liquidity_side(&mut self, liquidity_side: LiquiditySide) {
546        self.liquidity_side = Some(liquidity_side);
547    }
548
549    fn would_reduce_only(&self, side: PositionSide, position_qty: Quantity) -> bool {
550        self.core.would_reduce_only(side, position_qty)
551    }
552
553    fn previous_status(&self) -> Option<OrderStatus> {
554        self.core.previous_status
555    }
556}
557
558impl Display for TrailingStopMarketOrder {
559    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
560        write!(
561            f,
562            "TrailingStopMarketOrder({} {} {} {} {}, status={}, client_order_id={}, venue_order_id={}, position_id={}, exec_algorithm_id={}, exec_spawn_id={}, tags={:?}, activation_price={:?}, is_activated={})",
563            self.side,
564            self.quantity.to_formatted_string(),
565            self.instrument_id,
566            self.order_type,
567            self.time_in_force,
568            self.status,
569            self.client_order_id,
570            self.venue_order_id
571                .map_or_else(|| "None".to_string(), |id| format!("{id}")),
572            self.position_id
573                .map_or_else(|| "None".to_string(), |id| format!("{id}")),
574            self.exec_algorithm_id
575                .map_or_else(|| "None".to_string(), |id| format!("{id}")),
576            self.exec_spawn_id
577                .map_or_else(|| "None".to_string(), |id| format!("{id}")),
578            self.tags,
579            self.activation_price,
580            self.is_activated
581        )
582    }
583}
584
585impl TryFrom<OrderInitialized> for TrailingStopMarketOrder {
586    type Error = OrderError;
587
588    fn try_from(event: OrderInitialized) -> Result<Self, Self::Error> {
589        let trigger_price =
590            event
591                .trigger_price
592                .ok_or_else(|| CorrectnessError::PredicateViolation {
593                    message:
594                        "`trigger_price` is required for `TrailingStopMarketOrder` initialization"
595                            .to_string(),
596                })?;
597        let trigger_type =
598            event
599                .trigger_type
600                .ok_or_else(|| CorrectnessError::PredicateViolation {
601                    message:
602                        "`trigger_type` is required for `TrailingStopMarketOrder` initialization"
603                            .to_string(),
604                })?;
605        let trailing_offset =
606            event
607                .trailing_offset
608                .ok_or_else(|| CorrectnessError::PredicateViolation {
609                    message:
610                        "`trailing_offset` is required for `TrailingStopMarketOrder` initialization"
611                            .to_string(),
612                })?;
613        let trailing_offset_type = event.trailing_offset_type.ok_or_else(|| {
614            CorrectnessError::PredicateViolation {
615                message: "`trailing_offset_type` is required for `TrailingStopMarketOrder` initialization"
616                    .to_string(),
617            }
618        })?;
619        Self::new_checked(
620            event.trader_id,
621            event.strategy_id,
622            event.instrument_id,
623            event.client_order_id,
624            event.order_side,
625            event.quantity,
626            trigger_price,
627            trigger_type,
628            trailing_offset,
629            trailing_offset_type,
630            event.time_in_force,
631            event.expire_time,
632            event.reduce_only,
633            event.quote_quantity,
634            event.display_qty,
635            event.emulation_trigger,
636            event.trigger_instrument_id,
637            event.contingency_type,
638            event.order_list_id,
639            event.linked_order_ids,
640            event.parent_order_id,
641            event.exec_algorithm_id,
642            event.exec_algorithm_params,
643            event.exec_spawn_id,
644            event.tags,
645            event.event_id,
646            event.ts_event,
647        )
648    }
649}
650
651#[cfg(test)]
652mod tests {
653    use rstest::rstest;
654    use rust_decimal::Decimal;
655    use rust_decimal_macros::dec;
656
657    use super::*;
658    use crate::{
659        enums::{TimeInForce, TrailingOffsetType, TriggerType},
660        events::order::spec::{OrderFilledSpec, OrderInitializedSpec},
661        identifiers::InstrumentId,
662        instruments::{CurrencyPair, stubs::*},
663        orders::{builder::OrderTestBuilder, stubs::TestOrderStubs},
664        types::{Price, Quantity},
665    };
666
667    #[rstest]
668    fn test_initialize(audusd_sim: CurrencyPair) {
669        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
670            .instrument_id(audusd_sim.id)
671            .side(OrderSide::Buy)
672            .trigger_price(Price::from("0.68000"))
673            .trailing_offset(dec!(10))
674            .quantity(Quantity::from(1))
675            .build();
676
677        assert_eq!(order.trigger_price(), Some(Price::from("0.68000")));
678        assert_eq!(order.price(), None);
679
680        assert_eq!(order.time_in_force(), TimeInForce::Gtc);
681
682        assert_eq!(order.is_triggered(), Some(false));
683        assert_eq!(order.filled_qty(), Quantity::from(0));
684        assert_eq!(order.leaves_qty(), Quantity::from(1));
685
686        assert_eq!(order.display_qty(), None);
687        assert_eq!(order.trigger_instrument_id(), None);
688        assert_eq!(order.order_list_id(), None);
689    }
690
691    #[rstest]
692    fn test_display(audusd_sim: CurrencyPair) {
693        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
694            .instrument_id(audusd_sim.id)
695            .side(OrderSide::Buy)
696            .trigger_price(Price::from("0.68000"))
697            .trigger_type(TriggerType::LastPrice)
698            .trailing_offset(dec!(10))
699            .trailing_offset_type(TrailingOffsetType::Price)
700            .quantity(Quantity::from(1))
701            .build();
702
703        assert_eq!(
704            order.to_string(),
705            "TrailingStopMarketOrder(BUY 1 AUD/USD.SIM TRAILING_STOP_MARKET GTC, status=INITIALIZED, client_order_id=O-19700101-000000-001-001-1, venue_order_id=None, position_id=None, exec_algorithm_id=None, exec_spawn_id=None, tags=None, activation_price=None, is_activated=false)"
706        );
707    }
708
709    #[rstest]
710    #[should_panic(expected = "Condition failed: `display_qty` may not exceed `quantity`")]
711    fn test_display_qty_gt_quantity_err(audusd_sim: CurrencyPair) {
712        let _ = OrderTestBuilder::new(OrderType::TrailingStopMarket)
713            .instrument_id(audusd_sim.id)
714            .side(OrderSide::Buy)
715            .trigger_price(Price::from("0.68000"))
716            .trigger_type(TriggerType::LastPrice)
717            .trailing_offset(dec!(10))
718            .trailing_offset_type(TrailingOffsetType::Price)
719            .quantity(Quantity::from(1))
720            .display_qty(Quantity::from(2))
721            .build();
722    }
723
724    #[rstest]
725    #[should_panic(
726        expected = "Condition failed: invalid `Quantity` for 'quantity' not positive, was 0"
727    )]
728    fn test_quantity_zero_err(audusd_sim: CurrencyPair) {
729        let _ = OrderTestBuilder::new(OrderType::TrailingStopMarket)
730            .instrument_id(audusd_sim.id)
731            .side(OrderSide::Buy)
732            .trigger_price(Price::from("0.68000"))
733            .trigger_type(TriggerType::LastPrice)
734            .trailing_offset(dec!(10))
735            .trailing_offset_type(TrailingOffsetType::Price)
736            .quantity(Quantity::from(0))
737            .build();
738    }
739
740    #[rstest]
741    #[should_panic(expected = "Condition failed: `expire_time` is required for `GTD` order")]
742    fn test_gtd_without_expire_err(audusd_sim: CurrencyPair) {
743        let _ = OrderTestBuilder::new(OrderType::TrailingStopMarket)
744            .instrument_id(audusd_sim.id)
745            .side(OrderSide::Buy)
746            .trigger_price(Price::from("0.68000"))
747            .trigger_type(TriggerType::LastPrice)
748            .trailing_offset(dec!(10))
749            .trailing_offset_type(TrailingOffsetType::Price)
750            .time_in_force(TimeInForce::Gtd)
751            .quantity(Quantity::from(1))
752            .build();
753    }
754    #[rstest]
755    fn test_trailing_stop_market_order_update() {
756        // Create and accept a basic trailing stop market order
757        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
758            .instrument_id(InstrumentId::from("BTC-USDT.BINANCE"))
759            .quantity(Quantity::from(10))
760            .trigger_price(Price::new(100.0, 2))
761            .trailing_offset(Decimal::new(5, 1)) // 0.5
762            .trailing_offset_type(TrailingOffsetType::NoTrailingOffset)
763            .build();
764
765        let mut accepted_order = TestOrderStubs::make_accepted_order(&order);
766
767        // Update with new values
768        let updated_trigger_price = Price::new(95.0, 2);
769        let updated_quantity = Quantity::from(5);
770
771        let event = OrderUpdated {
772            client_order_id: accepted_order.client_order_id(),
773            strategy_id: accepted_order.strategy_id(),
774            trigger_price: Some(updated_trigger_price),
775            quantity: updated_quantity,
776            ..Default::default()
777        };
778
779        accepted_order.apply(OrderEventAny::Updated(event)).unwrap();
780
781        // Verify updates were applied correctly
782        assert_eq!(accepted_order.quantity(), updated_quantity);
783        assert_eq!(accepted_order.trigger_price(), Some(updated_trigger_price));
784    }
785
786    #[rstest]
787    fn test_trailing_stop_market_order_expire_time() {
788        // Create a new TrailingStopMarketOrder with an expire time
789        let expire_time = UnixNanos::from(1_234_567_890);
790        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
791            .instrument_id(InstrumentId::from("BTC-USDT.BINANCE"))
792            .quantity(Quantity::from(10))
793            .trigger_price(Price::new(100.0, 2))
794            .trailing_offset(Decimal::new(5, 1)) // 0.5
795            .trailing_offset_type(TrailingOffsetType::NoTrailingOffset)
796            .expire_time(expire_time)
797            .build();
798
799        // Assert that the expire time is set correctly
800        assert_eq!(order.expire_time(), Some(expire_time));
801    }
802
803    #[rstest]
804    fn test_trailing_stop_market_order_trigger_instrument_id() {
805        // Create a new TrailingStopMarketOrder with a trigger instrument ID
806        let trigger_instrument_id = InstrumentId::from("ETH-USDT.BINANCE");
807        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
808            .instrument_id(InstrumentId::from("BTC-USDT.BINANCE"))
809            .quantity(Quantity::from(10))
810            .trigger_price(Price::new(100.0, 2))
811            .trailing_offset(Decimal::new(5, 1)) // 0.5
812            .trailing_offset_type(TrailingOffsetType::NoTrailingOffset)
813            .trigger_instrument_id(trigger_instrument_id)
814            .build();
815
816        // Assert that the trigger instrument ID is set correctly
817        assert_eq!(order.trigger_instrument_id(), Some(trigger_instrument_id));
818    }
819
820    #[rstest]
821    fn test_trailing_stop_market_order_from_order_initialized() {
822        // Create an OrderInitialized event with all required fields for a TrailingStopMarketOrder
823        let order_initialized = OrderInitializedSpec::builder()
824            .trigger_price(Price::new(100.0, 2))
825            .trigger_type(TriggerType::Default)
826            .trailing_offset(Decimal::new(5, 1)) // 0.5
827            .trailing_offset_type(TrailingOffsetType::NoTrailingOffset)
828            .order_type(OrderType::TrailingStopMarket)
829            .build();
830
831        // Convert the OrderInitialized event into a TrailingStopMarketOrder
832        let order: TrailingStopMarketOrder = order_initialized.clone().try_into().unwrap();
833
834        // Assert essential fields match the OrderInitialized fields
835        assert_eq!(order.trader_id(), order_initialized.trader_id);
836        assert_eq!(order.strategy_id(), order_initialized.strategy_id);
837        assert_eq!(order.instrument_id(), order_initialized.instrument_id);
838        assert_eq!(order.client_order_id(), order_initialized.client_order_id);
839        assert_eq!(order.order_side(), order_initialized.order_side);
840        assert_eq!(order.quantity(), order_initialized.quantity);
841
842        // Assert specific fields for TrailingStopMarketOrder
843        assert_eq!(
844            order.trigger_price,
845            order_initialized.trigger_price.unwrap()
846        );
847        assert_eq!(order.trigger_type, order_initialized.trigger_type.unwrap());
848        assert_eq!(
849            order.trailing_offset,
850            order_initialized.trailing_offset.unwrap()
851        );
852        assert_eq!(
853            order.trailing_offset_type,
854            order_initialized.trailing_offset_type.unwrap()
855        );
856    }
857
858    #[rstest]
859    fn test_trailing_stop_market_order_sets_slippage_when_filled() {
860        // Create a trailing stop market order
861        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
862            .instrument_id(InstrumentId::from("BTC-USDT.BINANCE"))
863            .quantity(Quantity::from(10))
864            .side(OrderSide::Buy) // Explicitly setting Buy side
865            .trigger_price(Price::new(90.0, 2)) // Trigger price LOWER than fill price
866            .trailing_offset(Decimal::new(5, 1)) // 0.5
867            .trailing_offset_type(TrailingOffsetType::NoTrailingOffset)
868            .build();
869
870        // Accept the order first
871        let mut accepted_order = TestOrderStubs::make_accepted_order(&order);
872
873        // Create a filled event with the correct quantity
874        let fill_quantity = accepted_order.quantity(); // Use the same quantity as the order
875        let fill_price = Price::new(98.50, 2); // Use a price HIGHER than trigger price
876
877        let order_filled_event = OrderFilledSpec::builder()
878            .client_order_id(accepted_order.client_order_id())
879            .strategy_id(accepted_order.strategy_id())
880            .instrument_id(accepted_order.instrument_id())
881            .order_side(accepted_order.order_side())
882            .last_qty(fill_quantity)
883            .last_px(fill_price)
884            .venue_order_id(VenueOrderId::from("TEST-001"))
885            .trade_id(TradeId::from("TRADE-001"))
886            .build();
887
888        // Apply the fill event
889        accepted_order
890            .apply(OrderEventAny::Filled(order_filled_event))
891            .unwrap();
892
893        // The slippage calculation should be triggered by the filled event
894        assert!(accepted_order.slippage().is_some());
895
896        // We can also check the actual slippage value
897        let expected_slippage = 98.50 - 90.0; // For buy order: execution price - trigger price
898        let actual_slippage = accepted_order.slippage().unwrap();
899
900        assert!(
901            (actual_slippage - expected_slippage).abs() < 0.001,
902            "Expected slippage around {expected_slippage}, was {actual_slippage}"
903        );
904    }
905}