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 events(&self) -> Vec<&OrderEventAny> {
481        self.events.iter().collect()
482    }
483
484    fn venue_order_ids(&self) -> Vec<&VenueOrderId> {
485        self.venue_order_ids.iter().collect()
486    }
487
488    fn trade_ids(&self) -> Vec<&TradeId> {
489        self.trade_ids.iter().collect()
490    }
491
492    fn commissions(&self) -> &IndexMap<Currency, Money> {
493        &self.commissions
494    }
495
496    fn apply(&mut self, event: OrderEventAny) -> Result<(), OrderError> {
497        let updates_slippage = matches!(
498            event,
499            OrderEventAny::Filled(_) | OrderEventAny::FillVoided(_),
500        );
501        let is_order_triggered = matches!(event, OrderEventAny::Triggered(_));
502        let ts_event = if is_order_triggered {
503            Some(event.ts_event())
504        } else {
505            None
506        };
507
508        self.core.apply(event.clone())?;
509
510        if let OrderEventAny::Updated(ref event) = event {
511            self.update(event);
512        }
513
514        if is_order_triggered {
515            self.is_triggered = true;
516            self.ts_triggered = ts_event;
517        }
518
519        if updates_slippage && let Some(trigger_price) = self.trigger_price {
520            self.core.set_slippage(trigger_price);
521        }
522
523        Ok(())
524    }
525
526    fn update(&mut self, event: &OrderUpdated) {
527        assert!(event.price.is_none(), "{}", OrderError::InvalidOrderEvent);
528
529        if event.trigger_price.is_some() {
530            self.trigger_price = event.trigger_price;
531        }
532
533        self.core.apply_updated_quantity(event.quantity);
534    }
535
536    fn is_triggered(&self) -> Option<bool> {
537        Some(self.is_triggered)
538    }
539
540    fn set_position_id(&mut self, position_id: Option<PositionId>) {
541        self.position_id = position_id;
542    }
543
544    fn set_quantity(&mut self, quantity: Quantity) {
545        self.quantity = quantity;
546    }
547
548    fn set_leaves_qty(&mut self, leaves_qty: Quantity) {
549        self.leaves_qty = leaves_qty;
550    }
551
552    fn set_emulation_trigger(&mut self, emulation_trigger: Option<TriggerType>) {
553        self.emulation_trigger = emulation_trigger;
554    }
555
556    fn set_is_quote_quantity(&mut self, is_quote_quantity: bool) {
557        self.is_quote_quantity = is_quote_quantity;
558    }
559
560    fn set_liquidity_side(&mut self, liquidity_side: LiquiditySide) {
561        self.liquidity_side = Some(liquidity_side);
562    }
563
564    fn would_reduce_only(&self, side: PositionSide, position_qty: Quantity) -> bool {
565        self.core.would_reduce_only(side, position_qty)
566    }
567
568    fn previous_status(&self) -> Option<OrderStatus> {
569        self.core.previous_status
570    }
571}
572
573impl Display for TrailingStopMarketOrder {
574    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
575        write!(
576            f,
577            "TrailingStopMarketOrder({} {} {} {} {}, status={}, client_order_id={}, venue_order_id={}, position_id={}, exec_algorithm_id={}, exec_spawn_id={}, tags={:?}, activation_price={:?}, is_activated={})",
578            self.side,
579            self.quantity.to_formatted_string(),
580            self.instrument_id,
581            self.order_type,
582            self.time_in_force,
583            self.status,
584            self.client_order_id,
585            self.venue_order_id
586                .map_or_else(|| "None".to_string(), |id| format!("{id}")),
587            self.position_id
588                .map_or_else(|| "None".to_string(), |id| format!("{id}")),
589            self.exec_algorithm_id
590                .map_or_else(|| "None".to_string(), |id| format!("{id}")),
591            self.exec_spawn_id
592                .map_or_else(|| "None".to_string(), |id| format!("{id}")),
593            self.tags,
594            self.activation_price,
595            self.is_activated
596        )
597    }
598}
599
600impl TryFrom<OrderInitialized> for TrailingStopMarketOrder {
601    type Error = OrderError;
602
603    fn try_from(event: OrderInitialized) -> Result<Self, Self::Error> {
604        let trigger_type =
605            event
606                .trigger_type
607                .ok_or_else(|| CorrectnessError::PredicateViolation {
608                    message:
609                        "`trigger_type` is required for `TrailingStopMarketOrder` initialization"
610                            .to_string(),
611                })?;
612        let trailing_offset =
613            event
614                .trailing_offset
615                .ok_or_else(|| CorrectnessError::PredicateViolation {
616                    message:
617                        "`trailing_offset` is required for `TrailingStopMarketOrder` initialization"
618                            .to_string(),
619                })?;
620        let trailing_offset_type = event.trailing_offset_type.ok_or_else(|| {
621            CorrectnessError::PredicateViolation {
622                message: "`trailing_offset_type` is required for `TrailingStopMarketOrder` initialization"
623                    .to_string(),
624            }
625        })?;
626        Self::new_checked(
627            event.trader_id,
628            event.strategy_id,
629            event.instrument_id,
630            event.client_order_id,
631            event.order_side,
632            event.quantity,
633            event.activation_price,
634            event.trigger_price,
635            trigger_type,
636            trailing_offset,
637            trailing_offset_type,
638            event.time_in_force,
639            event.expire_time,
640            event.reduce_only,
641            event.quote_quantity,
642            event.display_qty,
643            event.emulation_trigger,
644            event.trigger_instrument_id,
645            event.contingency_type,
646            event.order_list_id,
647            event.linked_order_ids,
648            event.parent_order_id,
649            event.exec_algorithm_id,
650            event.exec_algorithm_params,
651            event.exec_spawn_id,
652            event.tags,
653            event.event_id,
654            event.ts_event,
655        )
656    }
657}
658
659#[cfg(test)]
660mod tests {
661    use rstest::rstest;
662    use rust_decimal::Decimal;
663    use rust_decimal_macros::dec;
664
665    use super::*;
666    use crate::{
667        enums::{TimeInForce, TrailingOffsetType, TriggerType},
668        events::order::spec::{OrderFilledSpec, OrderInitializedSpec},
669        identifiers::InstrumentId,
670        instruments::{CurrencyPair, stubs::*},
671        orders::{builder::OrderTestBuilder, stubs::TestOrderStubs},
672        types::{Price, Quantity},
673    };
674
675    #[rstest]
676    fn test_initialize(audusd_sim: CurrencyPair) {
677        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
678            .instrument_id(audusd_sim.id)
679            .side(OrderSide::Buy)
680            .trigger_price(Price::from("0.68000"))
681            .trailing_offset(dec!(10))
682            .trailing_offset_type(TrailingOffsetType::Price)
683            .quantity(Quantity::from(1))
684            .build();
685
686        assert_eq!(order.trigger_price(), Some(Price::from("0.68000")));
687        assert_eq!(order.price(), None);
688
689        assert_eq!(order.time_in_force(), TimeInForce::Gtc);
690
691        assert_eq!(order.is_triggered(), Some(false));
692        assert_eq!(order.filled_qty(), Quantity::from(0));
693        assert_eq!(order.leaves_qty(), Quantity::from(1));
694
695        assert_eq!(order.display_qty(), None);
696        assert_eq!(order.trigger_instrument_id(), None);
697        assert_eq!(order.order_list_id(), None);
698    }
699
700    #[rstest]
701    fn test_display(audusd_sim: CurrencyPair) {
702        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
703            .instrument_id(audusd_sim.id)
704            .side(OrderSide::Buy)
705            .trigger_price(Price::from("0.68000"))
706            .trigger_type(TriggerType::LastPrice)
707            .trailing_offset(dec!(10))
708            .trailing_offset_type(TrailingOffsetType::Price)
709            .quantity(Quantity::from(1))
710            .build();
711
712        assert_eq!(
713            order.to_string(),
714            "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)"
715        );
716    }
717
718    #[rstest]
719    #[should_panic(expected = "Condition failed: `display_qty` may not exceed `quantity`")]
720    fn test_display_qty_gt_quantity_err(audusd_sim: CurrencyPair) {
721        let _ = OrderTestBuilder::new(OrderType::TrailingStopMarket)
722            .instrument_id(audusd_sim.id)
723            .side(OrderSide::Buy)
724            .trigger_price(Price::from("0.68000"))
725            .trigger_type(TriggerType::LastPrice)
726            .trailing_offset(dec!(10))
727            .trailing_offset_type(TrailingOffsetType::Price)
728            .quantity(Quantity::from(1))
729            .display_qty(Quantity::from(2))
730            .build();
731    }
732
733    #[rstest]
734    #[should_panic(
735        expected = "Condition failed: invalid `Quantity` for 'quantity' not positive, was 0"
736    )]
737    fn test_quantity_zero_err(audusd_sim: CurrencyPair) {
738        let _ = OrderTestBuilder::new(OrderType::TrailingStopMarket)
739            .instrument_id(audusd_sim.id)
740            .side(OrderSide::Buy)
741            .trigger_price(Price::from("0.68000"))
742            .trigger_type(TriggerType::LastPrice)
743            .trailing_offset(dec!(10))
744            .trailing_offset_type(TrailingOffsetType::Price)
745            .quantity(Quantity::from(0))
746            .build();
747    }
748
749    #[rstest]
750    #[should_panic(expected = "Condition failed: `expire_time` is required for `GTD` order")]
751    fn test_gtd_without_expire_err(audusd_sim: CurrencyPair) {
752        let _ = OrderTestBuilder::new(OrderType::TrailingStopMarket)
753            .instrument_id(audusd_sim.id)
754            .side(OrderSide::Buy)
755            .trigger_price(Price::from("0.68000"))
756            .trigger_type(TriggerType::LastPrice)
757            .trailing_offset(dec!(10))
758            .trailing_offset_type(TrailingOffsetType::Price)
759            .time_in_force(TimeInForce::Gtd)
760            .quantity(Quantity::from(1))
761            .build();
762    }
763    #[rstest]
764    fn test_trailing_stop_market_order_update() {
765        // Create and accept a basic trailing stop market order
766        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
767            .instrument_id(InstrumentId::from("BTC-USDT.BINANCE"))
768            .quantity(Quantity::from(10))
769            .trigger_price(Price::new(100.0, 2))
770            .trailing_offset(Decimal::new(5, 1)) // 0.5
771            .trailing_offset_type(TrailingOffsetType::Price)
772            .build();
773
774        let mut accepted_order = TestOrderStubs::make_accepted_order(&order);
775
776        // Update with new values
777        let updated_trigger_price = Price::new(95.0, 2);
778        let updated_quantity = Quantity::from(5);
779
780        let event = OrderUpdated {
781            client_order_id: accepted_order.client_order_id(),
782            strategy_id: accepted_order.strategy_id(),
783            trigger_price: Some(updated_trigger_price),
784            quantity: updated_quantity,
785            ..Default::default()
786        };
787
788        accepted_order.apply(OrderEventAny::Updated(event)).unwrap();
789
790        // Verify updates were applied correctly
791        assert_eq!(accepted_order.quantity(), updated_quantity);
792        assert_eq!(accepted_order.trigger_price(), Some(updated_trigger_price));
793    }
794
795    #[rstest]
796    fn test_trailing_stop_market_order_rejects_invalid_update_atomically() {
797        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
798            .instrument_id(InstrumentId::from("BTC-USDT.BINANCE"))
799            .quantity(Quantity::from(10))
800            .trigger_price(Price::new(100.0, 2))
801            .trailing_offset(Decimal::new(5, 1))
802            .trailing_offset_type(TrailingOffsetType::Price)
803            .build();
804        let mut accepted_order = TestOrderStubs::make_accepted_order(&order);
805        let state = (
806            accepted_order.status(),
807            accepted_order.previous_status(),
808            accepted_order.ts_last(),
809            accepted_order.events().len(),
810        );
811        let event = OrderUpdated {
812            client_order_id: accepted_order.client_order_id(),
813            strategy_id: accepted_order.strategy_id(),
814            price: Some(Price::new(95.0, 2)),
815            ..Default::default()
816        };
817
818        let result = accepted_order.apply(OrderEventAny::Updated(event));
819
820        assert!(matches!(result, Err(OrderError::InvalidOrderEvent)));
821        assert_eq!(accepted_order.status(), state.0);
822        assert_eq!(accepted_order.previous_status(), state.1);
823        assert_eq!(accepted_order.ts_last(), state.2);
824        assert_eq!(accepted_order.events().len(), state.3);
825    }
826
827    #[rstest]
828    fn test_trailing_stop_market_order_expire_time() {
829        // Create a new TrailingStopMarketOrder with an expire time
830        let expire_time = UnixNanos::from(1_234_567_890);
831        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
832            .instrument_id(InstrumentId::from("BTC-USDT.BINANCE"))
833            .quantity(Quantity::from(10))
834            .trigger_price(Price::new(100.0, 2))
835            .trailing_offset(Decimal::new(5, 1)) // 0.5
836            .trailing_offset_type(TrailingOffsetType::Price)
837            .expire_time(expire_time)
838            .build();
839
840        // Assert that the expire time is set correctly
841        assert_eq!(order.expire_time(), Some(expire_time));
842    }
843
844    #[rstest]
845    fn test_trailing_stop_market_order_trigger_instrument_id() {
846        // Create a new TrailingStopMarketOrder with a trigger instrument ID
847        let trigger_instrument_id = InstrumentId::from("ETH-USDT.BINANCE");
848        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
849            .instrument_id(InstrumentId::from("BTC-USDT.BINANCE"))
850            .quantity(Quantity::from(10))
851            .trigger_price(Price::new(100.0, 2))
852            .trailing_offset(Decimal::new(5, 1)) // 0.5
853            .trailing_offset_type(TrailingOffsetType::Price)
854            .trigger_instrument_id(trigger_instrument_id)
855            .build();
856
857        // Assert that the trigger instrument ID is set correctly
858        assert_eq!(order.trigger_instrument_id(), Some(trigger_instrument_id));
859    }
860
861    #[rstest]
862    fn test_trailing_stop_market_order_from_order_initialized() {
863        // Create an OrderInitialized event with all required fields for a TrailingStopMarketOrder
864        let order_initialized = OrderInitializedSpec::builder()
865            .trigger_price(Price::new(100.0, 2))
866            .trigger_type(TriggerType::Default)
867            .trailing_offset(Decimal::new(5, 1)) // 0.5
868            .trailing_offset_type(TrailingOffsetType::Price)
869            .order_type(OrderType::TrailingStopMarket)
870            .build();
871
872        // Convert the OrderInitialized event into a TrailingStopMarketOrder
873        let order: TrailingStopMarketOrder = order_initialized.clone().try_into().unwrap();
874
875        // Assert essential fields match the OrderInitialized fields
876        assert_eq!(order.trader_id(), order_initialized.trader_id);
877        assert_eq!(order.strategy_id(), order_initialized.strategy_id);
878        assert_eq!(order.instrument_id(), order_initialized.instrument_id);
879        assert_eq!(order.client_order_id(), order_initialized.client_order_id);
880        assert_eq!(order.order_side(), order_initialized.order_side);
881        assert_eq!(order.quantity(), order_initialized.quantity);
882
883        // Assert specific fields for TrailingStopMarketOrder
884        assert_eq!(order.trigger_price, order_initialized.trigger_price);
885        assert_eq!(order.trigger_type, order_initialized.trigger_type.unwrap());
886        assert_eq!(
887            order.trailing_offset,
888            order_initialized.trailing_offset.unwrap()
889        );
890        assert_eq!(
891            order.trailing_offset_type,
892            order_initialized.trailing_offset_type.unwrap()
893        );
894    }
895
896    #[rstest]
897    fn test_activation_price_round_trips_through_event(audusd_sim: CurrencyPair) {
898        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
899            .instrument_id(audusd_sim.id)
900            .side(OrderSide::Buy)
901            .activation_price(Price::from("0.68500"))
902            .trigger_price(Price::from("0.68000"))
903            .trailing_offset(dec!(10))
904            .trailing_offset_type(TrailingOffsetType::Price)
905            .quantity(Quantity::from(1))
906            .build();
907
908        assert_eq!(order.activation_price(), Some(Price::from("0.68500")));
909
910        // The seed event carries `activation_price`, so a replay preserves it
911        let init = order.init_event().clone();
912        assert_eq!(init.activation_price, Some(Price::from("0.68500")));
913
914        let rebuilt: TrailingStopMarketOrder = init.try_into().unwrap();
915        assert_eq!(rebuilt.activation_price, Some(Price::from("0.68500")));
916        assert_eq!(rebuilt.trigger_price, Some(Price::from("0.68000")));
917    }
918
919    #[rstest]
920    fn test_reconstruct_with_trigger_and_activation_none() {
921        let init = OrderInitializedSpec::builder()
922            .order_type(OrderType::TrailingStopMarket)
923            .trigger_type(TriggerType::Default)
924            .trailing_offset(dec!(10))
925            .trailing_offset_type(TrailingOffsetType::Price)
926            .build();
927
928        let order: TrailingStopMarketOrder = init.try_into().unwrap();
929
930        assert_eq!(order.trigger_price(), None);
931        assert_eq!(order.activation_price(), None);
932    }
933
934    #[rstest]
935    fn test_trailing_stop_market_order_sets_slippage_when_filled() {
936        // Create a trailing stop market order
937        let order = OrderTestBuilder::new(OrderType::TrailingStopMarket)
938            .instrument_id(InstrumentId::from("BTC-USDT.BINANCE"))
939            .quantity(Quantity::from(10))
940            .side(OrderSide::Buy) // Explicitly setting Buy side
941            .trigger_price(Price::new(90.0, 2)) // Trigger price LOWER than fill price
942            .trailing_offset(Decimal::new(5, 1)) // 0.5
943            .trailing_offset_type(TrailingOffsetType::Price)
944            .build();
945
946        // Accept the order first
947        let mut accepted_order = TestOrderStubs::make_accepted_order(&order);
948
949        // Create a filled event with the correct quantity
950        let fill_quantity = accepted_order.quantity(); // Use the same quantity as the order
951        let fill_price = Price::new(98.50, 2); // Use a price HIGHER than trigger price
952
953        let order_filled_event = OrderFilledSpec::builder()
954            .client_order_id(accepted_order.client_order_id())
955            .strategy_id(accepted_order.strategy_id())
956            .instrument_id(accepted_order.instrument_id())
957            .order_side(accepted_order.order_side())
958            .last_qty(fill_quantity)
959            .last_px(fill_price)
960            .venue_order_id(VenueOrderId::from("TEST-001"))
961            .trade_id(TradeId::from("TRADE-001"))
962            .build();
963
964        // Apply the fill event
965        accepted_order
966            .apply(OrderEventAny::Filled(order_filled_event))
967            .unwrap();
968
969        // The fill triggers the slippage calculation: 98.50 - 90.0 for a buy order
970        assert_eq!(accepted_order.slippage(), Some(dec!(8.50)));
971    }
972}