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