Skip to main content

nautilus_model/orders/
limit_if_touched.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::{
17    fmt::Display,
18    ops::{Deref, DerefMut},
19};
20
21use indexmap::IndexMap;
22use nautilus_core::{
23    UUID4, UnixNanos,
24    correctness::{CorrectnessError, FAILED},
25};
26use rust_decimal::Decimal;
27use serde::{Deserialize, Serialize};
28use ustr::Ustr;
29
30use super::{Order, OrderAny, OrderCore, 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    orders::OrderError,
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 LimitIfTouchedOrder {
55    pub price: Price,
56    pub trigger_price: Price,
57    pub trigger_type: TriggerType,
58    pub expire_time: Option<UnixNanos>,
59    pub is_post_only: bool,
60    pub display_qty: Option<Quantity>,
61    pub trigger_instrument_id: Option<InstrumentId>,
62    pub is_triggered: bool,
63    pub ts_triggered: Option<UnixNanos>,
64    core: OrderCore,
65}
66
67impl LimitIfTouchedOrder {
68    /// Creates a new [`LimitIfTouchedOrder`] instance.
69    ///
70    /// # Errors
71    ///
72    /// Returns an error if:
73    /// - The `quantity` is not positive.
74    /// - The `display_qty` (when provided) exceeds `quantity`.
75    /// - The `time_in_force` is GTD and the `expire_time` is `None` or zero.
76    /// - The order metadata violates an [`OrderInitialized::new_checked`] invariant.
77    #[expect(clippy::too_many_arguments)]
78    pub fn new_checked(
79        trader_id: TraderId,
80        strategy_id: StrategyId,
81        instrument_id: InstrumentId,
82        client_order_id: ClientOrderId,
83        order_side: OrderSide,
84        quantity: Quantity,
85        price: Price,
86        trigger_price: Price,
87        trigger_type: TriggerType,
88        time_in_force: TimeInForce,
89        expire_time: Option<UnixNanos>,
90        post_only: bool,
91        reduce_only: bool,
92        quote_quantity: bool,
93        display_qty: Option<Quantity>,
94        emulation_trigger: Option<TriggerType>,
95        trigger_instrument_id: Option<InstrumentId>,
96        contingency_type: Option<ContingencyType>,
97        order_list_id: Option<OrderListId>,
98        linked_order_ids: Option<Vec<ClientOrderId>>,
99        parent_order_id: Option<ClientOrderId>,
100        exec_algorithm_id: Option<ExecAlgorithmId>,
101        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
102        exec_spawn_id: Option<ClientOrderId>,
103        tags: Option<Vec<Ustr>>,
104        init_id: UUID4,
105        ts_init: UnixNanos,
106    ) -> Result<Self, OrderError> {
107        check_positive_quantity(quantity, stringify!(quantity))?;
108        check_display_qty(display_qty, quantity)?;
109        check_time_in_force(time_in_force, expire_time)?;
110
111        match order_side {
112            OrderSide::Buy if trigger_price > price => {
113                return Err(CorrectnessError::PredicateViolation {
114                    message: "BUY Limit-If-Touched must have `trigger_price` <= `price`"
115                        .to_string(),
116                }
117                .into());
118            }
119            OrderSide::Sell if trigger_price < price => {
120                return Err(CorrectnessError::PredicateViolation {
121                    message: "SELL Limit-If-Touched must have `trigger_price` >= `price`"
122                        .to_string(),
123                }
124                .into());
125            }
126            _ => {}
127        }
128
129        let init_order = OrderInitialized::new_checked(
130            trader_id,
131            strategy_id,
132            instrument_id,
133            client_order_id,
134            order_side,
135            OrderType::LimitIfTouched,
136            quantity,
137            time_in_force,
138            post_only,
139            reduce_only,
140            quote_quantity,
141            false,
142            init_id,
143            ts_init,
144            ts_init,
145            Some(price),
146            None,
147            Some(trigger_price),
148            Some(trigger_type),
149            None,
150            None,
151            None,
152            expire_time,
153            display_qty,
154            emulation_trigger,
155            trigger_instrument_id,
156            contingency_type,
157            order_list_id,
158            linked_order_ids,
159            parent_order_id,
160            exec_algorithm_id,
161            exec_algorithm_params,
162            exec_spawn_id,
163            tags,
164        )?;
165
166        Ok(Self {
167            price,
168            trigger_price,
169            trigger_type,
170            expire_time,
171            is_post_only: post_only,
172            display_qty,
173            trigger_instrument_id,
174            is_triggered: false,
175            ts_triggered: None,
176            core: OrderCore::new(init_order),
177        })
178    }
179
180    /// Creates a new [`LimitIfTouchedOrder`] instance.
181    ///
182    /// # Panics
183    ///
184    /// Panics if any order validation fails (see [`LimitIfTouchedOrder::new_checked`]).
185    #[expect(clippy::too_many_arguments)]
186    #[must_use]
187    pub fn new(
188        trader_id: TraderId,
189        strategy_id: StrategyId,
190        instrument_id: InstrumentId,
191        client_order_id: ClientOrderId,
192        order_side: OrderSide,
193        quantity: Quantity,
194        price: Price,
195        trigger_price: Price,
196        trigger_type: TriggerType,
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            price,
224            trigger_price,
225            trigger_type,
226            time_in_force,
227            expire_time,
228            post_only,
229            reduce_only,
230            quote_quantity,
231            display_qty,
232            emulation_trigger,
233            trigger_instrument_id,
234            contingency_type,
235            order_list_id,
236            linked_order_ids,
237            parent_order_id,
238            exec_algorithm_id,
239            exec_algorithm_params,
240            exec_spawn_id,
241            tags,
242            init_id,
243            ts_init,
244        )
245        .unwrap_or_else(|e| panic!("{FAILED}: {e}"))
246    }
247}
248
249impl PartialEq for LimitIfTouchedOrder {
250    fn eq(&self, other: &Self) -> bool {
251        self.client_order_id == other.client_order_id
252    }
253}
254
255impl Deref for LimitIfTouchedOrder {
256    type Target = OrderCore;
257
258    fn deref(&self) -> &Self::Target {
259        &self.core
260    }
261}
262
263impl DerefMut for LimitIfTouchedOrder {
264    fn deref_mut(&mut self) -> &mut Self::Target {
265        &mut self.core
266    }
267}
268
269impl Order for LimitIfTouchedOrder {
270    fn into_any(self) -> OrderAny {
271        OrderAny::LimitIfTouched(self)
272    }
273
274    fn status(&self) -> OrderStatus {
275        self.status
276    }
277
278    fn trader_id(&self) -> TraderId {
279        self.trader_id
280    }
281
282    fn strategy_id(&self) -> StrategyId {
283        self.strategy_id
284    }
285
286    fn instrument_id(&self) -> InstrumentId {
287        self.instrument_id
288    }
289
290    fn symbol(&self) -> Symbol {
291        self.instrument_id.symbol
292    }
293
294    fn venue(&self) -> Venue {
295        self.instrument_id.venue
296    }
297
298    fn client_order_id(&self) -> ClientOrderId {
299        self.client_order_id
300    }
301
302    fn venue_order_id(&self) -> Option<VenueOrderId> {
303        self.venue_order_id
304    }
305
306    fn position_id(&self) -> Option<PositionId> {
307        self.position_id
308    }
309
310    fn account_id(&self) -> Option<AccountId> {
311        self.account_id
312    }
313
314    fn last_trade_id(&self) -> Option<TradeId> {
315        self.last_trade_id
316    }
317
318    fn order_side(&self) -> OrderSide {
319        self.side
320    }
321
322    fn order_type(&self) -> OrderType {
323        self.order_type
324    }
325
326    fn quantity(&self) -> Quantity {
327        self.quantity
328    }
329
330    fn time_in_force(&self) -> TimeInForce {
331        self.time_in_force
332    }
333
334    fn expire_time(&self) -> Option<UnixNanos> {
335        self.expire_time
336    }
337
338    fn price(&self) -> Option<Price> {
339        Some(self.price)
340    }
341
342    fn trigger_price(&self) -> Option<Price> {
343        Some(self.trigger_price)
344    }
345
346    fn trigger_type(&self) -> Option<TriggerType> {
347        Some(self.trigger_type)
348    }
349
350    fn liquidity_side(&self) -> Option<LiquiditySide> {
351        self.liquidity_side
352    }
353
354    fn is_post_only(&self) -> bool {
355        self.is_post_only
356    }
357
358    fn is_reduce_only(&self) -> bool {
359        self.is_reduce_only
360    }
361
362    fn is_quote_quantity(&self) -> bool {
363        self.is_quote_quantity
364    }
365
366    fn has_price(&self) -> bool {
367        true
368    }
369
370    fn display_qty(&self) -> Option<Quantity> {
371        self.display_qty
372    }
373
374    fn limit_offset(&self) -> Option<Decimal> {
375        None
376    }
377
378    fn trailing_offset(&self) -> Option<Decimal> {
379        None
380    }
381
382    fn trailing_offset_type(&self) -> Option<TrailingOffsetType> {
383        None
384    }
385
386    fn emulation_trigger(&self) -> Option<TriggerType> {
387        self.emulation_trigger
388    }
389
390    fn trigger_instrument_id(&self) -> Option<InstrumentId> {
391        self.trigger_instrument_id
392    }
393
394    fn contingency_type(&self) -> Option<ContingencyType> {
395        self.contingency_type
396    }
397
398    fn order_list_id(&self) -> Option<OrderListId> {
399        self.order_list_id
400    }
401
402    fn linked_order_ids(&self) -> Option<&[ClientOrderId]> {
403        self.linked_order_ids.as_deref()
404    }
405
406    fn parent_order_id(&self) -> Option<ClientOrderId> {
407        self.parent_order_id
408    }
409
410    fn exec_algorithm_id(&self) -> Option<ExecAlgorithmId> {
411        self.exec_algorithm_id
412    }
413
414    fn exec_algorithm_params(&self) -> Option<&IndexMap<Ustr, Ustr>> {
415        self.exec_algorithm_params.as_ref()
416    }
417
418    fn exec_spawn_id(&self) -> Option<ClientOrderId> {
419        self.exec_spawn_id
420    }
421
422    fn tags(&self) -> Option<&[Ustr]> {
423        self.tags.as_deref()
424    }
425
426    fn filled_qty(&self) -> Quantity {
427        self.filled_qty
428    }
429
430    fn voided_qty(&self) -> Quantity {
431        self.voided_qty
432    }
433
434    fn non_reopened_voided_qty(&self) -> Quantity {
435        self.non_reopened_voided_qty
436    }
437
438    fn leaves_qty(&self) -> Quantity {
439        self.leaves_qty
440    }
441
442    fn overfill_qty(&self) -> Quantity {
443        self.overfill_qty
444    }
445
446    fn avg_px(&self) -> Option<Decimal> {
447        self.avg_px
448    }
449
450    fn slippage(&self) -> Option<Decimal> {
451        self.slippage
452    }
453
454    fn init_id(&self) -> UUID4 {
455        self.init_id
456    }
457
458    fn ts_init(&self) -> UnixNanos {
459        self.ts_init
460    }
461
462    fn ts_submitted(&self) -> Option<UnixNanos> {
463        self.ts_submitted
464    }
465
466    fn ts_accepted(&self) -> Option<UnixNanos> {
467        self.ts_accepted
468    }
469
470    fn ts_closed(&self) -> Option<UnixNanos> {
471        self.ts_closed
472    }
473
474    fn ts_last(&self) -> UnixNanos {
475        self.ts_last
476    }
477
478    fn commissions(&self) -> &IndexMap<Currency, Money> {
479        &self.commissions
480    }
481
482    fn events(&self) -> Vec<&OrderEventAny> {
483        self.events.iter().collect()
484    }
485
486    fn last_event(&self) -> &OrderEventAny {
487        self.events
488            .last()
489            .expect("Order invariant violated: no events")
490    }
491
492    fn venue_order_ids(&self) -> Vec<&VenueOrderId> {
493        self.venue_order_ids.iter().collect()
494    }
495
496    fn trade_ids(&self) -> Vec<&TradeId> {
497        self.trade_ids.iter().collect()
498    }
499
500    fn apply(&mut self, event: OrderEventAny) -> Result<(), OrderError> {
501        let updates_slippage = matches!(
502            event,
503            OrderEventAny::Filled(_) | OrderEventAny::FillVoided(_),
504        );
505        let is_order_triggered = matches!(event, OrderEventAny::Triggered(_));
506        let ts_event = if is_order_triggered {
507            Some(event.ts_event())
508        } else {
509            None
510        };
511
512        self.core.apply(event.clone())?;
513
514        if let OrderEventAny::Updated(ref event) = event {
515            self.update(event);
516        }
517
518        if is_order_triggered {
519            self.is_triggered = true;
520            self.ts_triggered = ts_event;
521        }
522
523        if updates_slippage {
524            self.core.set_slippage(self.price);
525        }
526
527        Ok(())
528    }
529
530    fn update(&mut self, event: &OrderUpdated) {
531        if let Some(price) = event.price {
532            self.price = price;
533        }
534
535        if let Some(trigger_price) = event.trigger_price {
536            self.trigger_price = 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 LimitIfTouchedOrder {
580    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
581        write!(
582            f,
583            "LimitIfTouchedOrder({} {} {} @ {} / trigger {} ({:?}) {}, status={})",
584            self.side,
585            self.quantity.to_formatted_string(),
586            self.instrument_id,
587            self.price,
588            self.trigger_price,
589            self.trigger_type,
590            self.time_in_force,
591            self.status
592        )
593    }
594}
595
596impl TryFrom<OrderInitialized> for LimitIfTouchedOrder {
597    type Error = OrderError;
598
599    fn try_from(event: OrderInitialized) -> Result<Self, Self::Error> {
600        let price = event
601            .price
602            .ok_or_else(|| CorrectnessError::PredicateViolation {
603                message: "`price` is required for `LimitIfTouchedOrder` initialization".to_string(),
604            })?;
605        let trigger_price =
606            event
607                .trigger_price
608                .ok_or_else(|| CorrectnessError::PredicateViolation {
609                    message: "`trigger_price` is required for `LimitIfTouchedOrder` initialization"
610                        .to_string(),
611                })?;
612        let trigger_type =
613            event
614                .trigger_type
615                .ok_or_else(|| CorrectnessError::PredicateViolation {
616                    message: "`trigger_type` is required for `LimitIfTouchedOrder` initialization"
617                        .to_string(),
618                })?;
619        Self::new_checked(
620            event.trader_id,
621            event.strategy_id,
622            event.instrument_id,
623            event.client_order_id,
624            event.order_side,
625            event.quantity,
626            price,
627            trigger_price,
628            trigger_type,
629            event.time_in_force,
630            event.expire_time,
631            event.post_only,
632            event.reduce_only,
633            event.quote_quantity,
634            event.display_qty,
635            event.emulation_trigger,
636            event.trigger_instrument_id,
637            event.contingency_type,
638            event.order_list_id,
639            event.linked_order_ids,
640            event.parent_order_id,
641            event.exec_algorithm_id,
642            event.exec_algorithm_params,
643            event.exec_spawn_id,
644            event.tags,
645            event.event_id,
646            event.ts_event,
647        )
648    }
649}
650
651#[cfg(test)]
652mod tests {
653    use rstest::rstest;
654    use rust_decimal_macros::dec;
655
656    use super::*;
657    use crate::{
658        enums::{TimeInForce, TriggerType},
659        events::order::spec::{OrderFilledSpec, OrderInitializedSpec},
660        identifiers::InstrumentId,
661        instruments::{CurrencyPair, stubs::*},
662        orders::{builder::OrderTestBuilder, stubs::TestOrderStubs},
663        types::{Price, Quantity},
664    };
665
666    #[rstest]
667    fn test_initialize(audusd_sim: CurrencyPair) {
668        let order = OrderTestBuilder::new(OrderType::LimitIfTouched)
669            .instrument_id(audusd_sim.id)
670            .side(OrderSide::Buy)
671            .price(Price::from("0.68000"))
672            .trigger_price(Price::from("0.68000"))
673            .trigger_type(TriggerType::LastPrice)
674            .quantity(Quantity::from(1))
675            .build();
676
677        assert_eq!(order.trigger_price(), Some(Price::from("0.68000")));
678        assert_eq!(order.price(), Some(Price::from("0.68000")));
679
680        assert_eq!(order.time_in_force(), TimeInForce::Gtc);
681
682        assert_eq!(order.is_triggered(), Some(false));
683        assert_eq!(order.filled_qty(), Quantity::from(0));
684        assert_eq!(order.leaves_qty(), Quantity::from(1));
685
686        assert_eq!(order.display_qty(), None);
687        assert_eq!(order.trigger_instrument_id(), None);
688        assert_eq!(order.order_list_id(), None);
689    }
690
691    #[rstest]
692    fn test_display(audusd_sim: CurrencyPair) {
693        let order = OrderTestBuilder::new(OrderType::LimitIfTouched)
694            .instrument_id(audusd_sim.id)
695            .side(OrderSide::Buy)
696            .trigger_price(Price::from("30200"))
697            .price(Price::from("30200"))
698            .trigger_type(TriggerType::LastPrice)
699            .quantity(Quantity::from(1))
700            .build();
701
702        assert_eq!(
703            order.to_string(),
704            "LimitIfTouchedOrder(BUY 1 AUD/USD.SIM @ 30200 / trigger 30200 (LastPrice) GTC, status=INITIALIZED)"
705        );
706    }
707
708    #[rstest]
709    #[should_panic(
710        expected = "Condition failed: invalid `Quantity` for 'quantity' not positive, was 0"
711    )]
712    fn test_quantity_zero(audusd_sim: CurrencyPair) {
713        let _ = OrderTestBuilder::new(OrderType::LimitIfTouched)
714            .instrument_id(audusd_sim.id)
715            .side(OrderSide::Buy)
716            .price(Price::from("30000"))
717            .trigger_price(Price::from("30200"))
718            .trigger_type(TriggerType::LastPrice)
719            .quantity(Quantity::from(0))
720            .build();
721    }
722
723    #[rstest]
724    #[should_panic(expected = "Condition failed: `expire_time` is required for `GTD` order")]
725    fn test_gtd_without_expire(audusd_sim: CurrencyPair) {
726        let _ = OrderTestBuilder::new(OrderType::LimitIfTouched)
727            .instrument_id(audusd_sim.id)
728            .side(OrderSide::Buy)
729            .price(Price::from("30000"))
730            .trigger_price(Price::from("30200"))
731            .trigger_type(TriggerType::LastPrice)
732            .quantity(Quantity::from(1))
733            .time_in_force(TimeInForce::Gtd)
734            .build();
735    }
736
737    #[rstest]
738    #[should_panic(expected = "BUY Limit-If-Touched must have `trigger_price` <= `price`")]
739    fn test_buy_trigger_gt_price(audusd_sim: CurrencyPair) {
740        let _ = OrderTestBuilder::new(OrderType::LimitIfTouched)
741            .instrument_id(audusd_sim.id)
742            .side(OrderSide::Buy)
743            .trigger_price(Price::from("30300")) // Invalid trigger > price
744            .price(Price::from("30200"))
745            .trigger_type(TriggerType::LastPrice)
746            .quantity(Quantity::from(1))
747            .build();
748    }
749
750    #[rstest]
751    #[should_panic(expected = "SELL Limit-If-Touched must have `trigger_price` >= `price`")]
752    fn test_sell_trigger_lt_price(audusd_sim: CurrencyPair) {
753        let _ = OrderTestBuilder::new(OrderType::LimitIfTouched)
754            .instrument_id(audusd_sim.id)
755            .side(OrderSide::Sell)
756            .trigger_price(Price::from("30100")) // Invalid trigger < price
757            .price(Price::from("30200"))
758            .trigger_type(TriggerType::LastPrice)
759            .quantity(Quantity::from(1))
760            .build();
761    }
762
763    #[rstest]
764    fn test_limit_if_touched_order_update() {
765        // Create and accept a basic limit-if-touched order
766        let order = OrderTestBuilder::new(OrderType::LimitIfTouched)
767            .instrument_id(InstrumentId::from("BTC-USDT.BINANCE"))
768            .quantity(Quantity::from(10))
769            .price(Price::new(100.0, 2))
770            .trigger_price(Price::new(95.0, 2))
771            .trigger_type(TriggerType::Default)
772            .build();
773
774        let mut accepted_order = TestOrderStubs::make_accepted_order(&order);
775
776        // Update with new values
777        let updated_price = Price::new(105.0, 2);
778        let updated_trigger_price = Price::new(97.0, 2);
779        let updated_quantity = Quantity::from(5);
780
781        let event = OrderUpdated {
782            client_order_id: accepted_order.client_order_id(),
783            strategy_id: accepted_order.strategy_id(),
784            price: Some(updated_price),
785            trigger_price: Some(updated_trigger_price),
786            quantity: updated_quantity,
787            ..Default::default()
788        };
789
790        accepted_order.apply(OrderEventAny::Updated(event)).unwrap();
791
792        // Verify updates were applied correctly
793        assert_eq!(accepted_order.price(), Some(updated_price));
794        assert_eq!(accepted_order.trigger_price(), Some(updated_trigger_price));
795        assert_eq!(accepted_order.quantity(), updated_quantity);
796    }
797
798    #[rstest]
799    fn test_limit_if_touched_order_from_order_initialized() {
800        // Create an OrderInitialized event with all required fields for a LimitIfTouchedOrder
801        let order_initialized = OrderInitializedSpec::builder()
802            .price(Price::new(100.0, 2))
803            .trigger_price(Price::new(95.0, 2))
804            .trigger_type(TriggerType::Default)
805            .order_type(OrderType::LimitIfTouched)
806            .build();
807
808        // Convert the OrderInitialized event into a LimitIfTouchedOrder
809        let order: LimitIfTouchedOrder = order_initialized.clone().try_into().unwrap();
810
811        // Assert essential fields match the OrderInitialized fields
812        assert_eq!(order.trader_id(), order_initialized.trader_id);
813        assert_eq!(order.strategy_id(), order_initialized.strategy_id);
814        assert_eq!(order.instrument_id(), order_initialized.instrument_id);
815        assert_eq!(order.client_order_id(), order_initialized.client_order_id);
816        assert_eq!(order.order_side(), order_initialized.order_side);
817        assert_eq!(order.quantity(), order_initialized.quantity);
818
819        // Assert specific fields for LimitIfTouchedOrder
820        assert_eq!(order.price, order_initialized.price.unwrap());
821        assert_eq!(
822            order.trigger_price,
823            order_initialized.trigger_price.unwrap()
824        );
825        assert_eq!(order.trigger_type, order_initialized.trigger_type.unwrap());
826    }
827
828    #[rstest]
829    fn test_limit_if_touched_order_sets_slippage_when_filled() {
830        // Create a limit-if-touched order
831        let order = OrderTestBuilder::new(OrderType::LimitIfTouched)
832            .instrument_id(InstrumentId::from("BTC-USDT.BINANCE"))
833            .quantity(Quantity::from(10))
834            .side(OrderSide::Buy) // Explicitly setting Buy side
835            .price(Price::new(95.0, 2)) // Limit price
836            .trigger_price(Price::new(90.0, 2)) // Trigger price LOWER than fill price
837            .trigger_type(TriggerType::Default)
838            .build();
839
840        // Accept the order first
841        let mut accepted_order = TestOrderStubs::make_accepted_order(&order);
842
843        // Create a filled event with the correct quantity
844        let fill_quantity = accepted_order.quantity(); // Use the same quantity as the order
845        let fill_price = Price::new(98.50, 2); // Use a price LOWER than limit price
846
847        let order_filled_event = OrderFilledSpec::builder()
848            .client_order_id(accepted_order.client_order_id())
849            .strategy_id(accepted_order.strategy_id())
850            .instrument_id(accepted_order.instrument_id())
851            .order_side(accepted_order.order_side())
852            .last_qty(fill_quantity)
853            .last_px(fill_price)
854            .venue_order_id(VenueOrderId::from("TEST-001"))
855            .trade_id(TradeId::from("TRADE-001"))
856            .build();
857
858        // Apply the fill event
859        accepted_order
860            .apply(OrderEventAny::Filled(order_filled_event))
861            .unwrap();
862
863        // The fill triggers the slippage calculation: 98.50 - 95.0 for a buy order
864        assert_eq!(accepted_order.slippage(), Some(dec!(3.50)));
865    }
866}