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