Skip to main content

nautilus_common/factories/
order.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
16//! Factory for constructing order objects.
17
18use std::{cell::RefCell, rc::Rc};
19
20use indexmap::IndexMap;
21use nautilus_core::{UUID4, UnixNanos};
22use nautilus_model::{
23    enums::{ContingencyType, OrderSide, OrderType, TimeInForce, TrailingOffsetType, TriggerType},
24    identifiers::{
25        ClientOrderId, ExecAlgorithmId, InstrumentId, OrderListId, StrategyId, TraderId,
26    },
27    orders::{
28        LimitIfTouchedOrder, LimitOrder, MarketIfTouchedOrder, MarketOrder, MarketToLimitOrder,
29        Order, OrderAny, OrderList, StopLimitOrder, StopMarketOrder, TrailingStopLimitOrder,
30        TrailingStopMarketOrder,
31    },
32    types::{Price, Quantity},
33};
34use rust_decimal::Decimal;
35use ustr::Ustr;
36
37use crate::{
38    clock::Clock,
39    generators::{client_order_id::ClientOrderIdGenerator, order_list_id::OrderListIdGenerator},
40};
41
42#[derive(Debug)]
43pub struct OrderFactory {
44    clock: Rc<RefCell<dyn Clock>>,
45    trader_id: TraderId,
46    strategy_id: StrategyId,
47    order_id_generator: ClientOrderIdGenerator,
48    order_list_id_generator: OrderListIdGenerator,
49}
50
51#[bon::bon]
52impl OrderFactory {
53    /// Creates a new [`OrderFactory`] instance.
54    pub fn new(
55        trader_id: TraderId,
56        strategy_id: StrategyId,
57        init_order_id_count: Option<usize>,
58        init_order_list_id_count: Option<usize>,
59        clock: Rc<RefCell<dyn Clock>>,
60        use_uuids_for_client_order_ids: bool,
61        use_hyphens_in_client_order_ids: bool,
62    ) -> Self {
63        let order_id_generator = ClientOrderIdGenerator::new(
64            trader_id,
65            strategy_id,
66            init_order_id_count.unwrap_or(0),
67            clock.clone(),
68            use_uuids_for_client_order_ids,
69            use_hyphens_in_client_order_ids,
70        );
71
72        let order_list_id_generator = OrderListIdGenerator::new(
73            trader_id,
74            strategy_id,
75            init_order_list_id_count.unwrap_or(0),
76            clock.clone(),
77        );
78
79        Self {
80            clock,
81            trader_id,
82            strategy_id,
83            order_id_generator,
84            order_list_id_generator,
85        }
86    }
87
88    /// Returns the trader ID.
89    #[must_use]
90    pub const fn trader_id(&self) -> TraderId {
91        self.trader_id
92    }
93
94    /// Returns the strategy ID.
95    #[must_use]
96    pub const fn strategy_id(&self) -> StrategyId {
97        self.strategy_id
98    }
99
100    /// Sets the client order ID generator count.
101    pub const fn set_client_order_id_count(&mut self, count: usize) {
102        self.order_id_generator.set_count(count);
103    }
104
105    /// Returns the client order ID generator count.
106    #[must_use]
107    pub const fn client_order_id_count(&self) -> usize {
108        self.order_id_generator.count()
109    }
110
111    /// Sets the order list ID generator count.
112    pub const fn set_order_list_id_count(&mut self, count: usize) {
113        self.order_list_id_generator.set_count(count);
114    }
115
116    /// Returns the order list ID generator count.
117    #[must_use]
118    pub const fn order_list_id_count(&self) -> usize {
119        self.order_list_id_generator.count()
120    }
121
122    /// Generates a new client order ID.
123    pub fn generate_client_order_id(&mut self) -> ClientOrderId {
124        self.order_id_generator.generate()
125    }
126
127    /// Generates a new order list ID.
128    pub fn generate_order_list_id(&mut self) -> OrderListId {
129        self.order_list_id_generator.generate()
130    }
131
132    /// Resets the factory by resetting all ID generators.
133    pub const fn reset_factory(&mut self) {
134        self.order_id_generator.reset();
135        self.order_list_id_generator.reset();
136    }
137
138    /// Creates a new market order.
139    ///
140    /// # Panics
141    ///
142    /// Panics if the order parameters fail validation.
143    #[expect(clippy::too_many_arguments)]
144    pub fn market(
145        &mut self,
146        instrument_id: InstrumentId,
147        order_side: OrderSide,
148        quantity: Quantity,
149        time_in_force: Option<TimeInForce>,
150        reduce_only: Option<bool>,
151        quote_quantity: Option<bool>,
152        exec_algorithm_id: Option<ExecAlgorithmId>,
153        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
154        tags: Option<Vec<Ustr>>,
155        client_order_id: Option<ClientOrderId>,
156    ) -> OrderAny {
157        self.try_market(
158            instrument_id,
159            order_side,
160            quantity,
161            time_in_force,
162            reduce_only,
163            quote_quantity,
164            exec_algorithm_id,
165            exec_algorithm_params,
166            tags,
167            client_order_id,
168        )
169        .unwrap_or_else(|e| panic!("{e}"))
170    }
171
172    #[expect(clippy::too_many_arguments)]
173    pub(crate) fn try_market(
174        &mut self,
175        instrument_id: InstrumentId,
176        order_side: OrderSide,
177        quantity: Quantity,
178        time_in_force: Option<TimeInForce>,
179        reduce_only: Option<bool>,
180        quote_quantity: Option<bool>,
181        exec_algorithm_id: Option<ExecAlgorithmId>,
182        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
183        tags: Option<Vec<Ustr>>,
184        client_order_id: Option<ClientOrderId>,
185    ) -> anyhow::Result<OrderAny> {
186        let client_order_id = client_order_id.unwrap_or_else(|| self.generate_client_order_id());
187        let exec_spawn_id: Option<ClientOrderId> = if exec_algorithm_id.is_none() {
188            None
189        } else {
190            Some(client_order_id)
191        };
192        let order = MarketOrder::new_checked(
193            self.trader_id,
194            self.strategy_id,
195            instrument_id,
196            client_order_id,
197            order_side,
198            quantity,
199            time_in_force.unwrap_or(TimeInForce::Gtc),
200            UUID4::new(),
201            self.clock.borrow().timestamp_ns(),
202            reduce_only.unwrap_or(false),
203            quote_quantity.unwrap_or(false),
204            None,
205            None,
206            None,
207            None,
208            exec_algorithm_id,
209            exec_algorithm_params,
210            exec_spawn_id,
211            tags,
212        )?;
213        Ok(OrderAny::Market(order))
214    }
215
216    /// Creates a new limit order.
217    ///
218    /// # Panics
219    ///
220    /// Panics if the order parameters fail validation.
221    #[expect(clippy::too_many_arguments)]
222    pub fn limit(
223        &mut self,
224        instrument_id: InstrumentId,
225        order_side: OrderSide,
226        quantity: Quantity,
227        price: Price,
228        time_in_force: Option<TimeInForce>,
229        expire_time: Option<nautilus_core::UnixNanos>,
230        post_only: Option<bool>,
231        reduce_only: Option<bool>,
232        quote_quantity: Option<bool>,
233        display_qty: Option<Quantity>,
234        emulation_trigger: Option<TriggerType>,
235        trigger_instrument_id: Option<InstrumentId>,
236        exec_algorithm_id: Option<ExecAlgorithmId>,
237        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
238        tags: Option<Vec<Ustr>>,
239        client_order_id: Option<ClientOrderId>,
240    ) -> OrderAny {
241        self.try_limit(
242            instrument_id,
243            order_side,
244            quantity,
245            price,
246            time_in_force,
247            expire_time,
248            post_only,
249            reduce_only,
250            quote_quantity,
251            display_qty,
252            emulation_trigger,
253            trigger_instrument_id,
254            exec_algorithm_id,
255            exec_algorithm_params,
256            tags,
257            client_order_id,
258        )
259        .unwrap_or_else(|e| panic!("{e}"))
260    }
261
262    #[expect(clippy::too_many_arguments)]
263    pub(crate) fn try_limit(
264        &mut self,
265        instrument_id: InstrumentId,
266        order_side: OrderSide,
267        quantity: Quantity,
268        price: Price,
269        time_in_force: Option<TimeInForce>,
270        expire_time: Option<nautilus_core::UnixNanos>,
271        post_only: Option<bool>,
272        reduce_only: Option<bool>,
273        quote_quantity: Option<bool>,
274        display_qty: Option<Quantity>,
275        emulation_trigger: Option<TriggerType>,
276        trigger_instrument_id: Option<InstrumentId>,
277        exec_algorithm_id: Option<ExecAlgorithmId>,
278        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
279        tags: Option<Vec<Ustr>>,
280        client_order_id: Option<ClientOrderId>,
281    ) -> anyhow::Result<OrderAny> {
282        let client_order_id = client_order_id.unwrap_or_else(|| self.generate_client_order_id());
283        let exec_spawn_id: Option<ClientOrderId> = if exec_algorithm_id.is_none() {
284            None
285        } else {
286            Some(client_order_id)
287        };
288        let order = LimitOrder::new_checked(
289            self.trader_id,
290            self.strategy_id,
291            instrument_id,
292            client_order_id,
293            order_side,
294            quantity,
295            price,
296            time_in_force.unwrap_or(TimeInForce::Gtc),
297            expire_time,
298            post_only.unwrap_or(false),
299            reduce_only.unwrap_or(false),
300            quote_quantity.unwrap_or(false),
301            display_qty,
302            emulation_trigger,
303            trigger_instrument_id,
304            None,
305            None,
306            None,
307            None,
308            exec_algorithm_id,
309            exec_algorithm_params,
310            exec_spawn_id,
311            tags,
312            UUID4::new(),
313            self.clock.borrow().timestamp_ns(),
314        )?;
315        Ok(OrderAny::Limit(order))
316    }
317
318    /// Creates a new stop-market order.
319    ///
320    /// # Panics
321    ///
322    /// Panics if the order parameters fail validation.
323    #[expect(clippy::too_many_arguments)]
324    pub fn stop_market(
325        &mut self,
326        instrument_id: InstrumentId,
327        order_side: OrderSide,
328        quantity: Quantity,
329        trigger_price: Price,
330        trigger_type: Option<TriggerType>,
331        time_in_force: Option<TimeInForce>,
332        expire_time: Option<nautilus_core::UnixNanos>,
333        reduce_only: Option<bool>,
334        quote_quantity: Option<bool>,
335        display_qty: Option<Quantity>,
336        emulation_trigger: Option<TriggerType>,
337        trigger_instrument_id: Option<InstrumentId>,
338        exec_algorithm_id: Option<ExecAlgorithmId>,
339        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
340        tags: Option<Vec<Ustr>>,
341        client_order_id: Option<ClientOrderId>,
342    ) -> OrderAny {
343        self.try_stop_market(
344            instrument_id,
345            order_side,
346            quantity,
347            trigger_price,
348            trigger_type,
349            time_in_force,
350            expire_time,
351            reduce_only,
352            quote_quantity,
353            display_qty,
354            emulation_trigger,
355            trigger_instrument_id,
356            exec_algorithm_id,
357            exec_algorithm_params,
358            tags,
359            client_order_id,
360        )
361        .unwrap_or_else(|e| panic!("{e}"))
362    }
363
364    #[expect(clippy::too_many_arguments)]
365    pub(crate) fn try_stop_market(
366        &mut self,
367        instrument_id: InstrumentId,
368        order_side: OrderSide,
369        quantity: Quantity,
370        trigger_price: Price,
371        trigger_type: Option<TriggerType>,
372        time_in_force: Option<TimeInForce>,
373        expire_time: Option<nautilus_core::UnixNanos>,
374        reduce_only: Option<bool>,
375        quote_quantity: Option<bool>,
376        display_qty: Option<Quantity>,
377        emulation_trigger: Option<TriggerType>,
378        trigger_instrument_id: Option<InstrumentId>,
379        exec_algorithm_id: Option<ExecAlgorithmId>,
380        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
381        tags: Option<Vec<Ustr>>,
382        client_order_id: Option<ClientOrderId>,
383    ) -> anyhow::Result<OrderAny> {
384        let client_order_id = client_order_id.unwrap_or_else(|| self.generate_client_order_id());
385        let exec_spawn_id: Option<ClientOrderId> = if exec_algorithm_id.is_none() {
386            None
387        } else {
388            Some(client_order_id)
389        };
390        let order = StopMarketOrder::new_checked(
391            self.trader_id,
392            self.strategy_id,
393            instrument_id,
394            client_order_id,
395            order_side,
396            quantity,
397            trigger_price,
398            trigger_type.unwrap_or(TriggerType::Default),
399            time_in_force.unwrap_or(TimeInForce::Gtc),
400            expire_time,
401            reduce_only.unwrap_or(false),
402            quote_quantity.unwrap_or(false),
403            display_qty,
404            emulation_trigger,
405            trigger_instrument_id,
406            None,
407            None,
408            None,
409            None,
410            exec_algorithm_id,
411            exec_algorithm_params,
412            exec_spawn_id,
413            tags,
414            UUID4::new(),
415            self.clock.borrow().timestamp_ns(),
416        )?;
417        Ok(OrderAny::StopMarket(order))
418    }
419
420    /// Creates a new stop-limit order.
421    ///
422    /// # Panics
423    ///
424    /// Panics if the order parameters fail validation.
425    #[expect(clippy::too_many_arguments)]
426    pub fn stop_limit(
427        &mut self,
428        instrument_id: InstrumentId,
429        order_side: OrderSide,
430        quantity: Quantity,
431        price: Price,
432        trigger_price: Price,
433        trigger_type: Option<TriggerType>,
434        time_in_force: Option<TimeInForce>,
435        expire_time: Option<nautilus_core::UnixNanos>,
436        post_only: Option<bool>,
437        reduce_only: Option<bool>,
438        quote_quantity: Option<bool>,
439        display_qty: Option<Quantity>,
440        emulation_trigger: Option<TriggerType>,
441        trigger_instrument_id: Option<InstrumentId>,
442        exec_algorithm_id: Option<ExecAlgorithmId>,
443        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
444        tags: Option<Vec<Ustr>>,
445        client_order_id: Option<ClientOrderId>,
446    ) -> OrderAny {
447        self.try_stop_limit(
448            instrument_id,
449            order_side,
450            quantity,
451            price,
452            trigger_price,
453            trigger_type,
454            time_in_force,
455            expire_time,
456            post_only,
457            reduce_only,
458            quote_quantity,
459            display_qty,
460            emulation_trigger,
461            trigger_instrument_id,
462            exec_algorithm_id,
463            exec_algorithm_params,
464            tags,
465            client_order_id,
466        )
467        .unwrap_or_else(|e| panic!("{e}"))
468    }
469
470    #[expect(clippy::too_many_arguments)]
471    pub(crate) fn try_stop_limit(
472        &mut self,
473        instrument_id: InstrumentId,
474        order_side: OrderSide,
475        quantity: Quantity,
476        price: Price,
477        trigger_price: Price,
478        trigger_type: Option<TriggerType>,
479        time_in_force: Option<TimeInForce>,
480        expire_time: Option<nautilus_core::UnixNanos>,
481        post_only: Option<bool>,
482        reduce_only: Option<bool>,
483        quote_quantity: Option<bool>,
484        display_qty: Option<Quantity>,
485        emulation_trigger: Option<TriggerType>,
486        trigger_instrument_id: Option<InstrumentId>,
487        exec_algorithm_id: Option<ExecAlgorithmId>,
488        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
489        tags: Option<Vec<Ustr>>,
490        client_order_id: Option<ClientOrderId>,
491    ) -> anyhow::Result<OrderAny> {
492        let client_order_id = client_order_id.unwrap_or_else(|| self.generate_client_order_id());
493        let exec_spawn_id: Option<ClientOrderId> = if exec_algorithm_id.is_none() {
494            None
495        } else {
496            Some(client_order_id)
497        };
498        let order = StopLimitOrder::new_checked(
499            self.trader_id,
500            self.strategy_id,
501            instrument_id,
502            client_order_id,
503            order_side,
504            quantity,
505            price,
506            trigger_price,
507            trigger_type.unwrap_or(TriggerType::Default),
508            time_in_force.unwrap_or(TimeInForce::Gtc),
509            expire_time,
510            post_only.unwrap_or(false),
511            reduce_only.unwrap_or(false),
512            quote_quantity.unwrap_or(false),
513            display_qty,
514            emulation_trigger,
515            trigger_instrument_id,
516            None,
517            None,
518            None,
519            None,
520            exec_algorithm_id,
521            exec_algorithm_params,
522            exec_spawn_id,
523            tags,
524            UUID4::new(),
525            self.clock.borrow().timestamp_ns(),
526        )?;
527        Ok(OrderAny::StopLimit(order))
528    }
529
530    /// Creates a new market-to-limit order.
531    ///
532    /// # Panics
533    ///
534    /// Panics if the order parameters fail validation.
535    #[expect(clippy::too_many_arguments)]
536    pub fn market_to_limit(
537        &mut self,
538        instrument_id: InstrumentId,
539        order_side: OrderSide,
540        quantity: Quantity,
541        time_in_force: Option<TimeInForce>,
542        expire_time: Option<nautilus_core::UnixNanos>,
543        reduce_only: Option<bool>,
544        quote_quantity: Option<bool>,
545        display_qty: Option<Quantity>,
546        exec_algorithm_id: Option<ExecAlgorithmId>,
547        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
548        tags: Option<Vec<Ustr>>,
549        client_order_id: Option<ClientOrderId>,
550    ) -> OrderAny {
551        self.try_market_to_limit(
552            instrument_id,
553            order_side,
554            quantity,
555            time_in_force,
556            expire_time,
557            reduce_only,
558            quote_quantity,
559            display_qty,
560            exec_algorithm_id,
561            exec_algorithm_params,
562            tags,
563            client_order_id,
564        )
565        .unwrap_or_else(|e| panic!("{e}"))
566    }
567
568    #[expect(clippy::too_many_arguments)]
569    pub(crate) fn try_market_to_limit(
570        &mut self,
571        instrument_id: InstrumentId,
572        order_side: OrderSide,
573        quantity: Quantity,
574        time_in_force: Option<TimeInForce>,
575        expire_time: Option<nautilus_core::UnixNanos>,
576        reduce_only: Option<bool>,
577        quote_quantity: Option<bool>,
578        display_qty: Option<Quantity>,
579        exec_algorithm_id: Option<ExecAlgorithmId>,
580        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
581        tags: Option<Vec<Ustr>>,
582        client_order_id: Option<ClientOrderId>,
583    ) -> anyhow::Result<OrderAny> {
584        let client_order_id = client_order_id.unwrap_or_else(|| self.generate_client_order_id());
585        let exec_spawn_id: Option<ClientOrderId> = if exec_algorithm_id.is_none() {
586            None
587        } else {
588            Some(client_order_id)
589        };
590        let order = MarketToLimitOrder::new_checked(
591            self.trader_id,
592            self.strategy_id,
593            instrument_id,
594            client_order_id,
595            order_side,
596            quantity,
597            time_in_force.unwrap_or(TimeInForce::Gtc),
598            expire_time,
599            false, // post_only
600            reduce_only.unwrap_or(false),
601            quote_quantity.unwrap_or(false),
602            display_qty,
603            None,
604            None,
605            None,
606            None,
607            exec_algorithm_id,
608            exec_algorithm_params,
609            exec_spawn_id,
610            tags,
611            UUID4::new(),
612            self.clock.borrow().timestamp_ns(),
613        )?;
614        Ok(OrderAny::MarketToLimit(order))
615    }
616
617    /// Creates a new market-if-touched order.
618    ///
619    /// # Panics
620    ///
621    /// Panics if the order parameters fail validation.
622    #[expect(clippy::too_many_arguments)]
623    pub fn market_if_touched(
624        &mut self,
625        instrument_id: InstrumentId,
626        order_side: OrderSide,
627        quantity: Quantity,
628        trigger_price: Price,
629        trigger_type: Option<TriggerType>,
630        time_in_force: Option<TimeInForce>,
631        expire_time: Option<nautilus_core::UnixNanos>,
632        reduce_only: Option<bool>,
633        quote_quantity: Option<bool>,
634        emulation_trigger: Option<TriggerType>,
635        trigger_instrument_id: Option<InstrumentId>,
636        exec_algorithm_id: Option<ExecAlgorithmId>,
637        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
638        tags: Option<Vec<Ustr>>,
639        client_order_id: Option<ClientOrderId>,
640    ) -> OrderAny {
641        self.try_market_if_touched(
642            instrument_id,
643            order_side,
644            quantity,
645            trigger_price,
646            trigger_type,
647            time_in_force,
648            expire_time,
649            reduce_only,
650            quote_quantity,
651            emulation_trigger,
652            trigger_instrument_id,
653            exec_algorithm_id,
654            exec_algorithm_params,
655            tags,
656            client_order_id,
657        )
658        .unwrap_or_else(|e| panic!("{e}"))
659    }
660
661    #[expect(clippy::too_many_arguments)]
662    pub(crate) fn try_market_if_touched(
663        &mut self,
664        instrument_id: InstrumentId,
665        order_side: OrderSide,
666        quantity: Quantity,
667        trigger_price: Price,
668        trigger_type: Option<TriggerType>,
669        time_in_force: Option<TimeInForce>,
670        expire_time: Option<nautilus_core::UnixNanos>,
671        reduce_only: Option<bool>,
672        quote_quantity: Option<bool>,
673        emulation_trigger: Option<TriggerType>,
674        trigger_instrument_id: Option<InstrumentId>,
675        exec_algorithm_id: Option<ExecAlgorithmId>,
676        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
677        tags: Option<Vec<Ustr>>,
678        client_order_id: Option<ClientOrderId>,
679    ) -> anyhow::Result<OrderAny> {
680        let client_order_id = client_order_id.unwrap_or_else(|| self.generate_client_order_id());
681        let exec_spawn_id: Option<ClientOrderId> = if exec_algorithm_id.is_none() {
682            None
683        } else {
684            Some(client_order_id)
685        };
686        let order = MarketIfTouchedOrder::new_checked(
687            self.trader_id,
688            self.strategy_id,
689            instrument_id,
690            client_order_id,
691            order_side,
692            quantity,
693            trigger_price,
694            trigger_type.unwrap_or(TriggerType::Default),
695            time_in_force.unwrap_or(TimeInForce::Gtc),
696            expire_time,
697            reduce_only.unwrap_or(false),
698            quote_quantity.unwrap_or(false),
699            emulation_trigger,
700            trigger_instrument_id,
701            None,
702            None,
703            None,
704            None,
705            exec_algorithm_id,
706            exec_algorithm_params,
707            exec_spawn_id,
708            tags,
709            UUID4::new(),
710            self.clock.borrow().timestamp_ns(),
711        )?;
712        Ok(OrderAny::MarketIfTouched(order))
713    }
714
715    /// Creates a new limit-if-touched order.
716    ///
717    /// # Panics
718    ///
719    /// Panics if the order parameters fail validation.
720    #[expect(clippy::too_many_arguments)]
721    pub fn limit_if_touched(
722        &mut self,
723        instrument_id: InstrumentId,
724        order_side: OrderSide,
725        quantity: Quantity,
726        price: Price,
727        trigger_price: Price,
728        trigger_type: Option<TriggerType>,
729        time_in_force: Option<TimeInForce>,
730        expire_time: Option<nautilus_core::UnixNanos>,
731        post_only: Option<bool>,
732        reduce_only: Option<bool>,
733        quote_quantity: Option<bool>,
734        display_qty: Option<Quantity>,
735        emulation_trigger: Option<TriggerType>,
736        trigger_instrument_id: Option<InstrumentId>,
737        exec_algorithm_id: Option<ExecAlgorithmId>,
738        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
739        tags: Option<Vec<Ustr>>,
740        client_order_id: Option<ClientOrderId>,
741    ) -> OrderAny {
742        self.try_limit_if_touched(
743            instrument_id,
744            order_side,
745            quantity,
746            price,
747            trigger_price,
748            trigger_type,
749            time_in_force,
750            expire_time,
751            post_only,
752            reduce_only,
753            quote_quantity,
754            display_qty,
755            emulation_trigger,
756            trigger_instrument_id,
757            exec_algorithm_id,
758            exec_algorithm_params,
759            tags,
760            client_order_id,
761        )
762        .unwrap_or_else(|e| panic!("{e}"))
763    }
764
765    #[expect(clippy::too_many_arguments)]
766    pub(crate) fn try_limit_if_touched(
767        &mut self,
768        instrument_id: InstrumentId,
769        order_side: OrderSide,
770        quantity: Quantity,
771        price: Price,
772        trigger_price: Price,
773        trigger_type: Option<TriggerType>,
774        time_in_force: Option<TimeInForce>,
775        expire_time: Option<nautilus_core::UnixNanos>,
776        post_only: Option<bool>,
777        reduce_only: Option<bool>,
778        quote_quantity: Option<bool>,
779        display_qty: Option<Quantity>,
780        emulation_trigger: Option<TriggerType>,
781        trigger_instrument_id: Option<InstrumentId>,
782        exec_algorithm_id: Option<ExecAlgorithmId>,
783        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
784        tags: Option<Vec<Ustr>>,
785        client_order_id: Option<ClientOrderId>,
786    ) -> anyhow::Result<OrderAny> {
787        let client_order_id = client_order_id.unwrap_or_else(|| self.generate_client_order_id());
788        let exec_spawn_id: Option<ClientOrderId> = if exec_algorithm_id.is_none() {
789            None
790        } else {
791            Some(client_order_id)
792        };
793        let order = LimitIfTouchedOrder::new_checked(
794            self.trader_id,
795            self.strategy_id,
796            instrument_id,
797            client_order_id,
798            order_side,
799            quantity,
800            price,
801            trigger_price,
802            trigger_type.unwrap_or(TriggerType::Default),
803            time_in_force.unwrap_or(TimeInForce::Gtc),
804            expire_time,
805            post_only.unwrap_or(false),
806            reduce_only.unwrap_or(false),
807            quote_quantity.unwrap_or(false),
808            display_qty,
809            emulation_trigger,
810            trigger_instrument_id,
811            None,
812            None,
813            None,
814            None,
815            exec_algorithm_id,
816            exec_algorithm_params,
817            exec_spawn_id,
818            tags,
819            UUID4::new(),
820            self.clock.borrow().timestamp_ns(),
821        )?;
822        Ok(OrderAny::LimitIfTouched(order))
823    }
824
825    /// Creates a new trailing-stop-market order.
826    ///
827    /// # Panics
828    ///
829    /// Panics if the order parameters fail validation.
830    #[expect(clippy::too_many_arguments)]
831    pub fn trailing_stop_market(
832        &mut self,
833        instrument_id: InstrumentId,
834        order_side: OrderSide,
835        quantity: Quantity,
836        trailing_offset: Decimal,
837        trailing_offset_type: Option<TrailingOffsetType>,
838        activation_price: Option<Price>,
839        trigger_price: Option<Price>,
840        trigger_type: Option<TriggerType>,
841        time_in_force: Option<TimeInForce>,
842        expire_time: Option<nautilus_core::UnixNanos>,
843        reduce_only: Option<bool>,
844        quote_quantity: Option<bool>,
845        display_qty: Option<Quantity>,
846        emulation_trigger: Option<TriggerType>,
847        trigger_instrument_id: Option<InstrumentId>,
848        exec_algorithm_id: Option<ExecAlgorithmId>,
849        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
850        tags: Option<Vec<Ustr>>,
851        client_order_id: Option<ClientOrderId>,
852    ) -> OrderAny {
853        self.try_trailing_stop_market(
854            instrument_id,
855            order_side,
856            quantity,
857            trailing_offset,
858            trailing_offset_type,
859            activation_price,
860            trigger_price,
861            trigger_type,
862            time_in_force,
863            expire_time,
864            reduce_only,
865            quote_quantity,
866            display_qty,
867            emulation_trigger,
868            trigger_instrument_id,
869            exec_algorithm_id,
870            exec_algorithm_params,
871            tags,
872            client_order_id,
873        )
874        .unwrap_or_else(|e| panic!("{e}"))
875    }
876
877    #[expect(clippy::too_many_arguments)]
878    pub(crate) fn try_trailing_stop_market(
879        &mut self,
880        instrument_id: InstrumentId,
881        order_side: OrderSide,
882        quantity: Quantity,
883        trailing_offset: Decimal,
884        trailing_offset_type: Option<TrailingOffsetType>,
885        activation_price: Option<Price>,
886        trigger_price: Option<Price>,
887        trigger_type: Option<TriggerType>,
888        time_in_force: Option<TimeInForce>,
889        expire_time: Option<nautilus_core::UnixNanos>,
890        reduce_only: Option<bool>,
891        quote_quantity: Option<bool>,
892        display_qty: Option<Quantity>,
893        emulation_trigger: Option<TriggerType>,
894        trigger_instrument_id: Option<InstrumentId>,
895        exec_algorithm_id: Option<ExecAlgorithmId>,
896        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
897        tags: Option<Vec<Ustr>>,
898        client_order_id: Option<ClientOrderId>,
899    ) -> anyhow::Result<OrderAny> {
900        let client_order_id = client_order_id.unwrap_or_else(|| self.generate_client_order_id());
901        let exec_spawn_id: Option<ClientOrderId> = if exec_algorithm_id.is_none() {
902            None
903        } else {
904            Some(client_order_id)
905        };
906
907        // Both `trigger_price` and `activation_price` may be `None`: the order then activates at
908        // market and its initial trigger materializes from `trailing_offset` on the first update.
909        // To make activation serve as the initial trigger (OKX), pass it explicitly as `trigger_price`.
910        let order = TrailingStopMarketOrder::new_checked(
911            self.trader_id,
912            self.strategy_id,
913            instrument_id,
914            client_order_id,
915            order_side,
916            quantity,
917            activation_price,
918            trigger_price,
919            trigger_type.unwrap_or(TriggerType::Default),
920            trailing_offset,
921            trailing_offset_type.unwrap_or(TrailingOffsetType::Price),
922            time_in_force.unwrap_or(TimeInForce::Gtc),
923            expire_time,
924            reduce_only.unwrap_or(false),
925            quote_quantity.unwrap_or(false),
926            display_qty,
927            emulation_trigger,
928            trigger_instrument_id,
929            None,
930            None,
931            None,
932            None,
933            exec_algorithm_id,
934            exec_algorithm_params,
935            exec_spawn_id,
936            tags,
937            UUID4::new(),
938            self.clock.borrow().timestamp_ns(),
939        )?;
940
941        Ok(OrderAny::TrailingStopMarket(order))
942    }
943
944    /// Creates a new trailing-stop-limit order.
945    ///
946    /// # Panics
947    ///
948    /// Panics if the order parameters fail validation.
949    #[expect(clippy::too_many_arguments)]
950    pub fn trailing_stop_limit(
951        &mut self,
952        instrument_id: InstrumentId,
953        order_side: OrderSide,
954        quantity: Quantity,
955        price: Option<Price>,
956        limit_offset: Decimal,
957        trailing_offset: Decimal,
958        trailing_offset_type: Option<TrailingOffsetType>,
959        activation_price: Option<Price>,
960        trigger_price: Option<Price>,
961        trigger_type: Option<TriggerType>,
962        time_in_force: Option<TimeInForce>,
963        expire_time: Option<nautilus_core::UnixNanos>,
964        post_only: Option<bool>,
965        reduce_only: Option<bool>,
966        quote_quantity: Option<bool>,
967        display_qty: Option<Quantity>,
968        emulation_trigger: Option<TriggerType>,
969        trigger_instrument_id: Option<InstrumentId>,
970        exec_algorithm_id: Option<ExecAlgorithmId>,
971        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
972        tags: Option<Vec<Ustr>>,
973        client_order_id: Option<ClientOrderId>,
974    ) -> OrderAny {
975        self.try_trailing_stop_limit(
976            instrument_id,
977            order_side,
978            quantity,
979            price,
980            limit_offset,
981            trailing_offset,
982            trailing_offset_type,
983            activation_price,
984            trigger_price,
985            trigger_type,
986            time_in_force,
987            expire_time,
988            post_only,
989            reduce_only,
990            quote_quantity,
991            display_qty,
992            emulation_trigger,
993            trigger_instrument_id,
994            exec_algorithm_id,
995            exec_algorithm_params,
996            tags,
997            client_order_id,
998        )
999        .unwrap_or_else(|e| panic!("{e}"))
1000    }
1001
1002    #[expect(clippy::too_many_arguments)]
1003    pub(crate) fn try_trailing_stop_limit(
1004        &mut self,
1005        instrument_id: InstrumentId,
1006        order_side: OrderSide,
1007        quantity: Quantity,
1008        price: Option<Price>,
1009        limit_offset: Decimal,
1010        trailing_offset: Decimal,
1011        trailing_offset_type: Option<TrailingOffsetType>,
1012        activation_price: Option<Price>,
1013        trigger_price: Option<Price>,
1014        trigger_type: Option<TriggerType>,
1015        time_in_force: Option<TimeInForce>,
1016        expire_time: Option<nautilus_core::UnixNanos>,
1017        post_only: Option<bool>,
1018        reduce_only: Option<bool>,
1019        quote_quantity: Option<bool>,
1020        display_qty: Option<Quantity>,
1021        emulation_trigger: Option<TriggerType>,
1022        trigger_instrument_id: Option<InstrumentId>,
1023        exec_algorithm_id: Option<ExecAlgorithmId>,
1024        exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
1025        tags: Option<Vec<Ustr>>,
1026        client_order_id: Option<ClientOrderId>,
1027    ) -> anyhow::Result<OrderAny> {
1028        let client_order_id = client_order_id.unwrap_or_else(|| self.generate_client_order_id());
1029        let exec_spawn_id: Option<ClientOrderId> = if exec_algorithm_id.is_none() {
1030            None
1031        } else {
1032            Some(client_order_id)
1033        };
1034
1035        // Both `trigger_price` and `activation_price` may be `None`: the order then activates at
1036        // market and its initial trigger (and limit price) materialize from the offsets on the first
1037        // update. To make activation serve as the initial trigger (OKX), pass it as `trigger_price`.
1038        let order = TrailingStopLimitOrder::new_checked(
1039            self.trader_id,
1040            self.strategy_id,
1041            instrument_id,
1042            client_order_id,
1043            order_side,
1044            quantity,
1045            activation_price,
1046            price,
1047            trigger_price,
1048            trigger_type.unwrap_or(TriggerType::Default),
1049            limit_offset,
1050            trailing_offset,
1051            trailing_offset_type.unwrap_or(TrailingOffsetType::Price),
1052            time_in_force.unwrap_or(TimeInForce::Gtc),
1053            expire_time,
1054            post_only.unwrap_or(false),
1055            reduce_only.unwrap_or(false),
1056            quote_quantity.unwrap_or(false),
1057            display_qty,
1058            emulation_trigger,
1059            trigger_instrument_id,
1060            None,
1061            None,
1062            None,
1063            None,
1064            exec_algorithm_id,
1065            exec_algorithm_params,
1066            exec_spawn_id,
1067            tags,
1068            UUID4::new(),
1069            self.clock.borrow().timestamp_ns(),
1070        )?;
1071
1072        Ok(OrderAny::TrailingStopLimit(order))
1073    }
1074
1075    /// Creates a new [`OrderList`] from the given orders, generating a fresh
1076    /// order list ID and propagating it back to each order.
1077    ///
1078    /// All orders must share the same venue; the caller is responsible for
1079    /// passing orders with the factory's `strategy_id`. The returned list's
1080    /// invariants are checked by [`OrderList::validate`] at submission time.
1081    ///
1082    /// # Panics
1083    ///
1084    /// Panics if `orders` is empty or if orders span more than one venue.
1085    /// Callers are expected to guard non-empty input; `Strategy::submit_order_list`
1086    /// filters out the empty case and bails on mixed venues before reaching
1087    /// this constructor.
1088    #[must_use]
1089    pub fn create_list(&mut self, orders: &mut [OrderAny], ts_init: UnixNanos) -> OrderList {
1090        let instrument_id = orders
1091            .first()
1092            .expect("OrderFactory::create_list requires non-empty orders")
1093            .instrument_id();
1094        let venue = instrument_id.venue;
1095
1096        for order in orders.iter() {
1097            assert!(
1098                order.instrument_id().venue == venue,
1099                "OrderFactory::create_list requires all orders to share the same venue; \
1100                 expected {venue}, found {} on {}",
1101                order.instrument_id().venue,
1102                order.client_order_id(),
1103            );
1104        }
1105
1106        let order_list_id = self.generate_order_list_id();
1107        let order_ids: Vec<ClientOrderId> = orders.iter().map(OrderAny::client_order_id).collect();
1108
1109        for order in orders.iter_mut() {
1110            order.set_order_list_id(order_list_id);
1111        }
1112
1113        OrderList::new(
1114            order_list_id,
1115            instrument_id,
1116            self.strategy_id,
1117            order_ids,
1118            ts_init,
1119        )
1120    }
1121
1122    /// Creates a bracket order with an entry order and attached take-profit and stop-loss legs.
1123    ///
1124    /// Defaults:
1125    /// - `contingency_type`: `Ouo` for the TP/SL legs.
1126    /// - `entry_order_type`: `Market`; `tp_order_type`: `Limit`; `sl_order_type`: `StopMarket`.
1127    /// - `entry_tags`: `["ENTRY"]`; `tp_tags`: `["TAKE_PROFIT"]`; `sl_tags`: `["STOP_LOSS"]`.
1128    /// - `tp_post_only`: `true` for `Limit` and `LimitIfTouched`; `entry_post_only`: `false`.
1129    /// - `tp_reduce_only` and `sl_reduce_only`: `true`; the entry is always `reduce_only = false`.
1130    /// - TP and SL legs do not inherit `expire_time` from the entry.
1131    ///
1132    /// Setting `tp_reduce_only` or `sl_reduce_only` to `false` gives up the reduce-only guarantee
1133    /// for that leg. If the position is closed separately, the leg can still fill and open a
1134    /// position in the opposite direction.
1135    ///
1136    /// # Panics
1137    ///
1138    /// Panics if `entry_order_type`, `tp_order_type`, or `sl_order_type` is not one of the
1139    /// supported variants, or if a required price/trigger field is missing for the chosen type.
1140    #[builder]
1141    pub fn bracket(
1142        &mut self,
1143        instrument_id: InstrumentId,
1144        order_side: OrderSide,
1145        quantity: Quantity,
1146        #[builder(default = false)] quote_quantity: bool,
1147        emulation_trigger: Option<TriggerType>,
1148        trigger_instrument_id: Option<InstrumentId>,
1149        #[builder(default = ContingencyType::Ouo)] contingency_type: ContingencyType,
1150        // Entry order
1151        #[builder(default = OrderType::Market)] entry_order_type: OrderType,
1152        entry_price: Option<Price>,
1153        entry_trigger_price: Option<Price>,
1154        expire_time: Option<nautilus_core::UnixNanos>,
1155        #[builder(default = TimeInForce::Gtc)] time_in_force: TimeInForce,
1156        #[builder(default = false)] entry_post_only: bool,
1157        entry_exec_algorithm_id: Option<ExecAlgorithmId>,
1158        entry_exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
1159        #[builder(default = vec![Ustr::from("ENTRY")])] entry_tags: Vec<Ustr>,
1160        entry_client_order_id: Option<ClientOrderId>,
1161        // Take-profit order
1162        #[builder(default = OrderType::Limit)] tp_order_type: OrderType,
1163        tp_price: Option<Price>,
1164        tp_trigger_price: Option<Price>,
1165        #[builder(default = TriggerType::Default)] tp_trigger_type: TriggerType,
1166        tp_activation_price: Option<Price>,
1167        tp_trailing_offset: Option<Decimal>,
1168        #[builder(default = TrailingOffsetType::Price)] tp_trailing_offset_type: TrailingOffsetType,
1169        tp_limit_offset: Option<Decimal>,
1170        #[builder(default = TimeInForce::Gtc)] tp_time_in_force: TimeInForce,
1171        #[builder(default = true)] tp_post_only: bool,
1172        #[builder(default = true)] tp_reduce_only: bool,
1173        tp_exec_algorithm_id: Option<ExecAlgorithmId>,
1174        tp_exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
1175        #[builder(default = vec![Ustr::from("TAKE_PROFIT")])] tp_tags: Vec<Ustr>,
1176        tp_client_order_id: Option<ClientOrderId>,
1177        // Stop-loss order
1178        #[builder(default = OrderType::StopMarket)] sl_order_type: OrderType,
1179        sl_trigger_price: Option<Price>,
1180        #[builder(default = TriggerType::Default)] sl_trigger_type: TriggerType,
1181        sl_activation_price: Option<Price>,
1182        sl_trailing_offset: Option<Decimal>,
1183        #[builder(default = TrailingOffsetType::Price)] sl_trailing_offset_type: TrailingOffsetType,
1184        #[builder(default = TimeInForce::Gtc)] sl_time_in_force: TimeInForce,
1185        #[builder(default = true)] sl_reduce_only: bool,
1186        sl_exec_algorithm_id: Option<ExecAlgorithmId>,
1187        sl_exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
1188        #[builder(default = vec![Ustr::from("STOP_LOSS")])] sl_tags: Vec<Ustr>,
1189        sl_client_order_id: Option<ClientOrderId>,
1190    ) -> Vec<OrderAny> {
1191        self.try_bracket()
1192            .instrument_id(instrument_id)
1193            .order_side(order_side)
1194            .quantity(quantity)
1195            .quote_quantity(quote_quantity)
1196            .maybe_emulation_trigger(emulation_trigger)
1197            .maybe_trigger_instrument_id(trigger_instrument_id)
1198            .contingency_type(contingency_type)
1199            .entry_order_type(entry_order_type)
1200            .maybe_entry_price(entry_price)
1201            .maybe_entry_trigger_price(entry_trigger_price)
1202            .maybe_expire_time(expire_time)
1203            .time_in_force(time_in_force)
1204            .entry_post_only(entry_post_only)
1205            .maybe_entry_exec_algorithm_id(entry_exec_algorithm_id)
1206            .maybe_entry_exec_algorithm_params(entry_exec_algorithm_params)
1207            .entry_tags(entry_tags)
1208            .maybe_entry_client_order_id(entry_client_order_id)
1209            .tp_order_type(tp_order_type)
1210            .maybe_tp_price(tp_price)
1211            .maybe_tp_trigger_price(tp_trigger_price)
1212            .tp_trigger_type(tp_trigger_type)
1213            .maybe_tp_activation_price(tp_activation_price)
1214            .maybe_tp_trailing_offset(tp_trailing_offset)
1215            .tp_trailing_offset_type(tp_trailing_offset_type)
1216            .maybe_tp_limit_offset(tp_limit_offset)
1217            .tp_time_in_force(tp_time_in_force)
1218            .tp_post_only(tp_post_only)
1219            .tp_reduce_only(tp_reduce_only)
1220            .maybe_tp_exec_algorithm_id(tp_exec_algorithm_id)
1221            .maybe_tp_exec_algorithm_params(tp_exec_algorithm_params)
1222            .tp_tags(tp_tags)
1223            .maybe_tp_client_order_id(tp_client_order_id)
1224            .sl_order_type(sl_order_type)
1225            .maybe_sl_trigger_price(sl_trigger_price)
1226            .sl_trigger_type(sl_trigger_type)
1227            .maybe_sl_activation_price(sl_activation_price)
1228            .maybe_sl_trailing_offset(sl_trailing_offset)
1229            .sl_trailing_offset_type(sl_trailing_offset_type)
1230            .sl_time_in_force(sl_time_in_force)
1231            .sl_reduce_only(sl_reduce_only)
1232            .maybe_sl_exec_algorithm_id(sl_exec_algorithm_id)
1233            .maybe_sl_exec_algorithm_params(sl_exec_algorithm_params)
1234            .sl_tags(sl_tags)
1235            .maybe_sl_client_order_id(sl_client_order_id)
1236            .call()
1237            .unwrap_or_else(|e| panic!("{e}"))
1238    }
1239
1240    #[expect(clippy::too_many_lines)]
1241    #[builder]
1242    pub(crate) fn try_bracket(
1243        &mut self,
1244        instrument_id: InstrumentId,
1245        order_side: OrderSide,
1246        quantity: Quantity,
1247        #[builder(default = false)] quote_quantity: bool,
1248        emulation_trigger: Option<TriggerType>,
1249        trigger_instrument_id: Option<InstrumentId>,
1250        #[builder(default = ContingencyType::Ouo)] contingency_type: ContingencyType,
1251        // Entry order
1252        #[builder(default = OrderType::Market)] entry_order_type: OrderType,
1253        entry_price: Option<Price>,
1254        entry_trigger_price: Option<Price>,
1255        expire_time: Option<nautilus_core::UnixNanos>,
1256        #[builder(default = TimeInForce::Gtc)] time_in_force: TimeInForce,
1257        #[builder(default = false)] entry_post_only: bool,
1258        entry_exec_algorithm_id: Option<ExecAlgorithmId>,
1259        entry_exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
1260        #[builder(default = vec![Ustr::from("ENTRY")])] entry_tags: Vec<Ustr>,
1261        entry_client_order_id: Option<ClientOrderId>,
1262        // Take-profit order
1263        #[builder(default = OrderType::Limit)] tp_order_type: OrderType,
1264        tp_price: Option<Price>,
1265        tp_trigger_price: Option<Price>,
1266        #[builder(default = TriggerType::Default)] tp_trigger_type: TriggerType,
1267        tp_activation_price: Option<Price>,
1268        tp_trailing_offset: Option<Decimal>,
1269        #[builder(default = TrailingOffsetType::Price)] tp_trailing_offset_type: TrailingOffsetType,
1270        tp_limit_offset: Option<Decimal>,
1271        #[builder(default = TimeInForce::Gtc)] tp_time_in_force: TimeInForce,
1272        #[builder(default = true)] tp_post_only: bool,
1273        #[builder(default = true)] tp_reduce_only: bool,
1274        tp_exec_algorithm_id: Option<ExecAlgorithmId>,
1275        tp_exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
1276        #[builder(default = vec![Ustr::from("TAKE_PROFIT")])] tp_tags: Vec<Ustr>,
1277        tp_client_order_id: Option<ClientOrderId>,
1278        // Stop-loss order
1279        #[builder(default = OrderType::StopMarket)] sl_order_type: OrderType,
1280        sl_trigger_price: Option<Price>,
1281        #[builder(default = TriggerType::Default)] sl_trigger_type: TriggerType,
1282        sl_activation_price: Option<Price>,
1283        sl_trailing_offset: Option<Decimal>,
1284        #[builder(default = TrailingOffsetType::Price)] sl_trailing_offset_type: TrailingOffsetType,
1285        #[builder(default = TimeInForce::Gtc)] sl_time_in_force: TimeInForce,
1286        #[builder(default = true)] sl_reduce_only: bool,
1287        sl_exec_algorithm_id: Option<ExecAlgorithmId>,
1288        sl_exec_algorithm_params: Option<IndexMap<Ustr, Ustr>>,
1289        #[builder(default = vec![Ustr::from("STOP_LOSS")])] sl_tags: Vec<Ustr>,
1290        sl_client_order_id: Option<ClientOrderId>,
1291    ) -> anyhow::Result<Vec<OrderAny>> {
1292        let order_list_id = self.generate_order_list_id();
1293        let ts_init = self.clock.borrow().timestamp_ns();
1294
1295        let entry_client_order_id =
1296            entry_client_order_id.unwrap_or_else(|| self.generate_client_order_id());
1297        let sl_client_order_id =
1298            sl_client_order_id.unwrap_or_else(|| self.generate_client_order_id());
1299        let tp_client_order_id =
1300            tp_client_order_id.unwrap_or_else(|| self.generate_client_order_id());
1301
1302        let entry_exec_spawn_id = entry_exec_algorithm_id
1303            .as_ref()
1304            .map(|_| entry_client_order_id);
1305        let tp_exec_spawn_id = tp_exec_algorithm_id.as_ref().map(|_| tp_client_order_id);
1306        let sl_exec_spawn_id = sl_exec_algorithm_id.as_ref().map(|_| sl_client_order_id);
1307
1308        let entry_tags = Some(entry_tags);
1309        let tp_tags = Some(tp_tags);
1310        let sl_tags = Some(sl_tags);
1311
1312        let entry_contingency_type = Some(ContingencyType::Oto);
1313        let entry_order_list_id = Some(order_list_id);
1314        let entry_linked_order_ids = Some(vec![sl_client_order_id, tp_client_order_id]);
1315        let entry_parent_order_id: Option<ClientOrderId> = None;
1316
1317        let entry_order = match entry_order_type {
1318            OrderType::Market => OrderAny::Market(MarketOrder::new_checked(
1319                self.trader_id,
1320                self.strategy_id,
1321                instrument_id,
1322                entry_client_order_id,
1323                order_side,
1324                quantity,
1325                time_in_force,
1326                UUID4::new(),
1327                ts_init,
1328                false, // reduce_only
1329                quote_quantity,
1330                entry_contingency_type,
1331                entry_order_list_id,
1332                entry_linked_order_ids,
1333                entry_parent_order_id,
1334                entry_exec_algorithm_id,
1335                entry_exec_algorithm_params,
1336                entry_exec_spawn_id,
1337                entry_tags,
1338            )?),
1339            OrderType::Limit => OrderAny::Limit(LimitOrder::new_checked(
1340                self.trader_id,
1341                self.strategy_id,
1342                instrument_id,
1343                entry_client_order_id,
1344                order_side,
1345                quantity,
1346                required(entry_price, "`entry_price` is required for a LIMIT entry")?,
1347                time_in_force,
1348                expire_time,
1349                entry_post_only,
1350                false, // reduce_only
1351                quote_quantity,
1352                None, // display_qty
1353                emulation_trigger,
1354                trigger_instrument_id,
1355                entry_contingency_type,
1356                entry_order_list_id,
1357                entry_linked_order_ids,
1358                entry_parent_order_id,
1359                entry_exec_algorithm_id,
1360                entry_exec_algorithm_params,
1361                entry_exec_spawn_id,
1362                entry_tags,
1363                UUID4::new(),
1364                ts_init,
1365            )?),
1366            OrderType::MarketIfTouched => {
1367                OrderAny::MarketIfTouched(MarketIfTouchedOrder::new_checked(
1368                    self.trader_id,
1369                    self.strategy_id,
1370                    instrument_id,
1371                    entry_client_order_id,
1372                    order_side,
1373                    quantity,
1374                    required(
1375                        entry_trigger_price,
1376                        "`entry_trigger_price` is required for a MARKET_IF_TOUCHED entry",
1377                    )?,
1378                    TriggerType::Default,
1379                    time_in_force,
1380                    expire_time,
1381                    false, // reduce_only
1382                    quote_quantity,
1383                    emulation_trigger,
1384                    trigger_instrument_id,
1385                    entry_contingency_type,
1386                    entry_order_list_id,
1387                    entry_linked_order_ids,
1388                    entry_parent_order_id,
1389                    entry_exec_algorithm_id,
1390                    entry_exec_algorithm_params,
1391                    entry_exec_spawn_id,
1392                    entry_tags,
1393                    UUID4::new(),
1394                    ts_init,
1395                )?)
1396            }
1397            OrderType::LimitIfTouched => {
1398                OrderAny::LimitIfTouched(LimitIfTouchedOrder::new_checked(
1399                    self.trader_id,
1400                    self.strategy_id,
1401                    instrument_id,
1402                    entry_client_order_id,
1403                    order_side,
1404                    quantity,
1405                    required(
1406                        entry_price,
1407                        "`entry_price` is required for a LIMIT_IF_TOUCHED entry",
1408                    )?,
1409                    required(
1410                        entry_trigger_price,
1411                        "`entry_trigger_price` is required for a LIMIT_IF_TOUCHED entry",
1412                    )?,
1413                    TriggerType::Default,
1414                    time_in_force,
1415                    expire_time,
1416                    entry_post_only,
1417                    false, // reduce_only
1418                    quote_quantity,
1419                    None, // display_qty
1420                    emulation_trigger,
1421                    trigger_instrument_id,
1422                    entry_contingency_type,
1423                    entry_order_list_id,
1424                    entry_linked_order_ids,
1425                    entry_parent_order_id,
1426                    entry_exec_algorithm_id,
1427                    entry_exec_algorithm_params,
1428                    entry_exec_spawn_id,
1429                    entry_tags,
1430                    UUID4::new(),
1431                    ts_init,
1432                )?)
1433            }
1434            OrderType::StopLimit => OrderAny::StopLimit(StopLimitOrder::new_checked(
1435                self.trader_id,
1436                self.strategy_id,
1437                instrument_id,
1438                entry_client_order_id,
1439                order_side,
1440                quantity,
1441                required(
1442                    entry_price,
1443                    "`entry_price` is required for a STOP_LIMIT entry",
1444                )?,
1445                required(
1446                    entry_trigger_price,
1447                    "`entry_trigger_price` is required for a STOP_LIMIT entry",
1448                )?,
1449                TriggerType::Default,
1450                time_in_force,
1451                expire_time,
1452                entry_post_only,
1453                false, // reduce_only
1454                quote_quantity,
1455                None, // display_qty
1456                emulation_trigger,
1457                trigger_instrument_id,
1458                entry_contingency_type,
1459                entry_order_list_id,
1460                entry_linked_order_ids,
1461                entry_parent_order_id,
1462                entry_exec_algorithm_id,
1463                entry_exec_algorithm_params,
1464                entry_exec_spawn_id,
1465                entry_tags,
1466                UUID4::new(),
1467                ts_init,
1468            )?),
1469            other => anyhow::bail!("invalid `entry_order_type`, was {other}"),
1470        };
1471
1472        let sl_tp_side = match order_side {
1473            OrderSide::Buy => OrderSide::Sell,
1474            OrderSide::Sell => OrderSide::Buy,
1475        };
1476
1477        let tp_contingency_type = Some(contingency_type);
1478        let tp_order_list_id = Some(order_list_id);
1479        let tp_linked_order_ids = Some(vec![sl_client_order_id]);
1480        let tp_parent_order_id = Some(entry_client_order_id);
1481
1482        let tp_order = match tp_order_type {
1483            OrderType::Limit => OrderAny::Limit(LimitOrder::new_checked(
1484                self.trader_id,
1485                self.strategy_id,
1486                instrument_id,
1487                tp_client_order_id,
1488                sl_tp_side,
1489                quantity,
1490                required(tp_price, "`tp_price` is required for a LIMIT take-profit")?,
1491                tp_time_in_force,
1492                None, // expire_time
1493                tp_post_only,
1494                tp_reduce_only,
1495                quote_quantity,
1496                None, // display_qty
1497                emulation_trigger,
1498                trigger_instrument_id,
1499                tp_contingency_type,
1500                tp_order_list_id,
1501                tp_linked_order_ids,
1502                tp_parent_order_id,
1503                tp_exec_algorithm_id,
1504                tp_exec_algorithm_params,
1505                tp_exec_spawn_id,
1506                tp_tags,
1507                UUID4::new(),
1508                ts_init,
1509            )?),
1510            OrderType::LimitIfTouched => {
1511                OrderAny::LimitIfTouched(LimitIfTouchedOrder::new_checked(
1512                    self.trader_id,
1513                    self.strategy_id,
1514                    instrument_id,
1515                    tp_client_order_id,
1516                    sl_tp_side,
1517                    quantity,
1518                    required(
1519                        tp_price,
1520                        "`tp_price` is required for a LIMIT_IF_TOUCHED take-profit",
1521                    )?,
1522                    required(
1523                        tp_trigger_price,
1524                        "`tp_trigger_price` is required for a LIMIT_IF_TOUCHED take-profit",
1525                    )?,
1526                    tp_trigger_type,
1527                    tp_time_in_force,
1528                    None, // expire_time
1529                    tp_post_only,
1530                    tp_reduce_only,
1531                    quote_quantity,
1532                    None, // display_qty
1533                    emulation_trigger,
1534                    trigger_instrument_id,
1535                    tp_contingency_type,
1536                    tp_order_list_id,
1537                    tp_linked_order_ids,
1538                    tp_parent_order_id,
1539                    tp_exec_algorithm_id,
1540                    tp_exec_algorithm_params,
1541                    tp_exec_spawn_id,
1542                    tp_tags,
1543                    UUID4::new(),
1544                    ts_init,
1545                )?)
1546            }
1547            OrderType::MarketIfTouched => {
1548                OrderAny::MarketIfTouched(MarketIfTouchedOrder::new_checked(
1549                    self.trader_id,
1550                    self.strategy_id,
1551                    instrument_id,
1552                    tp_client_order_id,
1553                    sl_tp_side,
1554                    quantity,
1555                    required(
1556                        tp_trigger_price,
1557                        "`tp_trigger_price` is required for a MARKET_IF_TOUCHED take-profit",
1558                    )?,
1559                    tp_trigger_type,
1560                    tp_time_in_force,
1561                    None, // expire_time
1562                    tp_reduce_only,
1563                    quote_quantity,
1564                    emulation_trigger,
1565                    trigger_instrument_id,
1566                    tp_contingency_type,
1567                    tp_order_list_id,
1568                    tp_linked_order_ids,
1569                    tp_parent_order_id,
1570                    tp_exec_algorithm_id,
1571                    tp_exec_algorithm_params,
1572                    tp_exec_spawn_id,
1573                    tp_tags,
1574                    UUID4::new(),
1575                    ts_init,
1576                )?)
1577            }
1578            OrderType::TrailingStopMarket => {
1579                let tp_trailing_offset = required(
1580                    tp_trailing_offset,
1581                    "`tp_trailing_offset` is required for a TRAILING_STOP_MARKET take-profit",
1582                )?;
1583                let trigger_price = required(
1584                    tp_trigger_price.or(tp_activation_price),
1585                    "TRAILING_STOP_MARKET take-profit requires `tp_trigger_price` or `tp_activation_price`",
1586                )?;
1587                let order = TrailingStopMarketOrder::new_checked(
1588                    self.trader_id,
1589                    self.strategy_id,
1590                    instrument_id,
1591                    tp_client_order_id,
1592                    sl_tp_side,
1593                    quantity,
1594                    tp_activation_price,
1595                    Some(trigger_price),
1596                    tp_trigger_type,
1597                    tp_trailing_offset,
1598                    tp_trailing_offset_type,
1599                    tp_time_in_force,
1600                    None, // expire_time
1601                    tp_reduce_only,
1602                    quote_quantity,
1603                    None, // display_qty
1604                    emulation_trigger,
1605                    trigger_instrument_id,
1606                    tp_contingency_type,
1607                    tp_order_list_id,
1608                    tp_linked_order_ids,
1609                    tp_parent_order_id,
1610                    tp_exec_algorithm_id,
1611                    tp_exec_algorithm_params,
1612                    tp_exec_spawn_id,
1613                    tp_tags,
1614                    UUID4::new(),
1615                    ts_init,
1616                )?;
1617                OrderAny::TrailingStopMarket(order)
1618            }
1619            OrderType::TrailingStopLimit => {
1620                let tp_trailing_offset = required(
1621                    tp_trailing_offset,
1622                    "`tp_trailing_offset` is required for a TRAILING_STOP_LIMIT take-profit",
1623                )?;
1624                let tp_limit_offset = required(
1625                    tp_limit_offset,
1626                    "`tp_limit_offset` is required for a TRAILING_STOP_LIMIT take-profit",
1627                )?;
1628                let trigger_price = required(
1629                    tp_trigger_price.or(tp_activation_price),
1630                    "TRAILING_STOP_LIMIT take-profit requires `tp_trigger_price` or `tp_activation_price`",
1631                )?;
1632                let price = required(
1633                    tp_price,
1634                    "`tp_price` is required for a TRAILING_STOP_LIMIT take-profit",
1635                )?;
1636                let order = TrailingStopLimitOrder::new_checked(
1637                    self.trader_id,
1638                    self.strategy_id,
1639                    instrument_id,
1640                    tp_client_order_id,
1641                    sl_tp_side,
1642                    quantity,
1643                    tp_activation_price,
1644                    Some(price),
1645                    Some(trigger_price),
1646                    tp_trigger_type,
1647                    tp_limit_offset,
1648                    tp_trailing_offset,
1649                    tp_trailing_offset_type,
1650                    tp_time_in_force,
1651                    None,  // expire_time
1652                    false, // post_only (TRAILING_STOP_LIMIT TP must not be post-only)
1653                    tp_reduce_only,
1654                    quote_quantity,
1655                    None, // display_qty
1656                    emulation_trigger,
1657                    trigger_instrument_id,
1658                    tp_contingency_type,
1659                    tp_order_list_id,
1660                    tp_linked_order_ids,
1661                    tp_parent_order_id,
1662                    tp_exec_algorithm_id,
1663                    tp_exec_algorithm_params,
1664                    tp_exec_spawn_id,
1665                    tp_tags,
1666                    UUID4::new(),
1667                    ts_init,
1668                )?;
1669                OrderAny::TrailingStopLimit(order)
1670            }
1671            other => anyhow::bail!("invalid `tp_order_type`, was {other}"),
1672        };
1673
1674        let sl_contingency_type = Some(contingency_type);
1675        let sl_order_list_id = Some(order_list_id);
1676        let sl_linked_order_ids = Some(vec![tp_client_order_id]);
1677        let sl_parent_order_id = Some(entry_client_order_id);
1678
1679        let sl_order = match sl_order_type {
1680            OrderType::StopMarket => OrderAny::StopMarket(StopMarketOrder::new_checked(
1681                self.trader_id,
1682                self.strategy_id,
1683                instrument_id,
1684                sl_client_order_id,
1685                sl_tp_side,
1686                quantity,
1687                required(
1688                    sl_trigger_price,
1689                    "`sl_trigger_price` is required for a STOP_MARKET stop-loss",
1690                )?,
1691                sl_trigger_type,
1692                sl_time_in_force,
1693                None, // expire_time
1694                sl_reduce_only,
1695                quote_quantity,
1696                None, // display_qty
1697                emulation_trigger,
1698                trigger_instrument_id,
1699                sl_contingency_type,
1700                sl_order_list_id,
1701                sl_linked_order_ids,
1702                sl_parent_order_id,
1703                sl_exec_algorithm_id,
1704                sl_exec_algorithm_params,
1705                sl_exec_spawn_id,
1706                sl_tags,
1707                UUID4::new(),
1708                ts_init,
1709            )?),
1710            OrderType::TrailingStopMarket => {
1711                let sl_trailing_offset = required(
1712                    sl_trailing_offset,
1713                    "`sl_trailing_offset` is required for a TRAILING_STOP_MARKET stop-loss",
1714                )?;
1715                let trigger_price = required(
1716                    sl_trigger_price.or(sl_activation_price),
1717                    "TRAILING_STOP_MARKET stop-loss requires `sl_trigger_price` or `sl_activation_price`",
1718                )?;
1719                let order = TrailingStopMarketOrder::new_checked(
1720                    self.trader_id,
1721                    self.strategy_id,
1722                    instrument_id,
1723                    sl_client_order_id,
1724                    sl_tp_side,
1725                    quantity,
1726                    sl_activation_price,
1727                    Some(trigger_price),
1728                    sl_trigger_type,
1729                    sl_trailing_offset,
1730                    sl_trailing_offset_type,
1731                    sl_time_in_force,
1732                    None, // expire_time
1733                    sl_reduce_only,
1734                    quote_quantity,
1735                    None, // display_qty
1736                    emulation_trigger,
1737                    trigger_instrument_id,
1738                    sl_contingency_type,
1739                    sl_order_list_id,
1740                    sl_linked_order_ids,
1741                    sl_parent_order_id,
1742                    sl_exec_algorithm_id,
1743                    sl_exec_algorithm_params,
1744                    sl_exec_spawn_id,
1745                    sl_tags,
1746                    UUID4::new(),
1747                    ts_init,
1748                )?;
1749                OrderAny::TrailingStopMarket(order)
1750            }
1751            other => anyhow::bail!("invalid `sl_order_type`, was {other}"),
1752        };
1753
1754        Ok(vec![entry_order, sl_order, tp_order])
1755    }
1756}
1757
1758fn required<T>(value: Option<T>, message: &'static str) -> anyhow::Result<T> {
1759    value.ok_or_else(|| anyhow::anyhow!(message))
1760}
1761
1762#[cfg(test)]
1763pub mod tests {
1764    use std::{cell::RefCell, rc::Rc};
1765
1766    use indexmap::IndexMap;
1767    use nautilus_core::UnixNanos;
1768    use nautilus_model::{
1769        enums::{
1770            ContingencyType, OrderSide, OrderType, TimeInForce, TrailingOffsetType, TriggerType,
1771        },
1772        identifiers::{
1773            ClientOrderId, ExecAlgorithmId, InstrumentId, OrderListId,
1774            stubs::{strategy_id_ema_cross, trader_id},
1775        },
1776        orders::Order,
1777        types::Price,
1778    };
1779    use rstest::{fixture, rstest};
1780    use rust_decimal::Decimal;
1781    use ustr::Ustr;
1782
1783    use crate::{clock::VirtualClock, factories::OrderFactory};
1784
1785    #[fixture]
1786    pub fn order_factory() -> OrderFactory {
1787        let trader_id = trader_id();
1788        let strategy_id = strategy_id_ema_cross();
1789        let clock = Rc::new(RefCell::new(VirtualClock::new()));
1790        OrderFactory::new(
1791            trader_id,
1792            strategy_id,
1793            None,
1794            None,
1795            clock,
1796            false, // use_uuids_for_client_order_ids
1797            true,  // use_hyphens_in_client_order_ids
1798        )
1799    }
1800
1801    #[rstest]
1802    fn test_order_factory_identity(order_factory: OrderFactory) {
1803        assert_eq!(order_factory.trader_id(), trader_id());
1804        assert_eq!(order_factory.strategy_id(), strategy_id_ema_cross());
1805    }
1806
1807    #[rstest]
1808    fn test_generate_client_order_id(mut order_factory: OrderFactory) {
1809        let client_order_id = order_factory.generate_client_order_id();
1810        assert_eq!(
1811            client_order_id,
1812            ClientOrderId::new("O-19700101-000000-001-001-1")
1813        );
1814    }
1815
1816    #[rstest]
1817    fn test_generate_order_list_id(mut order_factory: OrderFactory) {
1818        let order_list_id = order_factory.generate_order_list_id();
1819        assert_eq!(
1820            order_list_id,
1821            OrderListId::new("OL-19700101-000000-001-001-1")
1822        );
1823    }
1824
1825    #[rstest]
1826    fn test_set_client_order_id_count(mut order_factory: OrderFactory) {
1827        order_factory.set_client_order_id_count(10);
1828        let client_order_id = order_factory.generate_client_order_id();
1829        assert_eq!(
1830            client_order_id,
1831            ClientOrderId::new("O-19700101-000000-001-001-11")
1832        );
1833    }
1834
1835    #[rstest]
1836    fn test_set_order_list_id_count(mut order_factory: OrderFactory) {
1837        order_factory.set_order_list_id_count(10);
1838        let order_list_id = order_factory.generate_order_list_id();
1839        assert_eq!(
1840            order_list_id,
1841            OrderListId::new("OL-19700101-000000-001-001-11")
1842        );
1843    }
1844
1845    #[rstest]
1846    fn test_reset_factory(mut order_factory: OrderFactory) {
1847        order_factory.generate_order_list_id();
1848        order_factory.generate_client_order_id();
1849        order_factory.reset_factory();
1850        let client_order_id = order_factory.generate_client_order_id();
1851        let order_list_id = order_factory.generate_order_list_id();
1852        assert_eq!(
1853            client_order_id,
1854            ClientOrderId::new("O-19700101-000000-001-001-1")
1855        );
1856        assert_eq!(
1857            order_list_id,
1858            OrderListId::new("OL-19700101-000000-001-001-1")
1859        );
1860    }
1861
1862    #[fixture]
1863    pub fn order_factory_with_uuids() -> OrderFactory {
1864        let trader_id = trader_id();
1865        let strategy_id = strategy_id_ema_cross();
1866        let clock = Rc::new(RefCell::new(VirtualClock::new()));
1867        OrderFactory::new(
1868            trader_id,
1869            strategy_id,
1870            None,
1871            None,
1872            clock,
1873            true, // use_uuids_for_client_order_ids
1874            true, // use_hyphens_in_client_order_ids
1875        )
1876    }
1877
1878    #[fixture]
1879    pub fn order_factory_with_hyphens_removed() -> OrderFactory {
1880        let trader_id = trader_id();
1881        let strategy_id = strategy_id_ema_cross();
1882        let clock = Rc::new(RefCell::new(VirtualClock::new()));
1883        OrderFactory::new(
1884            trader_id,
1885            strategy_id,
1886            None,
1887            None,
1888            clock,
1889            false, // use_uuids_for_client_order_ids
1890            false, // use_hyphens_in_client_order_ids
1891        )
1892    }
1893
1894    #[fixture]
1895    pub fn order_factory_with_uuids_and_hyphens_removed() -> OrderFactory {
1896        let trader_id = trader_id();
1897        let strategy_id = strategy_id_ema_cross();
1898        let clock = Rc::new(RefCell::new(VirtualClock::new()));
1899        OrderFactory::new(
1900            trader_id,
1901            strategy_id,
1902            None,
1903            None,
1904            clock,
1905            true,  // use_uuids_for_client_order_ids
1906            false, // use_hyphens_in_client_order_ids
1907        )
1908    }
1909
1910    #[rstest]
1911    fn test_generate_client_order_id_with_uuids(mut order_factory_with_uuids: OrderFactory) {
1912        let client_order_id = order_factory_with_uuids.generate_client_order_id();
1913
1914        // UUID should be 36 characters with hyphens
1915        assert_eq!(client_order_id.as_str().len(), 36);
1916        assert!(client_order_id.as_str().contains('-'));
1917    }
1918
1919    #[rstest]
1920    fn test_generate_client_order_id_with_hyphens_removed(
1921        mut order_factory_with_hyphens_removed: OrderFactory,
1922    ) {
1923        let client_order_id = order_factory_with_hyphens_removed.generate_client_order_id();
1924
1925        assert_eq!(
1926            client_order_id,
1927            ClientOrderId::new("O197001010000000010011")
1928        );
1929        assert!(!client_order_id.as_str().contains('-'));
1930    }
1931
1932    #[rstest]
1933    fn test_generate_client_order_id_with_uuids_and_hyphens_removed(
1934        mut order_factory_with_uuids_and_hyphens_removed: OrderFactory,
1935    ) {
1936        let client_order_id =
1937            order_factory_with_uuids_and_hyphens_removed.generate_client_order_id();
1938
1939        // UUID without hyphens should be 32 characters
1940        assert_eq!(client_order_id.as_str().len(), 32);
1941        assert!(!client_order_id.as_str().contains('-'));
1942    }
1943
1944    #[rstest]
1945    fn test_market_order(mut order_factory: OrderFactory) {
1946        let market_order = order_factory.market(
1947            InstrumentId::from("BTCUSDT.BINANCE"),
1948            OrderSide::Buy,
1949            100.into(),
1950            Some(TimeInForce::Gtc),
1951            Some(false),
1952            Some(false),
1953            None,
1954            None,
1955            None,
1956            None,
1957        );
1958        // TODO: Add additional polymorphic getters
1959        assert_eq!(market_order.instrument_id(), "BTCUSDT.BINANCE".into());
1960        assert_eq!(market_order.order_side(), OrderSide::Buy);
1961        assert_eq!(market_order.quantity(), 100.into());
1962        // assert_eq!(market_order.time_in_force(), TimeInForce::Gtc);
1963        // assert!(!market_order.is_reduce_only);
1964        // assert!(!market_order.is_quote_quantity);
1965        assert_eq!(market_order.exec_algorithm_id(), None);
1966        // assert_eq!(market_order.exec_algorithm_params(), None);
1967        // assert_eq!(market_order.exec_spawn_id, None);
1968        // assert_eq!(market_order.tags, None);
1969        assert_eq!(
1970            market_order.client_order_id(),
1971            ClientOrderId::new("O-19700101-000000-001-001-1")
1972        );
1973        // assert_eq!(market_order.order_list_id(), None);
1974    }
1975
1976    #[rstest]
1977    fn test_market_order_preserves_primary_exec_algorithm_metadata(
1978        mut order_factory: OrderFactory,
1979    ) {
1980        let client_order_id = ClientOrderId::from("O-PRIMARY");
1981        let exec_algorithm_id = ExecAlgorithmId::from("TWAP");
1982        let exec_algorithm_params =
1983            IndexMap::from([(Ustr::from("interval_secs"), Ustr::from("10"))]);
1984        let order = order_factory.market(
1985            InstrumentId::from("BTCUSDT.BINANCE"),
1986            OrderSide::Buy,
1987            100.into(),
1988            Some(TimeInForce::Gtc),
1989            Some(false),
1990            Some(false),
1991            Some(exec_algorithm_id),
1992            Some(exec_algorithm_params.clone()),
1993            None,
1994            Some(client_order_id),
1995        );
1996
1997        assert_eq!(order.client_order_id(), client_order_id);
1998        assert_eq!(order.exec_algorithm_id(), Some(exec_algorithm_id));
1999        assert_eq!(order.exec_algorithm_params(), Some(&exec_algorithm_params));
2000        assert_eq!(order.exec_spawn_id(), Some(client_order_id));
2001        assert!(order.is_primary());
2002        assert!(!order.is_spawned());
2003    }
2004
2005    #[rstest]
2006    fn test_limit_order(mut order_factory: OrderFactory) {
2007        let limit_order = order_factory.limit(
2008            InstrumentId::from("BTCUSDT.BINANCE"),
2009            OrderSide::Buy,
2010            100.into(),
2011            Price::from("50000.00"),
2012            Some(TimeInForce::Gtc),
2013            None,
2014            Some(false),
2015            Some(false),
2016            Some(false),
2017            None,
2018            None,
2019            None,
2020            None,
2021            None,
2022            None,
2023            None,
2024        );
2025
2026        assert_eq!(limit_order.instrument_id(), "BTCUSDT.BINANCE".into());
2027        assert_eq!(limit_order.order_side(), OrderSide::Buy);
2028        assert_eq!(limit_order.quantity(), 100.into());
2029        assert_eq!(limit_order.price(), Some(Price::from("50000.00")));
2030        assert_eq!(
2031            limit_order.client_order_id(),
2032            ClientOrderId::new("O-19700101-000000-001-001-1")
2033        );
2034    }
2035
2036    #[rstest]
2037    fn test_limit_order_with_post_only(mut order_factory: OrderFactory) {
2038        let limit_order = order_factory.limit(
2039            InstrumentId::from("BTCUSDT.BINANCE"),
2040            OrderSide::Buy,
2041            100.into(),
2042            Price::from("50000.00"),
2043            Some(TimeInForce::Gtc),
2044            None,
2045            Some(true), // post_only
2046            Some(false),
2047            Some(false),
2048            None,
2049            None,
2050            None,
2051            None,
2052            None,
2053            None,
2054            None,
2055        );
2056
2057        assert!(limit_order.is_post_only());
2058    }
2059
2060    #[rstest]
2061    fn test_limit_order_with_display_qty(mut order_factory: OrderFactory) {
2062        let limit_order = order_factory.limit(
2063            InstrumentId::from("BTCUSDT.BINANCE"),
2064            OrderSide::Buy,
2065            100.into(),
2066            Price::from("50000.00"),
2067            Some(TimeInForce::Gtc),
2068            None,
2069            Some(false),     // post_only
2070            Some(false),     // reduce_only
2071            Some(false),     // quote_quantity
2072            Some(50.into()), // display_qty
2073            None,
2074            None,
2075            None,
2076            None,
2077            None,
2078            None,
2079        );
2080
2081        assert_eq!(limit_order.display_qty(), Some(50.into()));
2082    }
2083
2084    #[rstest]
2085    fn test_stop_market_order(mut order_factory: OrderFactory) {
2086        let stop_order = order_factory.stop_market(
2087            InstrumentId::from("BTCUSDT.BINANCE"),
2088            OrderSide::Sell,
2089            100.into(),
2090            Price::from("45000.00"),
2091            Some(TriggerType::LastPrice),
2092            Some(TimeInForce::Gtc),
2093            None,
2094            Some(false),
2095            Some(false),
2096            None,
2097            None,
2098            None,
2099            None,
2100            None,
2101            None,
2102            None,
2103        );
2104
2105        assert_eq!(stop_order.instrument_id(), "BTCUSDT.BINANCE".into());
2106        assert_eq!(stop_order.order_side(), OrderSide::Sell);
2107        assert_eq!(stop_order.quantity(), 100.into());
2108        assert_eq!(stop_order.trigger_price(), Some(Price::from("45000.00")));
2109        assert_eq!(stop_order.trigger_type(), Some(TriggerType::LastPrice));
2110    }
2111
2112    #[rstest]
2113    fn test_stop_limit_order(mut order_factory: OrderFactory) {
2114        let stop_limit_order = order_factory.stop_limit(
2115            InstrumentId::from("BTCUSDT.BINANCE"),
2116            OrderSide::Sell,
2117            100.into(),
2118            Price::from("45100.00"), // limit price
2119            Price::from("45000.00"), // trigger price
2120            Some(TriggerType::LastPrice),
2121            Some(TimeInForce::Gtc),
2122            None,
2123            Some(false),
2124            Some(false),
2125            Some(false),
2126            None,
2127            None,
2128            None,
2129            None,
2130            None,
2131            None,
2132            None,
2133        );
2134
2135        assert_eq!(stop_limit_order.instrument_id(), "BTCUSDT.BINANCE".into());
2136        assert_eq!(stop_limit_order.order_side(), OrderSide::Sell);
2137        assert_eq!(stop_limit_order.quantity(), 100.into());
2138        assert_eq!(stop_limit_order.price(), Some(Price::from("45100.00")));
2139        assert_eq!(
2140            stop_limit_order.trigger_price(),
2141            Some(Price::from("45000.00"))
2142        );
2143        assert_eq!(
2144            stop_limit_order.trigger_type(),
2145            Some(TriggerType::LastPrice)
2146        );
2147    }
2148
2149    #[rstest]
2150    fn test_market_if_touched_order(mut order_factory: OrderFactory) {
2151        let mit_order = order_factory.market_if_touched(
2152            InstrumentId::from("BTCUSDT.BINANCE"),
2153            OrderSide::Buy,
2154            100.into(),
2155            Price::from("48000.00"),
2156            Some(TriggerType::LastPrice),
2157            Some(TimeInForce::Gtc),
2158            None,
2159            Some(false),
2160            Some(false),
2161            None,
2162            None,
2163            None,
2164            None,
2165            None,
2166            None,
2167        );
2168
2169        assert_eq!(mit_order.instrument_id(), "BTCUSDT.BINANCE".into());
2170        assert_eq!(mit_order.order_side(), OrderSide::Buy);
2171        assert_eq!(mit_order.quantity(), 100.into());
2172        assert_eq!(mit_order.trigger_price(), Some(Price::from("48000.00")));
2173        assert_eq!(mit_order.trigger_type(), Some(TriggerType::LastPrice));
2174    }
2175
2176    #[rstest]
2177    fn test_limit_if_touched_order(mut order_factory: OrderFactory) {
2178        let lit_order = order_factory.limit_if_touched(
2179            InstrumentId::from("BTCUSDT.BINANCE"),
2180            OrderSide::Buy,
2181            100.into(),
2182            Price::from("48100.00"), // limit price
2183            Price::from("48000.00"), // trigger price
2184            Some(TriggerType::LastPrice),
2185            Some(TimeInForce::Gtc),
2186            None,
2187            Some(false),
2188            Some(false),
2189            Some(false),
2190            None,
2191            None,
2192            None,
2193            None,
2194            None,
2195            None,
2196            None,
2197        );
2198
2199        assert_eq!(lit_order.instrument_id(), "BTCUSDT.BINANCE".into());
2200        assert_eq!(lit_order.order_side(), OrderSide::Buy);
2201        assert_eq!(lit_order.quantity(), 100.into());
2202        assert_eq!(lit_order.price(), Some(Price::from("48100.00")));
2203        assert_eq!(lit_order.trigger_price(), Some(Price::from("48000.00")));
2204        assert_eq!(lit_order.trigger_type(), Some(TriggerType::LastPrice));
2205    }
2206
2207    #[rstest]
2208    fn test_market_to_limit_order(mut order_factory: OrderFactory) {
2209        let mtl_order = order_factory.market_to_limit(
2210            InstrumentId::from("BTCUSDT.BINANCE"),
2211            OrderSide::Buy,
2212            100.into(),
2213            Some(TimeInForce::Gtc),
2214            None,
2215            Some(false),
2216            Some(false),
2217            None,
2218            None,
2219            None,
2220            None,
2221            None,
2222        );
2223
2224        assert_eq!(mtl_order.instrument_id(), "BTCUSDT.BINANCE".into());
2225        assert_eq!(mtl_order.order_side(), OrderSide::Buy);
2226        assert_eq!(mtl_order.quantity(), 100.into());
2227        assert_eq!(mtl_order.order_type(), OrderType::MarketToLimit);
2228        assert_eq!(
2229            mtl_order.client_order_id(),
2230            ClientOrderId::new("O-19700101-000000-001-001-1")
2231        );
2232    }
2233
2234    #[rstest]
2235    fn test_trailing_stop_limit_order(mut order_factory: OrderFactory) {
2236        let tsl_order = order_factory.trailing_stop_limit(
2237            InstrumentId::from("BTCUSDT.BINANCE"),
2238            OrderSide::Sell,
2239            100.into(),
2240            Some(Price::from("45100.00")), // limit price
2241            Decimal::new(10, 2),           // limit_offset
2242            Decimal::new(50, 2),           // trailing_offset
2243            Some(TrailingOffsetType::Price),
2244            Some(Price::from("45000.00")),
2245            Some(Price::from("45000.00")), // trigger_price
2246            Some(TriggerType::LastPrice),
2247            Some(TimeInForce::Gtc),
2248            None,
2249            Some(false), // post_only
2250            Some(true),  // reduce_only
2251            Some(false), // quote_quantity
2252            None,
2253            None,
2254            None,
2255            None,
2256            None,
2257            None,
2258            None,
2259        );
2260
2261        assert_eq!(tsl_order.instrument_id(), "BTCUSDT.BINANCE".into());
2262        assert_eq!(tsl_order.order_side(), OrderSide::Sell);
2263        assert_eq!(tsl_order.order_type(), OrderType::TrailingStopLimit);
2264        assert_eq!(tsl_order.price(), Some(Price::from("45100.00")));
2265        assert_eq!(tsl_order.activation_price(), Some(Price::from("45000.00")));
2266        assert_eq!(tsl_order.trigger_price(), Some(Price::from("45000.00")));
2267        assert_eq!(tsl_order.trigger_type(), Some(TriggerType::LastPrice));
2268        assert_eq!(tsl_order.trailing_offset(), Some(Decimal::new(50, 2)));
2269        assert_eq!(tsl_order.limit_offset(), Some(Decimal::new(10, 2)));
2270    }
2271
2272    #[rstest]
2273    fn test_bracket_order_with_market_entry(mut order_factory: OrderFactory) {
2274        let orders = order_factory
2275            .bracket()
2276            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2277            .order_side(OrderSide::Buy)
2278            .quantity(100.into())
2279            .tp_price(Price::from("55000.00"))
2280            .sl_trigger_price(Price::from("45000.00"))
2281            .call();
2282
2283        assert_eq!(orders.len(), 3);
2284        assert_eq!(orders[0].instrument_id(), "BTCUSDT.BINANCE".into());
2285
2286        // Entry should be market order
2287        assert_eq!(orders[0].order_side(), OrderSide::Buy);
2288
2289        // SL should be opposite side stop-market
2290        assert_eq!(orders[1].order_side(), OrderSide::Sell);
2291        assert_eq!(orders[1].trigger_price(), Some(Price::from("45000.00")));
2292
2293        // TP should be opposite side limit
2294        assert_eq!(orders[2].order_side(), OrderSide::Sell);
2295        assert_eq!(orders[2].price(), Some(Price::from("55000.00")));
2296    }
2297
2298    #[rstest]
2299    fn test_bracket_order_with_limit_entry(mut order_factory: OrderFactory) {
2300        let orders = order_factory
2301            .bracket()
2302            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2303            .order_side(OrderSide::Buy)
2304            .quantity(100.into())
2305            .entry_order_type(OrderType::Limit)
2306            .entry_price(Price::from("49000.00"))
2307            .tp_price(Price::from("55000.00"))
2308            .sl_trigger_price(Price::from("45000.00"))
2309            .call();
2310
2311        assert_eq!(orders.len(), 3);
2312        assert_eq!(orders[0].price(), Some(Price::from("49000.00")));
2313    }
2314
2315    #[rstest]
2316    fn test_bracket_order_with_stop_limit_entry(mut order_factory: OrderFactory) {
2317        let orders = order_factory
2318            .bracket()
2319            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2320            .order_side(OrderSide::Buy)
2321            .quantity(100.into())
2322            .entry_order_type(OrderType::StopLimit)
2323            .entry_price(Price::from("51500.00"))
2324            .entry_trigger_price(Price::from("51000.00"))
2325            .tp_price(Price::from("55000.00"))
2326            .sl_trigger_price(Price::from("45000.00"))
2327            .call();
2328
2329        assert_eq!(orders.len(), 3);
2330        assert_eq!(orders[0].trigger_price(), Some(Price::from("51000.00")));
2331        assert_eq!(orders[0].price(), Some(Price::from("51500.00")));
2332    }
2333
2334    #[rstest]
2335    fn test_bracket_order_sell_side(mut order_factory: OrderFactory) {
2336        let orders = order_factory
2337            .bracket()
2338            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2339            .order_side(OrderSide::Sell)
2340            .quantity(100.into())
2341            .entry_order_type(OrderType::Limit)
2342            .entry_price(Price::from("51000.00"))
2343            .tp_price(Price::from("45000.00"))
2344            .sl_trigger_price(Price::from("55000.00"))
2345            .call();
2346
2347        assert_eq!(orders.len(), 3);
2348        assert_eq!(orders[0].order_side(), OrderSide::Sell);
2349        assert_eq!(orders[1].order_side(), OrderSide::Buy);
2350        assert_eq!(orders[2].order_side(), OrderSide::Buy);
2351    }
2352
2353    #[rstest]
2354    fn test_bracket_order_sets_contingencies(mut order_factory: OrderFactory) {
2355        let orders = order_factory
2356            .bracket()
2357            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2358            .order_side(OrderSide::Buy)
2359            .quantity(100.into())
2360            .entry_order_type(OrderType::Limit)
2361            .entry_price(Price::from("50000.00"))
2362            .tp_price(Price::from("55000.00"))
2363            .sl_trigger_price(Price::from("45000.00"))
2364            .call();
2365
2366        let entry = &orders[0];
2367        let stop = &orders[1];
2368        let take = &orders[2];
2369
2370        let order_list_id = entry
2371            .order_list_id()
2372            .expect("Entry should have order_list_id");
2373        assert_eq!(entry.contingency_type(), Some(ContingencyType::Oto));
2374        assert_eq!(
2375            entry.linked_order_ids().unwrap(),
2376            &[stop.client_order_id(), take.client_order_id()]
2377        );
2378
2379        assert_eq!(stop.order_list_id(), Some(order_list_id));
2380        assert_eq!(stop.contingency_type(), Some(ContingencyType::Ouo));
2381        assert_eq!(stop.parent_order_id(), Some(entry.client_order_id()));
2382        assert_eq!(stop.linked_order_ids().unwrap(), &[take.client_order_id()]);
2383
2384        assert_eq!(take.order_list_id(), Some(order_list_id));
2385        assert_eq!(take.contingency_type(), Some(ContingencyType::Ouo));
2386        assert_eq!(take.parent_order_id(), Some(entry.client_order_id()));
2387        assert_eq!(take.linked_order_ids().unwrap(), &[stop.client_order_id()]);
2388    }
2389
2390    #[rstest]
2391    fn test_bracket_order_default_tags(mut order_factory: OrderFactory) {
2392        let orders = order_factory
2393            .bracket()
2394            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2395            .order_side(OrderSide::Buy)
2396            .quantity(100.into())
2397            .tp_price(Price::from("55000.00"))
2398            .sl_trigger_price(Price::from("45000.00"))
2399            .call();
2400
2401        assert_eq!(orders[0].tags(), Some(&vec![Ustr::from("ENTRY")][..]));
2402        assert_eq!(orders[1].tags(), Some(&vec![Ustr::from("STOP_LOSS")][..]));
2403        assert_eq!(orders[2].tags(), Some(&vec![Ustr::from("TAKE_PROFIT")][..]));
2404    }
2405
2406    #[rstest]
2407    fn test_bracket_order_custom_tags(mut order_factory: OrderFactory) {
2408        let orders = order_factory
2409            .bracket()
2410            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2411            .order_side(OrderSide::Buy)
2412            .quantity(100.into())
2413            .tp_price(Price::from("55000.00"))
2414            .sl_trigger_price(Price::from("45000.00"))
2415            .entry_tags(vec![Ustr::from("ALPHA"), Ustr::from("ENTRY-V2")])
2416            .tp_tags(vec![Ustr::from("TP-V2")])
2417            .sl_tags(vec![Ustr::from("SL-V2")])
2418            .call();
2419
2420        assert_eq!(
2421            orders[0].tags(),
2422            Some(&vec![Ustr::from("ALPHA"), Ustr::from("ENTRY-V2")][..])
2423        );
2424        assert_eq!(orders[1].tags(), Some(&vec![Ustr::from("SL-V2")][..]));
2425        assert_eq!(orders[2].tags(), Some(&vec![Ustr::from("TP-V2")][..]));
2426    }
2427
2428    #[rstest]
2429    fn test_bracket_order_custom_contingency_type(mut order_factory: OrderFactory) {
2430        let orders = order_factory
2431            .bracket()
2432            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2433            .order_side(OrderSide::Buy)
2434            .quantity(100.into())
2435            .contingency_type(ContingencyType::Oco)
2436            .tp_price(Price::from("55000.00"))
2437            .sl_trigger_price(Price::from("45000.00"))
2438            .call();
2439
2440        assert_eq!(orders[1].contingency_type(), Some(ContingencyType::Oco));
2441        assert_eq!(orders[2].contingency_type(), Some(ContingencyType::Oco));
2442    }
2443
2444    #[rstest]
2445    fn test_bracket_order_custom_client_order_ids(mut order_factory: OrderFactory) {
2446        let entry_id = ClientOrderId::new("CUSTOM-ENTRY");
2447        let tp_id = ClientOrderId::new("CUSTOM-TP");
2448        let sl_id = ClientOrderId::new("CUSTOM-SL");
2449
2450        let orders = order_factory
2451            .bracket()
2452            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2453            .order_side(OrderSide::Buy)
2454            .quantity(100.into())
2455            .tp_price(Price::from("55000.00"))
2456            .sl_trigger_price(Price::from("45000.00"))
2457            .entry_client_order_id(entry_id)
2458            .tp_client_order_id(tp_id)
2459            .sl_client_order_id(sl_id)
2460            .call();
2461
2462        assert_eq!(orders[0].client_order_id(), entry_id);
2463        assert_eq!(orders[1].client_order_id(), sl_id);
2464        assert_eq!(orders[2].client_order_id(), tp_id);
2465    }
2466
2467    #[rstest]
2468    fn test_bracket_order_per_leg_order_types(mut order_factory: OrderFactory) {
2469        let orders = order_factory
2470            .bracket()
2471            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2472            .order_side(OrderSide::Buy)
2473            .quantity(100.into())
2474            .entry_order_type(OrderType::Limit)
2475            .entry_price(Price::from("50000.00"))
2476            .tp_order_type(OrderType::MarketIfTouched)
2477            .tp_trigger_price(Price::from("55000.00"))
2478            .tp_trigger_type(TriggerType::LastPrice)
2479            .sl_order_type(OrderType::TrailingStopMarket)
2480            .sl_trigger_price(Price::from("45000.00"))
2481            .sl_activation_price(Price::from("44000.00"))
2482            .sl_trailing_offset(Decimal::new(50, 2))
2483            .sl_trailing_offset_type(TrailingOffsetType::BasisPoints)
2484            .call();
2485
2486        // Entry: limit
2487        assert_eq!(orders[0].order_type(), OrderType::Limit);
2488        // SL: trailing stop market with non-default offset type
2489        assert_eq!(orders[1].order_type(), OrderType::TrailingStopMarket);
2490        assert_eq!(orders[1].trigger_price(), Some(Price::from("45000.00")));
2491        assert_eq!(orders[1].activation_price(), Some(Price::from("44000.00")));
2492        assert_eq!(orders[1].trailing_offset(), Some(Decimal::new(50, 2)));
2493        assert_eq!(
2494            orders[1].trailing_offset_type(),
2495            Some(TrailingOffsetType::BasisPoints)
2496        );
2497        // TP: market-if-touched with non-default trigger type
2498        assert_eq!(orders[2].order_type(), OrderType::MarketIfTouched);
2499        assert_eq!(orders[2].trigger_price(), Some(Price::from("55000.00")));
2500        assert_eq!(orders[2].trigger_type(), Some(TriggerType::LastPrice));
2501    }
2502
2503    #[rstest]
2504    fn test_bracket_order_reduce_only_flags(mut order_factory: OrderFactory) {
2505        let orders = order_factory
2506            .bracket()
2507            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2508            .order_side(OrderSide::Buy)
2509            .quantity(100.into())
2510            .entry_order_type(OrderType::Limit)
2511            .entry_price(Price::from("50000.00"))
2512            .tp_price(Price::from("55000.00"))
2513            .sl_trigger_price(Price::from("45000.00"))
2514            .call();
2515
2516        assert!(!orders[0].is_reduce_only(), "entry must not be reduce-only");
2517        assert!(orders[1].is_reduce_only(), "SL must be reduce-only");
2518        assert!(orders[2].is_reduce_only(), "TP must be reduce-only");
2519    }
2520
2521    #[rstest]
2522    #[case::tp_disabled(false, true)]
2523    #[case::sl_disabled(true, false)]
2524    #[case::both_disabled(false, false)]
2525    #[case::both_enabled(true, true)]
2526    fn test_bracket_order_reduce_only_overrides(
2527        mut order_factory: OrderFactory,
2528        #[case] tp_reduce_only: bool,
2529        #[case] sl_reduce_only: bool,
2530    ) {
2531        let orders = order_factory
2532            .bracket()
2533            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2534            .order_side(OrderSide::Buy)
2535            .quantity(100.into())
2536            .entry_order_type(OrderType::Limit)
2537            .entry_price(Price::from("50000.00"))
2538            .tp_price(Price::from("55000.00"))
2539            .tp_reduce_only(tp_reduce_only)
2540            .sl_trigger_price(Price::from("45000.00"))
2541            .sl_reduce_only(sl_reduce_only)
2542            .call();
2543
2544        assert!(!orders[0].is_reduce_only(), "entry must not be reduce-only");
2545        assert_eq!(orders[1].is_reduce_only(), sl_reduce_only);
2546        assert_eq!(orders[2].is_reduce_only(), tp_reduce_only);
2547    }
2548
2549    #[rstest]
2550    #[case::limit(OrderType::Limit, Some("55000.00"), None, None, None, None)]
2551    #[case::limit_if_touched(
2552        OrderType::LimitIfTouched,
2553        Some("54500.00"),
2554        Some("55000.00"),
2555        None,
2556        None,
2557        None
2558    )]
2559    #[case::market_if_touched(OrderType::MarketIfTouched, None, Some("55000.00"), None, None, None)]
2560    #[case::trailing_stop_market(
2561        OrderType::TrailingStopMarket,
2562        None,
2563        Some("55000.00"),
2564        Some("54500.00"),
2565        Some(Decimal::new(75, 2)),
2566        None
2567    )]
2568    #[case::trailing_stop_limit(
2569        OrderType::TrailingStopLimit,
2570        Some("55000.00"),
2571        Some("54000.00"),
2572        Some("53500.00"),
2573        Some(Decimal::new(50, 2)),
2574        Some(Decimal::new(10, 2))
2575    )]
2576    fn test_bracket_order_tp_reduce_only_disabled_for_each_tp_order_type(
2577        mut order_factory: OrderFactory,
2578        #[case] tp_order_type: OrderType,
2579        #[case] tp_price: Option<&str>,
2580        #[case] tp_trigger_price: Option<&str>,
2581        #[case] tp_activation_price: Option<&str>,
2582        #[case] tp_trailing_offset: Option<Decimal>,
2583        #[case] tp_limit_offset: Option<Decimal>,
2584    ) {
2585        let orders = order_factory
2586            .bracket()
2587            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2588            .order_side(OrderSide::Buy)
2589            .quantity(100.into())
2590            .tp_order_type(tp_order_type)
2591            .maybe_tp_price(tp_price.map(Price::from))
2592            .maybe_tp_trigger_price(tp_trigger_price.map(Price::from))
2593            .maybe_tp_activation_price(tp_activation_price.map(Price::from))
2594            .maybe_tp_trailing_offset(tp_trailing_offset)
2595            .maybe_tp_limit_offset(tp_limit_offset)
2596            .tp_reduce_only(false)
2597            .sl_trigger_price(Price::from("45000.00"))
2598            .call();
2599
2600        assert_eq!(orders[2].order_type(), tp_order_type);
2601        assert!(!orders[2].is_reduce_only(), "TP must not be reduce-only");
2602        assert!(orders[1].is_reduce_only(), "SL must remain reduce-only");
2603    }
2604
2605    #[rstest]
2606    #[case::stop_market(OrderType::StopMarket, None, None)]
2607    #[case::trailing_stop_market(
2608        OrderType::TrailingStopMarket,
2609        Some("44000.00"),
2610        Some(Decimal::new(50, 2))
2611    )]
2612    fn test_bracket_order_sl_reduce_only_disabled_for_each_sl_order_type(
2613        mut order_factory: OrderFactory,
2614        #[case] sl_order_type: OrderType,
2615        #[case] sl_activation_price: Option<&str>,
2616        #[case] sl_trailing_offset: Option<Decimal>,
2617    ) {
2618        let orders = order_factory
2619            .bracket()
2620            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2621            .order_side(OrderSide::Buy)
2622            .quantity(100.into())
2623            .tp_price(Price::from("55000.00"))
2624            .sl_order_type(sl_order_type)
2625            .sl_trigger_price(Price::from("45000.00"))
2626            .maybe_sl_activation_price(sl_activation_price.map(Price::from))
2627            .maybe_sl_trailing_offset(sl_trailing_offset)
2628            .sl_reduce_only(false)
2629            .call();
2630
2631        assert_eq!(orders[1].order_type(), sl_order_type);
2632        assert!(!orders[1].is_reduce_only(), "SL must not be reduce-only");
2633        assert!(orders[2].is_reduce_only(), "TP must remain reduce-only");
2634    }
2635
2636    #[rstest]
2637    fn test_bracket_order_default_post_only(mut order_factory: OrderFactory) {
2638        let orders = order_factory
2639            .bracket()
2640            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2641            .order_side(OrderSide::Buy)
2642            .quantity(100.into())
2643            .entry_order_type(OrderType::Limit)
2644            .entry_price(Price::from("50000.00"))
2645            .tp_price(Price::from("55000.00"))
2646            .sl_trigger_price(Price::from("45000.00"))
2647            .call();
2648
2649        assert!(!orders[0].is_post_only(), "entry default is not post-only");
2650        assert!(orders[2].is_post_only(), "Limit TP default is post-only");
2651    }
2652
2653    #[rstest]
2654    fn test_bracket_order_trailing_stop_limit_tp_forces_no_post_only(
2655        mut order_factory: OrderFactory,
2656    ) {
2657        let orders = order_factory
2658            .bracket()
2659            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2660            .order_side(OrderSide::Buy)
2661            .quantity(100.into())
2662            .tp_order_type(OrderType::TrailingStopLimit)
2663            .tp_price(Price::from("55000.00"))
2664            .tp_trigger_price(Price::from("54000.00"))
2665            .tp_trailing_offset(Decimal::new(50, 2))
2666            .tp_limit_offset(Decimal::new(10, 2))
2667            .tp_post_only(true) // explicitly true; constructor must override to false
2668            .sl_trigger_price(Price::from("45000.00"))
2669            .call();
2670
2671        assert_eq!(orders[2].order_type(), OrderType::TrailingStopLimit);
2672        assert!(
2673            !orders[2].is_post_only(),
2674            "TRAILING_STOP_LIMIT TP must never be post-only"
2675        );
2676    }
2677
2678    #[rstest]
2679    fn test_bracket_order_expire_time_entry_only(mut order_factory: OrderFactory) {
2680        let expire_time = UnixNanos::from(1_700_000_000_000_000_000_u64);
2681        let orders = order_factory
2682            .bracket()
2683            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2684            .order_side(OrderSide::Buy)
2685            .quantity(100.into())
2686            .entry_order_type(OrderType::Limit)
2687            .entry_price(Price::from("50000.00"))
2688            .expire_time(expire_time)
2689            .time_in_force(TimeInForce::Gtd)
2690            .tp_price(Price::from("55000.00"))
2691            .sl_trigger_price(Price::from("45000.00"))
2692            .call();
2693
2694        assert_eq!(orders[0].expire_time(), Some(expire_time));
2695        assert_eq!(orders[1].expire_time(), None);
2696        assert_eq!(orders[2].expire_time(), None);
2697    }
2698
2699    #[rstest]
2700    fn test_bracket_order_with_market_if_touched_entry(mut order_factory: OrderFactory) {
2701        let orders = order_factory
2702            .bracket()
2703            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2704            .order_side(OrderSide::Buy)
2705            .quantity(100.into())
2706            .entry_order_type(OrderType::MarketIfTouched)
2707            .entry_trigger_price(Price::from("51000.00"))
2708            .tp_price(Price::from("55000.00"))
2709            .sl_trigger_price(Price::from("45000.00"))
2710            .call();
2711
2712        assert_eq!(orders[0].order_type(), OrderType::MarketIfTouched);
2713        assert_eq!(orders[0].trigger_price(), Some(Price::from("51000.00")));
2714    }
2715
2716    #[rstest]
2717    fn test_bracket_order_with_limit_if_touched_entry(mut order_factory: OrderFactory) {
2718        let orders = order_factory
2719            .bracket()
2720            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2721            .order_side(OrderSide::Buy)
2722            .quantity(100.into())
2723            .entry_order_type(OrderType::LimitIfTouched)
2724            .entry_price(Price::from("51500.00"))
2725            .entry_trigger_price(Price::from("51000.00"))
2726            .tp_price(Price::from("55000.00"))
2727            .sl_trigger_price(Price::from("45000.00"))
2728            .call();
2729
2730        assert_eq!(orders[0].order_type(), OrderType::LimitIfTouched);
2731        assert_eq!(orders[0].price(), Some(Price::from("51500.00")));
2732        assert_eq!(orders[0].trigger_price(), Some(Price::from("51000.00")));
2733    }
2734
2735    #[rstest]
2736    fn test_bracket_order_with_limit_if_touched_tp(mut order_factory: OrderFactory) {
2737        // BUY entry => SELL TP; SELL LimitIfTouched requires trigger_price >= price.
2738        let orders = order_factory
2739            .bracket()
2740            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2741            .order_side(OrderSide::Buy)
2742            .quantity(100.into())
2743            .tp_order_type(OrderType::LimitIfTouched)
2744            .tp_price(Price::from("54500.00"))
2745            .tp_trigger_price(Price::from("55000.00"))
2746            .sl_trigger_price(Price::from("45000.00"))
2747            .call();
2748
2749        assert_eq!(orders[2].order_type(), OrderType::LimitIfTouched);
2750        assert_eq!(orders[2].price(), Some(Price::from("54500.00")));
2751        assert_eq!(orders[2].trigger_price(), Some(Price::from("55000.00")));
2752        assert!(
2753            orders[2].is_post_only(),
2754            "LimitIfTouched TP default is post-only"
2755        );
2756    }
2757
2758    #[rstest]
2759    fn test_bracket_order_with_trailing_stop_market_tp(mut order_factory: OrderFactory) {
2760        let orders = order_factory
2761            .bracket()
2762            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2763            .order_side(OrderSide::Buy)
2764            .quantity(100.into())
2765            .tp_order_type(OrderType::TrailingStopMarket)
2766            .tp_trigger_price(Price::from("55000.00"))
2767            .tp_activation_price(Price::from("54500.00"))
2768            .tp_trailing_offset(Decimal::new(75, 2))
2769            .sl_trigger_price(Price::from("45000.00"))
2770            .call();
2771
2772        assert_eq!(orders[2].order_type(), OrderType::TrailingStopMarket);
2773        assert_eq!(orders[2].trigger_price(), Some(Price::from("55000.00")));
2774        assert_eq!(orders[2].activation_price(), Some(Price::from("54500.00")));
2775        assert_eq!(orders[2].trailing_offset(), Some(Decimal::new(75, 2)));
2776    }
2777
2778    #[rstest]
2779    fn test_bracket_order_with_trailing_stop_limit_tp(mut order_factory: OrderFactory) {
2780        let orders = order_factory
2781            .bracket()
2782            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2783            .order_side(OrderSide::Buy)
2784            .quantity(100.into())
2785            .tp_order_type(OrderType::TrailingStopLimit)
2786            .tp_price(Price::from("55000.00"))
2787            .tp_trigger_price(Price::from("54000.00"))
2788            .tp_activation_price(Price::from("53500.00"))
2789            .tp_trailing_offset(Decimal::new(50, 2))
2790            .tp_limit_offset(Decimal::new(10, 2))
2791            .sl_trigger_price(Price::from("45000.00"))
2792            .call();
2793
2794        assert_eq!(orders[2].order_type(), OrderType::TrailingStopLimit);
2795        assert_eq!(orders[2].price(), Some(Price::from("55000.00")));
2796        assert_eq!(orders[2].trigger_price(), Some(Price::from("54000.00")));
2797        assert_eq!(orders[2].activation_price(), Some(Price::from("53500.00")));
2798        assert_eq!(orders[2].trailing_offset(), Some(Decimal::new(50, 2)));
2799        assert_eq!(orders[2].limit_offset(), Some(Decimal::new(10, 2)));
2800    }
2801
2802    #[rstest]
2803    #[should_panic(expected = "`tp_price` is required for a LIMIT take-profit")]
2804    fn test_bracket_order_panics_on_missing_tp_price(mut order_factory: OrderFactory) {
2805        let _ = order_factory
2806            .bracket()
2807            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2808            .order_side(OrderSide::Buy)
2809            .quantity(100.into())
2810            .sl_trigger_price(Price::from("45000.00"))
2811            .call();
2812    }
2813
2814    #[rstest]
2815    #[should_panic(expected = "`sl_trigger_price` is required for a STOP_MARKET stop-loss")]
2816    fn test_bracket_order_panics_on_missing_sl_trigger_price(mut order_factory: OrderFactory) {
2817        let _ = order_factory
2818            .bracket()
2819            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2820            .order_side(OrderSide::Buy)
2821            .quantity(100.into())
2822            .tp_price(Price::from("55000.00"))
2823            .call();
2824    }
2825
2826    #[rstest]
2827    #[should_panic(
2828        expected = "`tp_trailing_offset` is required for a TRAILING_STOP_MARKET take-profit"
2829    )]
2830    fn test_bracket_order_panics_on_missing_tp_trailing_offset(mut order_factory: OrderFactory) {
2831        let _ = order_factory
2832            .bracket()
2833            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2834            .order_side(OrderSide::Buy)
2835            .quantity(100.into())
2836            .tp_order_type(OrderType::TrailingStopMarket)
2837            .tp_trigger_price(Price::from("55000.00"))
2838            .sl_trigger_price(Price::from("45000.00"))
2839            .call();
2840    }
2841
2842    #[rstest]
2843    #[should_panic(expected = "invalid `entry_order_type`")]
2844    fn test_bracket_order_panics_on_invalid_entry_order_type(mut order_factory: OrderFactory) {
2845        let _ = order_factory
2846            .bracket()
2847            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2848            .order_side(OrderSide::Buy)
2849            .quantity(100.into())
2850            .entry_order_type(OrderType::MarketToLimit)
2851            .tp_price(Price::from("55000.00"))
2852            .sl_trigger_price(Price::from("45000.00"))
2853            .call();
2854    }
2855
2856    #[rstest]
2857    #[should_panic(expected = "invalid `tp_order_type`")]
2858    fn test_bracket_order_panics_on_invalid_tp_order_type(mut order_factory: OrderFactory) {
2859        let _ = order_factory
2860            .bracket()
2861            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2862            .order_side(OrderSide::Buy)
2863            .quantity(100.into())
2864            .tp_order_type(OrderType::StopMarket)
2865            .tp_price(Price::from("55000.00"))
2866            .sl_trigger_price(Price::from("45000.00"))
2867            .call();
2868    }
2869
2870    #[rstest]
2871    #[should_panic(expected = "invalid `sl_order_type`")]
2872    fn test_bracket_order_panics_on_invalid_sl_order_type(mut order_factory: OrderFactory) {
2873        let _ = order_factory
2874            .bracket()
2875            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
2876            .order_side(OrderSide::Buy)
2877            .quantity(100.into())
2878            .sl_order_type(OrderType::Limit)
2879            .tp_price(Price::from("55000.00"))
2880            .sl_trigger_price(Price::from("45000.00"))
2881            .call();
2882    }
2883
2884    #[rstest]
2885    #[should_panic(expected = "share the same venue")]
2886    fn test_create_list_panics_on_mixed_venues(mut order_factory: OrderFactory) {
2887        let binance = order_factory.market(
2888            InstrumentId::from("BTCUSDT.BINANCE"),
2889            OrderSide::Buy,
2890            100.into(),
2891            None,
2892            None,
2893            None,
2894            None,
2895            None,
2896            None,
2897            None,
2898        );
2899        let bybit = order_factory.market(
2900            InstrumentId::from("BTCUSDT.BYBIT"),
2901            OrderSide::Buy,
2902            100.into(),
2903            None,
2904            None,
2905            None,
2906            None,
2907            None,
2908            None,
2909            None,
2910        );
2911
2912        let mut orders = vec![binance, bybit];
2913        let _ = order_factory.create_list(&mut orders, UnixNanos::default());
2914    }
2915
2916    #[rstest]
2917    fn test_create_list_from_plain_orders(mut order_factory: OrderFactory) {
2918        let entry = order_factory.limit(
2919            InstrumentId::from("BTCUSDT.BINANCE"),
2920            OrderSide::Buy,
2921            100.into(),
2922            Price::from("50000.00"),
2923            None,
2924            None,
2925            None,
2926            None,
2927            None,
2928            None,
2929            None,
2930            None,
2931            None,
2932            None,
2933            None,
2934            None,
2935        );
2936        let sl = order_factory.stop_market(
2937            InstrumentId::from("BTCUSDT.BINANCE"),
2938            OrderSide::Sell,
2939            100.into(),
2940            Price::from("45000.00"),
2941            None,
2942            None,
2943            None,
2944            None,
2945            None,
2946            None,
2947            None,
2948            None,
2949            None,
2950            None,
2951            None,
2952            None,
2953        );
2954
2955        let mut orders = vec![entry.clone(), sl.clone()];
2956        let order_list = order_factory.create_list(&mut orders, UnixNanos::default());
2957
2958        assert_eq!(order_list.len(), 2);
2959        assert_eq!(
2960            order_list.instrument_id,
2961            InstrumentId::from("BTCUSDT.BINANCE")
2962        );
2963        assert_eq!(order_list.client_order_ids[0], entry.client_order_id());
2964        assert_eq!(order_list.client_order_ids[1], sl.client_order_id());
2965        assert_eq!(
2966            order_list.id,
2967            OrderListId::new("OL-19700101-000000-001-001-1"),
2968        );
2969        assert_eq!(orders[0].order_list_id(), Some(order_list.id));
2970        assert_eq!(orders[1].order_list_id(), Some(order_list.id));
2971        assert_eq!(orders[0].init_event().order_list_id, Some(order_list.id));
2972        assert_eq!(orders[1].init_event().order_list_id, Some(order_list.id));
2973    }
2974}