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