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