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