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