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 venue_order_ids(&self) -> Vec<&VenueOrderId> {
487        self.venue_order_ids.iter().collect()
488    }
489
490    fn trade_ids(&self) -> Vec<&TradeId> {
491        self.trade_ids.iter().collect()
492    }
493
494    fn apply(&mut self, event: OrderEventAny) -> Result<(), OrderError> {
495        let updates_slippage = matches!(
496            event,
497            OrderEventAny::Filled(_) | OrderEventAny::FillVoided(_),
498        );
499        let is_order_triggered = matches!(event, OrderEventAny::Triggered(_));
500        let ts_event = if is_order_triggered {
501            Some(event.ts_event())
502        } else {
503            None
504        };
505
506        self.core.apply(event.clone())?;
507
508        if let OrderEventAny::Updated(ref event) = event {
509            self.update(event);
510        }
511
512        if is_order_triggered {
513            self.is_triggered = true;
514            self.ts_triggered = ts_event;
515        }
516
517        if updates_slippage {
518            self.core.set_slippage(self.price);
519        }
520
521        Ok(())
522    }
523
524    fn update(&mut self, event: &OrderUpdated) {
525        if let Some(price) = event.price {
526            self.price = price;
527        }
528
529        if let Some(trigger_price) = event.trigger_price {
530            self.trigger_price = trigger_price;
531        }
532
533        self.core.apply_updated_quantity(event.quantity);
534    }
535
536    fn is_triggered(&self) -> Option<bool> {
537        Some(self.is_triggered)
538    }
539
540    fn set_position_id(&mut self, position_id: Option<PositionId>) {
541        self.position_id = position_id;
542    }
543
544    fn set_quantity(&mut self, quantity: Quantity) {
545        self.quantity = quantity;
546    }
547
548    fn set_leaves_qty(&mut self, leaves_qty: Quantity) {
549        self.leaves_qty = leaves_qty;
550    }
551
552    fn set_emulation_trigger(&mut self, emulation_trigger: Option<TriggerType>) {
553        self.emulation_trigger = emulation_trigger;
554    }
555
556    fn set_is_quote_quantity(&mut self, is_quote_quantity: bool) {
557        self.is_quote_quantity = is_quote_quantity;
558    }
559
560    fn set_liquidity_side(&mut self, liquidity_side: LiquiditySide) {
561        self.liquidity_side = Some(liquidity_side);
562    }
563
564    fn would_reduce_only(&self, side: PositionSide, position_qty: Quantity) -> bool {
565        self.core.would_reduce_only(side, position_qty)
566    }
567
568    fn previous_status(&self) -> Option<OrderStatus> {
569        self.core.previous_status
570    }
571}
572
573impl Display for LimitIfTouchedOrder {
574    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
575        write!(
576            f,
577            "LimitIfTouchedOrder({} {} {} @ {} / trigger {} ({:?}) {}, status={})",
578            self.side,
579            self.quantity.to_formatted_string(),
580            self.instrument_id,
581            self.price,
582            self.trigger_price,
583            self.trigger_type,
584            self.time_in_force,
585            self.status
586        )
587    }
588}
589
590impl TryFrom<OrderInitialized> for LimitIfTouchedOrder {
591    type Error = OrderError;
592
593    fn try_from(event: OrderInitialized) -> Result<Self, Self::Error> {
594        let price = event
595            .price
596            .ok_or_else(|| CorrectnessError::PredicateViolation {
597                message: "`price` is required for `LimitIfTouchedOrder` initialization".to_string(),
598            })?;
599        let trigger_price =
600            event
601                .trigger_price
602                .ok_or_else(|| CorrectnessError::PredicateViolation {
603                    message: "`trigger_price` is required for `LimitIfTouchedOrder` initialization"
604                        .to_string(),
605                })?;
606        let trigger_type =
607            event
608                .trigger_type
609                .ok_or_else(|| CorrectnessError::PredicateViolation {
610                    message: "`trigger_type` is required for `LimitIfTouchedOrder` initialization"
611                        .to_string(),
612                })?;
613        Self::new_checked(
614            event.trader_id,
615            event.strategy_id,
616            event.instrument_id,
617            event.client_order_id,
618            event.order_side,
619            event.quantity,
620            price,
621            trigger_price,
622            trigger_type,
623            event.time_in_force,
624            event.expire_time,
625            event.post_only,
626            event.reduce_only,
627            event.quote_quantity,
628            event.display_qty,
629            event.emulation_trigger,
630            event.trigger_instrument_id,
631            event.contingency_type,
632            event.order_list_id,
633            event.linked_order_ids,
634            event.parent_order_id,
635            event.exec_algorithm_id,
636            event.exec_algorithm_params,
637            event.exec_spawn_id,
638            event.tags,
639            event.event_id,
640            event.ts_event,
641        )
642    }
643}
644
645#[cfg(test)]
646mod tests {
647    use rstest::rstest;
648    use rust_decimal_macros::dec;
649
650    use super::*;
651    use crate::{
652        enums::{TimeInForce, TriggerType},
653        events::order::spec::{OrderFilledSpec, OrderInitializedSpec},
654        identifiers::InstrumentId,
655        instruments::{CurrencyPair, stubs::*},
656        orders::{builder::OrderTestBuilder, stubs::TestOrderStubs},
657        types::{Price, Quantity},
658    };
659
660    #[rstest]
661    fn test_initialize(audusd_sim: CurrencyPair) {
662        let order = OrderTestBuilder::new(OrderType::LimitIfTouched)
663            .instrument_id(audusd_sim.id)
664            .side(OrderSide::Buy)
665            .price(Price::from("0.68000"))
666            .trigger_price(Price::from("0.68000"))
667            .trigger_type(TriggerType::LastPrice)
668            .quantity(Quantity::from(1))
669            .build();
670
671        assert_eq!(order.trigger_price(), Some(Price::from("0.68000")));
672        assert_eq!(order.price(), Some(Price::from("0.68000")));
673
674        assert_eq!(order.time_in_force(), TimeInForce::Gtc);
675
676        assert_eq!(order.is_triggered(), Some(false));
677        assert_eq!(order.filled_qty(), Quantity::from(0));
678        assert_eq!(order.leaves_qty(), Quantity::from(1));
679
680        assert_eq!(order.display_qty(), None);
681        assert_eq!(order.trigger_instrument_id(), None);
682        assert_eq!(order.order_list_id(), None);
683    }
684
685    #[rstest]
686    fn test_display(audusd_sim: CurrencyPair) {
687        let order = OrderTestBuilder::new(OrderType::LimitIfTouched)
688            .instrument_id(audusd_sim.id)
689            .side(OrderSide::Buy)
690            .trigger_price(Price::from("30200"))
691            .price(Price::from("30200"))
692            .trigger_type(TriggerType::LastPrice)
693            .quantity(Quantity::from(1))
694            .build();
695
696        assert_eq!(
697            order.to_string(),
698            "LimitIfTouchedOrder(BUY 1 AUD/USD.SIM @ 30200 / trigger 30200 (LastPrice) GTC, status=INITIALIZED)"
699        );
700    }
701
702    #[rstest]
703    #[should_panic(
704        expected = "Condition failed: invalid `Quantity` for 'quantity' not positive, was 0"
705    )]
706    fn test_quantity_zero(audusd_sim: CurrencyPair) {
707        let _ = OrderTestBuilder::new(OrderType::LimitIfTouched)
708            .instrument_id(audusd_sim.id)
709            .side(OrderSide::Buy)
710            .price(Price::from("30000"))
711            .trigger_price(Price::from("30200"))
712            .trigger_type(TriggerType::LastPrice)
713            .quantity(Quantity::from(0))
714            .build();
715    }
716
717    #[rstest]
718    #[should_panic(expected = "Condition failed: `expire_time` is required for `GTD` order")]
719    fn test_gtd_without_expire(audusd_sim: CurrencyPair) {
720        let _ = OrderTestBuilder::new(OrderType::LimitIfTouched)
721            .instrument_id(audusd_sim.id)
722            .side(OrderSide::Buy)
723            .price(Price::from("30000"))
724            .trigger_price(Price::from("30200"))
725            .trigger_type(TriggerType::LastPrice)
726            .quantity(Quantity::from(1))
727            .time_in_force(TimeInForce::Gtd)
728            .build();
729    }
730
731    #[rstest]
732    #[should_panic(expected = "BUY Limit-If-Touched must have `trigger_price` <= `price`")]
733    fn test_buy_trigger_gt_price(audusd_sim: CurrencyPair) {
734        let _ = OrderTestBuilder::new(OrderType::LimitIfTouched)
735            .instrument_id(audusd_sim.id)
736            .side(OrderSide::Buy)
737            .trigger_price(Price::from("30300")) // Invalid trigger > price
738            .price(Price::from("30200"))
739            .trigger_type(TriggerType::LastPrice)
740            .quantity(Quantity::from(1))
741            .build();
742    }
743
744    #[rstest]
745    #[should_panic(expected = "SELL Limit-If-Touched must have `trigger_price` >= `price`")]
746    fn test_sell_trigger_lt_price(audusd_sim: CurrencyPair) {
747        let _ = OrderTestBuilder::new(OrderType::LimitIfTouched)
748            .instrument_id(audusd_sim.id)
749            .side(OrderSide::Sell)
750            .trigger_price(Price::from("30100")) // Invalid trigger < price
751            .price(Price::from("30200"))
752            .trigger_type(TriggerType::LastPrice)
753            .quantity(Quantity::from(1))
754            .build();
755    }
756
757    #[rstest]
758    fn test_limit_if_touched_order_update() {
759        // Create and accept a basic limit-if-touched order
760        let order = OrderTestBuilder::new(OrderType::LimitIfTouched)
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            .trigger_type(TriggerType::Default)
766            .build();
767
768        let mut accepted_order = TestOrderStubs::make_accepted_order(&order);
769
770        // Update with new values
771        let updated_price = Price::new(105.0, 2);
772        let updated_trigger_price = Price::new(97.0, 2);
773        let updated_quantity = Quantity::from(5);
774
775        let event = OrderUpdated {
776            client_order_id: accepted_order.client_order_id(),
777            strategy_id: accepted_order.strategy_id(),
778            price: Some(updated_price),
779            trigger_price: Some(updated_trigger_price),
780            quantity: updated_quantity,
781            ..Default::default()
782        };
783
784        accepted_order.apply(OrderEventAny::Updated(event)).unwrap();
785
786        // Verify updates were applied correctly
787        assert_eq!(accepted_order.price(), Some(updated_price));
788        assert_eq!(accepted_order.trigger_price(), Some(updated_trigger_price));
789        assert_eq!(accepted_order.quantity(), updated_quantity);
790    }
791
792    #[rstest]
793    fn test_limit_if_touched_order_from_order_initialized() {
794        // Create an OrderInitialized event with all required fields for a LimitIfTouchedOrder
795        let order_initialized = OrderInitializedSpec::builder()
796            .price(Price::new(100.0, 2))
797            .trigger_price(Price::new(95.0, 2))
798            .trigger_type(TriggerType::Default)
799            .order_type(OrderType::LimitIfTouched)
800            .build();
801
802        // Convert the OrderInitialized event into a LimitIfTouchedOrder
803        let order: LimitIfTouchedOrder = order_initialized.clone().try_into().unwrap();
804
805        // Assert essential fields match the OrderInitialized fields
806        assert_eq!(order.trader_id(), order_initialized.trader_id);
807        assert_eq!(order.strategy_id(), order_initialized.strategy_id);
808        assert_eq!(order.instrument_id(), order_initialized.instrument_id);
809        assert_eq!(order.client_order_id(), order_initialized.client_order_id);
810        assert_eq!(order.order_side(), order_initialized.order_side);
811        assert_eq!(order.quantity(), order_initialized.quantity);
812
813        // Assert specific fields for LimitIfTouchedOrder
814        assert_eq!(order.price, order_initialized.price.unwrap());
815        assert_eq!(
816            order.trigger_price,
817            order_initialized.trigger_price.unwrap()
818        );
819        assert_eq!(order.trigger_type, order_initialized.trigger_type.unwrap());
820    }
821
822    #[rstest]
823    fn test_limit_if_touched_order_sets_slippage_when_filled() {
824        // Create a limit-if-touched order
825        let order = OrderTestBuilder::new(OrderType::LimitIfTouched)
826            .instrument_id(InstrumentId::from("BTC-USDT.BINANCE"))
827            .quantity(Quantity::from(10))
828            .side(OrderSide::Buy) // Explicitly setting Buy side
829            .price(Price::new(95.0, 2)) // Limit price
830            .trigger_price(Price::new(90.0, 2)) // Trigger price LOWER than fill price
831            .trigger_type(TriggerType::Default)
832            .build();
833
834        // Accept the order first
835        let mut accepted_order = TestOrderStubs::make_accepted_order(&order);
836
837        // Create a filled event with the correct quantity
838        let fill_quantity = accepted_order.quantity(); // Use the same quantity as the order
839        let fill_price = Price::new(98.50, 2); // Use a price LOWER than limit price
840
841        let order_filled_event = OrderFilledSpec::builder()
842            .client_order_id(accepted_order.client_order_id())
843            .strategy_id(accepted_order.strategy_id())
844            .instrument_id(accepted_order.instrument_id())
845            .order_side(accepted_order.order_side())
846            .last_qty(fill_quantity)
847            .last_px(fill_price)
848            .venue_order_id(VenueOrderId::from("TEST-001"))
849            .trade_id(TradeId::from("TRADE-001"))
850            .build();
851
852        // Apply the fill event
853        accepted_order
854            .apply(OrderEventAny::Filled(order_filled_event))
855            .unwrap();
856
857        // The fill triggers the slippage calculation: 98.50 - 95.0 for a buy order
858        assert_eq!(accepted_order.slippage(), Some(dec!(3.50)));
859    }
860}