Skip to main content

nautilus_trading/algorithm/
mod.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//! Execution algorithm infrastructure for order slicing and execution optimization.
17//!
18//! This module provides the [`ExecutionAlgorithm`] trait and supporting infrastructure
19//! for implementing algorithms like TWAP (Time-Weighted Average Price) and VWAP
20//! (Volume-Weighted Average Price) that slice large orders into smaller child orders.
21//!
22//! # Architecture
23//!
24//! Execution algorithms extend [`DataActor`] (not [`Strategy`](super::Strategy)) because:
25//! - They don't own positions (the parent Strategy does).
26//! - Spawned orders carry the parent Strategy's ID, not the algorithm's ID.
27//! - They act as order processors/transformers, not position managers.
28//!
29//! # Order Flow
30//!
31//! 1. A Strategy submits an order with `exec_algorithm_id` set.
32//! 2. The order is routed to the algorithm's `{id}.execute` endpoint.
33//! 3. The algorithm receives the order via `on_order()`.
34//! 4. The algorithm spawns child orders using `spawn_market()`, `spawn_limit()`, etc.
35//! 5. Spawned orders are submitted through the `RiskEngine`.
36//! 6. The algorithm receives fill events and manages remaining quantity.
37
38use std::fmt::Display;
39
40pub mod config;
41pub mod core;
42pub mod twap;
43
44pub use core::{ExecutionAlgorithmCore, ExecutionAlgorithmNative, StrategyEventHandlers};
45
46pub use config::{ExecutionAlgorithmConfig, ImportableExecutionAlgorithmConfig};
47use nautilus_common::{
48    actor::{DataActor, DataActorNative, registry::try_get_actor_unchecked},
49    enums::ComponentState,
50    logging::{CMD, EVT, RECV, SEND},
51    messages::execution::{CancelOrder, ModifyOrder, SubmitOrder, TradingCommand},
52    msgbus::{self, MessagingSwitchboard, TypedHandler},
53    timer::TimeEvent,
54};
55use nautilus_core::{UUID4, UnixNanos};
56use nautilus_model::{
57    enums::{OrderStatus, TimeInForce, TriggerType},
58    events::{
59        OrderAccepted, OrderCancelDenied, OrderCancelRejected, OrderCanceled, OrderDenied,
60        OrderEmulated, OrderEventAny, OrderExpired, OrderFillVoided, OrderFilled, OrderInitialized,
61        OrderModifyDenied, OrderModifyRejected, OrderPendingCancel, OrderPendingUpdate,
62        OrderRejected, OrderReleased, OrderSubmitted, OrderTriggered, OrderUpdated,
63        PositionChanged, PositionClosed, PositionEvent, PositionOpened,
64    },
65    identifiers::{
66        AccountId, ClientId, ClientOrderId, ExecAlgorithmId, PositionId, StrategyId, TraderId,
67    },
68    orders::{LimitOrder, MarketOrder, MarketToLimitOrder, Order, OrderAny, OrderError, OrderList},
69    types::{Price, Quantity, quantity::QuantityRaw},
70};
71pub use twap::{TwapAlgorithm, TwapAlgorithmConfig};
72use ustr::Ustr;
73
74use crate::algorithm::core::SpawnReduction;
75
76/// Core trait for implementing execution algorithms in NautilusTrader.
77///
78/// Execution algorithms are specialized [`DataActor`]s that receive orders from strategies
79/// and execute them by spawning child orders. They are used for order slicing algorithms
80/// like TWAP and VWAP.
81///
82/// # Key Capabilities
83///
84/// - All [`DataActor`] capabilities (data subscriptions, event handling, timers)
85/// - Order spawning (market, limit, market-to-limit)
86/// - Order lifecycle management (submit, modify, cancel)
87/// - Event filtering for algorithm-owned orders
88///
89/// When a reduced spawned order terminates with unfilled quantity, its reduction
90/// is restored in primary quantity units while the primary remains locally
91/// mutable. Submission handoff permanently ends restoration and late-fill
92/// re-deduction. A caller-held primary value remains reduced and must be
93/// discarded or refreshed from the cache before reuse.
94///
95/// # Implementation
96///
97/// Use the `nautilus_execution_algorithm!` macro to generate the native runtime
98/// wiring and `ExecutionAlgorithm` implementation, including the required
99/// `on_order()` method. Normal execution algorithm logic should call facade
100/// methods such as `submit_order()`, `spawn_market()`, and
101/// `unsubscribe_all_strategy_events()`. Native runtime code that needs the
102/// internal core should use [`ExecutionAlgorithmNative`].
103pub trait ExecutionAlgorithm: DataActor {
104    /// Returns the execution algorithm ID.
105    fn id(&self) -> ExecAlgorithmId
106    where
107        Self: ExecutionAlgorithmNative,
108    {
109        ExecutionAlgorithmNative::exec_algorithm_core(self).exec_algorithm_id
110    }
111
112    /// Executes a trading command.
113    ///
114    /// This is the main entry point for commands routed to the algorithm.
115    /// Dispatches to the appropriate handler based on command type.
116    ///
117    /// Commands are only processed when the algorithm is in `Running` state.
118    ///
119    /// # Errors
120    ///
121    /// Returns an error if command handling fails.
122    fn execute(&mut self, command: TradingCommand) -> anyhow::Result<()>
123    where
124        Self: ExecutionAlgorithmNative,
125        Self: 'static + std::fmt::Debug + Sized,
126    {
127        let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
128        if core.config.log_commands {
129            let id = &core.actor.actor_id;
130            log::info!("{id} {RECV}{CMD} {command}");
131        }
132
133        if DataActorNative::core(core).state() != ComponentState::Running {
134            return Ok(());
135        }
136
137        match command {
138            TradingCommand::SubmitOrder(cmd) => {
139                self.subscribe_to_strategy_events(cmd.strategy_id);
140                let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
141                core.remember_submit_params(cmd.client_order_id, cmd.params.clone());
142                let order = core.get_order(&cmd.client_order_id)?;
143                self.on_order(order)
144            }
145            TradingCommand::SubmitOrderList(cmd) => {
146                self.subscribe_to_strategy_events(cmd.strategy_id);
147                let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
148                for client_order_id in &cmd.order_list.client_order_ids {
149                    core.remember_submit_params(*client_order_id, cmd.params.clone());
150                }
151                let orders = core.get_orders_for_list(&cmd.order_list)?;
152                self.on_order_list(cmd.order_list, orders)
153            }
154            TradingCommand::ModifyOrder(cmd) => self.handle_modify_order(cmd),
155            TradingCommand::CancelOrder(cmd) => self.handle_cancel_order(cmd),
156            _ => {
157                log::warn!("Unhandled command type: {command}");
158                Ok(())
159            }
160        }
161    }
162
163    /// Called when a primary order is received for execution.
164    ///
165    /// Override this method to implement the algorithm's order slicing logic.
166    ///
167    /// # Errors
168    ///
169    /// Returns an error if order handling fails.
170    fn on_order(&mut self, order: OrderAny) -> anyhow::Result<()>;
171
172    /// Called when an order list is received for execution.
173    ///
174    /// Override this method to handle order lists. The default implementation
175    /// processes each order individually.
176    ///
177    /// # Errors
178    ///
179    /// Returns an error if order list handling fails.
180    fn on_order_list(
181        &mut self,
182        _order_list: OrderList,
183        orders: Vec<OrderAny>,
184    ) -> anyhow::Result<()> {
185        for order in orders {
186            self.on_order(order)?;
187        }
188        Ok(())
189    }
190
191    /// Denies an order by applying and publishing an `OrderDenied` event.
192    ///
193    /// An order absent from the cache is added first, with its `OrderInitialized` event published
194    /// before the denial. A closed cached order is left unchanged. Use an `OrderDeniedReason`
195    /// string for the standardized reason.
196    ///
197    /// # Errors
198    ///
199    /// Returns an error if:
200    /// - The algorithm is not registered with a trader.
201    /// - The order cannot be added to the cache.
202    /// - The denial cannot be applied, including an invalid order state transition.
203    ///
204    /// No event is published when the denial cannot be applied.
205    fn deny_order(&mut self, order: &OrderAny, reason: Ustr) -> anyhow::Result<()>
206    where
207        Self: ExecutionAlgorithmNative,
208    {
209        let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
210        registered_trader_id(core)?;
211        let ts_now = core.clock_mut().timestamp_ns();
212        let event = OrderEventAny::Denied(OrderDenied::new(
213            order.trader_id(),
214            order.strategy_id(),
215            order.instrument_id(),
216            order.client_order_id(),
217            reason,
218            UUID4::new(),
219            ts_now,
220            ts_now,
221        ));
222
223        let publish_initialized = {
224            let cache_rc = core.cache_rc();
225            let mut cache = cache_rc.borrow_mut();
226
227            if cache
228                .order(&order.client_order_id())
229                .is_some_and(|cached_order| cached_order.is_closed())
230            {
231                return Ok(());
232            }
233
234            let publish_initialized = if cache.order_exists(&order.client_order_id()) {
235                false
236            } else {
237                cache.add_order(order.clone(), None, None, false)?;
238                true
239            };
240
241            cache.update_order(&event)?;
242            publish_initialized
243        };
244
245        if publish_initialized {
246            publish_order_initialized(order);
247        }
248        publish_order_event(&event);
249
250        // A denied order never executes, so its stored submit params are dropped here
251        // rather than waiting for an execution completion that will never arrive.
252        ExecutionAlgorithmNative::exec_algorithm_core_mut(self)
253            .remove_submit_params(&order.client_order_id());
254
255        Ok(())
256    }
257
258    /// Handles a cancel order command for algorithm-managed orders.
259    ///
260    /// This generates an internal cancel event and publishes it. The order
261    /// is canceled locally without sending a command to the execution engine.
262    /// Unknown or closed orders produce `OrderCancelDenied`.
263    ///
264    /// # Errors
265    ///
266    /// Returns an error if cancellation fails.
267    fn handle_cancel_order(&mut self, command: CancelOrder) -> anyhow::Result<()>
268    where
269        Self: ExecutionAlgorithmNative,
270    {
271        let (order, is_pending_cancel) = {
272            let cache = ExecutionAlgorithmNative::exec_algorithm_core_mut(self).cache_ref();
273            (
274                cache
275                    .order(&command.client_order_id)
276                    .map(|order| order.clone()),
277                cache.is_order_pending_cancel_local(&command.client_order_id),
278            )
279        };
280
281        let Some(order) = order else {
282            return deny_cancel_command(
283                ExecutionAlgorithmNative::exec_algorithm_core_mut(self),
284                &command,
285                "Order not found in cache",
286            );
287        };
288
289        if is_pending_cancel {
290            return Ok(());
291        }
292
293        if order.is_closed() {
294            return deny_cancel_command(
295                ExecutionAlgorithmNative::exec_algorithm_core_mut(self),
296                &command,
297                "Order already closed",
298            );
299        }
300
301        let event = OrderEventAny::Canceled(self.generate_order_canceled(&order));
302
303        let order = {
304            let cache_rc = ExecutionAlgorithmNative::exec_algorithm_core_mut(self).cache_rc();
305            let mut cache = cache_rc.borrow_mut();
306            match cache.update_order(&event) {
307                Ok(order) => order,
308                Err(e)
309                    if matches!(
310                        e.downcast_ref::<OrderError>(),
311                        Some(OrderError::InvalidStateTransition)
312                    ) =>
313                {
314                    log::warn!("InvalidStateTrigger: {e}, did not apply cancel event");
315                    return Ok(());
316                }
317                Err(e) => return Err(e),
318            }
319        };
320
321        let topic = format!("events.order.{}", order.strategy_id());
322        msgbus::publish_order_event(topic.into(), &event);
323        msgbus::publish_order_event(
324            msgbus::switchboard::get_order_canceled_topic(order.instrument_id()),
325            &event,
326        );
327
328        Ok(())
329    }
330
331    /// Handles a modify order command for algorithm-managed orders.
332    ///
333    /// Active-local orders are left unchanged because the algorithm owns their execution state.
334    ///
335    /// # Errors
336    ///
337    /// Returns an error if command handling fails.
338    fn handle_modify_order(&mut self, command: ModifyOrder) -> anyhow::Result<()>
339    where
340        Self: ExecutionAlgorithmNative,
341    {
342        let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
343
344        let reason = {
345            let cache = core.cache_ref();
346            match cache.order(&command.client_order_id) {
347                None => "Order not found in cache",
348                Some(order) if order.is_closed() => "Order already closed",
349                Some(order) if order.is_active_local() => {
350                    "Order is being executed by this algorithm"
351                }
352                Some(_) => "Order is not active-local",
353            }
354        };
355
356        deny_modify_command(core, &command, reason)
357    }
358
359    /// Generates an `OrderCanceled` event for an order.
360    fn generate_order_canceled(&mut self, order: &OrderAny) -> OrderCanceled
361    where
362        Self: ExecutionAlgorithmNative,
363    {
364        let ts_now = ExecutionAlgorithmNative::exec_algorithm_core_mut(self)
365            .clock_mut()
366            .timestamp_ns();
367
368        OrderCanceled::new(
369            order.trader_id(),
370            order.strategy_id(),
371            order.instrument_id(),
372            order.client_order_id(),
373            UUID4::new(),
374            ts_now,
375            ts_now,
376            false, // reconciliation
377            order.venue_order_id(),
378            order.account_id(),
379            None,
380        )
381    }
382
383    /// Generates an `OrderPendingUpdate` event for an order.
384    fn generate_order_pending_update(
385        &mut self,
386        order: &OrderAny,
387        command_id: UUID4,
388    ) -> OrderPendingUpdate
389    where
390        Self: ExecutionAlgorithmNative,
391    {
392        let ts_now = ExecutionAlgorithmNative::exec_algorithm_core_mut(self)
393            .clock_mut()
394            .timestamp_ns();
395
396        let mut event = OrderPendingUpdate::new(
397            order.trader_id(),
398            order.strategy_id(),
399            order.instrument_id(),
400            order.client_order_id(),
401            order.account_id(),
402            UUID4::new(),
403            ts_now,
404            ts_now,
405            false, // reconciliation
406            order.venue_order_id(),
407        );
408        event.causation_id = Some(command_id);
409        event
410    }
411
412    /// Generates an `OrderPendingCancel` event for an order.
413    fn generate_order_pending_cancel(
414        &mut self,
415        order: &OrderAny,
416        command_id: UUID4,
417    ) -> OrderPendingCancel
418    where
419        Self: ExecutionAlgorithmNative,
420    {
421        let ts_now = ExecutionAlgorithmNative::exec_algorithm_core_mut(self)
422            .clock_mut()
423            .timestamp_ns();
424
425        let mut event = OrderPendingCancel::new(
426            order.trader_id(),
427            order.strategy_id(),
428            order.instrument_id(),
429            order.client_order_id(),
430            order.account_id(),
431            UUID4::new(),
432            ts_now,
433            ts_now,
434            false, // reconciliation
435            order.venue_order_id(),
436        );
437        event.causation_id = Some(command_id);
438        event
439    }
440
441    /// Spawns a market order from a primary order.
442    ///
443    /// Creates a new market order with:
444    /// - A unique client order ID: `{primary_id}-E{sequence}`.
445    /// - The primary order's trader ID, strategy ID, and instrument ID.
446    /// - The algorithm's `exec_algorithm_id`.
447    /// - `exec_spawn_id` set to the primary order's client order ID.
448    ///
449    /// If `reduce_primary` is true, the primary order's quantity is reduced by
450    /// the spawned quantity. Unfilled quantity is restored when the spawn is
451    /// denied, rejected, canceled, expired, or refused before submission while
452    /// the primary remains locally mutable. Converted quote-quantity spawns are
453    /// restored proportionally in primary units. Late fills re-deduct restored
454    /// quantity until primary submission is handed off.
455    ///
456    /// # Errors
457    ///
458    /// Returns an error if the spawned order parameters are invalid. Failed
459    /// construction leaves primary quantity and pending spawn reductions unchanged.
460    fn spawn_market(
461        &mut self,
462        primary: &mut OrderAny,
463        quantity: Quantity,
464        time_in_force: TimeInForce,
465        reduce_only: bool,
466        tags: Option<Vec<Ustr>>,
467        reduce_primary: bool,
468    ) -> Result<MarketOrder, OrderError>
469    where
470        Self: ExecutionAlgorithmNative,
471    {
472        let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
473        let client_order_id = core.spawn_client_order_id(&primary.client_order_id());
474        let ts_init = core.clock_mut().timestamp_ns();
475        let exec_algorithm_id = core.exec_algorithm_id;
476
477        let spawned = MarketOrder::new_checked(
478            primary.trader_id(),
479            primary.strategy_id(),
480            primary.instrument_id(),
481            client_order_id,
482            primary.order_side(),
483            quantity,
484            time_in_force,
485            UUID4::new(),
486            ts_init,
487            reduce_only,
488            primary.is_quote_quantity(),
489            primary.contingency_type(),
490            primary.order_list_id(),
491            primary.linked_order_ids().map(<[ClientOrderId]>::to_vec),
492            primary.parent_order_id(),
493            Some(exec_algorithm_id),
494            primary.exec_algorithm_params().cloned(),
495            Some(primary.client_order_id()),
496            tags.or_else(|| primary.tags().map(<[Ustr]>::to_vec)),
497        )?;
498
499        if reduce_primary {
500            self.reduce_primary_order(primary, quantity);
501            ExecutionAlgorithmNative::exec_algorithm_core_mut(self).track_pending_spawn_reduction(
502                client_order_id,
503                primary.client_order_id(),
504                quantity,
505                primary.is_quote_quantity(),
506            );
507        }
508
509        Ok(spawned)
510    }
511
512    /// Spawns a limit order from a primary order.
513    ///
514    /// Creates a new limit order with:
515    /// - A unique client order ID: `{primary_id}-E{sequence}`
516    /// - The primary order's trader ID, strategy ID, and instrument ID
517    /// - The algorithm's `exec_algorithm_id`
518    /// - `exec_spawn_id` set to the primary order's client order ID
519    ///
520    /// `submit_order` refuses the returned order when `emulation_trigger` is
521    /// `Some`; use `None` for an order that the execution algorithm will submit.
522    ///
523    /// If `reduce_primary` is true, the primary order's quantity is reduced by
524    /// the spawned quantity. Unfilled quantity is restored when the spawn is
525    /// denied, rejected, canceled, expired, or refused before submission while
526    /// the primary remains locally mutable. Converted quote-quantity spawns are
527    /// restored proportionally in primary units. Late fills re-deduct restored
528    /// quantity until primary submission is handed off.
529    ///
530    /// # Errors
531    ///
532    /// Returns an error if the spawned order parameters are invalid. Failed
533    /// construction leaves primary quantity and pending spawn reductions unchanged.
534    #[expect(clippy::too_many_arguments)]
535    fn spawn_limit(
536        &mut self,
537        primary: &mut OrderAny,
538        quantity: Quantity,
539        price: Price,
540        time_in_force: TimeInForce,
541        expire_time: Option<UnixNanos>,
542        post_only: bool,
543        reduce_only: bool,
544        display_qty: Option<Quantity>,
545        emulation_trigger: Option<TriggerType>,
546        tags: Option<Vec<Ustr>>,
547        reduce_primary: bool,
548    ) -> Result<LimitOrder, OrderError>
549    where
550        Self: ExecutionAlgorithmNative,
551    {
552        let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
553        let client_order_id = core.spawn_client_order_id(&primary.client_order_id());
554        let ts_init = core.clock_mut().timestamp_ns();
555        let exec_algorithm_id = core.exec_algorithm_id;
556
557        let spawned = LimitOrder::new_checked(
558            primary.trader_id(),
559            primary.strategy_id(),
560            primary.instrument_id(),
561            client_order_id,
562            primary.order_side(),
563            quantity,
564            price,
565            time_in_force,
566            expire_time,
567            post_only,
568            reduce_only,
569            primary.is_quote_quantity(),
570            display_qty,
571            emulation_trigger,
572            None, // trigger_instrument_id
573            primary.contingency_type(),
574            primary.order_list_id(),
575            primary.linked_order_ids().map(<[ClientOrderId]>::to_vec),
576            primary.parent_order_id(),
577            Some(exec_algorithm_id),
578            primary.exec_algorithm_params().cloned(),
579            Some(primary.client_order_id()),
580            tags.or_else(|| primary.tags().map(<[Ustr]>::to_vec)),
581            UUID4::new(),
582            ts_init,
583        )?;
584
585        if reduce_primary {
586            self.reduce_primary_order(primary, quantity);
587            ExecutionAlgorithmNative::exec_algorithm_core_mut(self).track_pending_spawn_reduction(
588                client_order_id,
589                primary.client_order_id(),
590                quantity,
591                primary.is_quote_quantity(),
592            );
593        }
594
595        Ok(spawned)
596    }
597
598    /// Spawns a market-to-limit order from a primary order.
599    ///
600    /// Creates a new market-to-limit order with:
601    /// - A unique client order ID: `{primary_id}-E{sequence}`
602    /// - The primary order's trader ID, strategy ID, and instrument ID
603    /// - The algorithm's `exec_algorithm_id`
604    /// - `exec_spawn_id` set to the primary order's client order ID
605    ///
606    /// If `reduce_primary` is true, the primary order's quantity is reduced by
607    /// the spawned quantity. Unfilled quantity is restored when the spawn is
608    /// denied, rejected, canceled, expired, or refused before submission while
609    /// the primary remains locally mutable. Converted quote-quantity spawns are
610    /// restored proportionally in primary units. Late fills re-deduct restored
611    /// quantity until primary submission is handed off.
612    ///
613    /// `_emulation_trigger` is accepted for signature parity and is not applied:
614    /// a `MARKET_TO_LIMIT` order is always initialized with no emulation trigger
615    /// and cannot be emulated.
616    ///
617    /// # Errors
618    ///
619    /// Returns an error if the spawned order parameters are invalid. Failed
620    /// construction leaves primary quantity and pending spawn reductions unchanged.
621    #[expect(clippy::too_many_arguments)]
622    fn spawn_market_to_limit(
623        &mut self,
624        primary: &mut OrderAny,
625        quantity: Quantity,
626        time_in_force: TimeInForce,
627        expire_time: Option<UnixNanos>,
628        reduce_only: bool,
629        display_qty: Option<Quantity>,
630        _emulation_trigger: Option<TriggerType>,
631        tags: Option<Vec<Ustr>>,
632        reduce_primary: bool,
633    ) -> Result<MarketToLimitOrder, OrderError>
634    where
635        Self: ExecutionAlgorithmNative,
636    {
637        let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
638        let client_order_id = core.spawn_client_order_id(&primary.client_order_id());
639        let ts_init = core.clock_mut().timestamp_ns();
640        let exec_algorithm_id = core.exec_algorithm_id;
641
642        let spawned = MarketToLimitOrder::new_checked(
643            primary.trader_id(),
644            primary.strategy_id(),
645            primary.instrument_id(),
646            client_order_id,
647            primary.order_side(),
648            quantity,
649            time_in_force,
650            expire_time,
651            false, // post_only
652            reduce_only,
653            primary.is_quote_quantity(),
654            display_qty,
655            primary.contingency_type(),
656            primary.order_list_id(),
657            primary.linked_order_ids().map(<[ClientOrderId]>::to_vec),
658            primary.parent_order_id(),
659            Some(exec_algorithm_id),
660            primary.exec_algorithm_params().cloned(),
661            Some(primary.client_order_id()),
662            tags.or_else(|| primary.tags().map(<[Ustr]>::to_vec)),
663            UUID4::new(),
664            ts_init,
665        )?;
666
667        if reduce_primary {
668            self.reduce_primary_order(primary, quantity);
669            ExecutionAlgorithmNative::exec_algorithm_core_mut(self).track_pending_spawn_reduction(
670                client_order_id,
671                primary.client_order_id(),
672                quantity,
673                primary.is_quote_quantity(),
674            );
675        }
676
677        Ok(spawned)
678    }
679
680    /// Reduces the primary order's quantity by the spawn quantity.
681    ///
682    /// Generates an `OrderUpdated` event and applies it to the primary order,
683    /// then updates the order in the cache.
684    ///
685    /// # Panics
686    ///
687    /// Panics if `spawn_qty` exceeds the primary order's `leaves_qty`.
688    fn reduce_primary_order(&mut self, primary: &mut OrderAny, spawn_qty: Quantity)
689    where
690        Self: ExecutionAlgorithmNative,
691    {
692        let leaves_qty = primary.leaves_qty();
693        assert!(
694            leaves_qty >= spawn_qty,
695            "Spawn quantity {spawn_qty} exceeds primary leaves_qty {leaves_qty}"
696        );
697
698        let primary_qty = primary.quantity();
699        let mut new_qty = primary_qty - spawn_qty;
700        new_qty.precision = primary_qty.precision;
701
702        let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
703        let ts_now = core.clock_mut().timestamp_ns();
704
705        let updated = OrderUpdated::new(
706            primary.trader_id(),
707            primary.strategy_id(),
708            primary.instrument_id(),
709            primary.client_order_id(),
710            new_qty,
711            UUID4::new(),
712            ts_now,
713            ts_now,
714            false, // reconciliation
715            primary.venue_order_id(),
716            primary.account_id(),
717            None, // price
718            None, // trigger_price
719            None, // protection_price
720            primary.is_quote_quantity(),
721        );
722
723        let event = OrderEventAny::Updated(updated);
724
725        {
726            let cache_rc = core.cache_rc();
727            let mut cache = cache_rc.borrow_mut();
728            *primary = cache
729                .update_order(&event)
730                .expect("Failed to update order in cache");
731        }
732
733        publish_order_event(&event);
734    }
735
736    /// Restores a spawn reduction while the cached primary order remains local.
737    ///
738    /// The quantity deducted from the cached primary order is restored up to the
739    /// spawned order's unfilled proportion in primary units. Tracked fill voids
740    /// return only the additional budget released by the correction. Primaries handed
741    /// off for submission retain their committed quantity. Uncompensated
742    /// late-fill debt on the primary is discharged before quantity is returned.
743    ///
744    /// `refused_before_submission` selects whether the restoration log records a
745    /// refusal or an order update.
746    fn restore_primary_order_quantity(&mut self, order: &OrderAny, refused_before_submission: bool)
747    where
748        Self: ExecutionAlgorithmNative,
749    {
750        let Some(exec_spawn_id) = order.exec_spawn_id() else {
751            return;
752        };
753
754        let reduction = {
755            let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
756            core.spawn_reduction(order.client_order_id())
757        };
758
759        let Some(mut reduction) = reduction else {
760            return;
761        };
762
763        let primary = {
764            let cache = ExecutionAlgorithmNative::exec_algorithm_core_mut(self).cache_ref();
765            cache
766                .order(&exec_spawn_id)
767                .map(|o| <OrderAny as Clone>::clone(&o))
768        };
769
770        let Some(primary) = primary else {
771            ExecutionAlgorithmNative::exec_algorithm_core_mut(self)
772                .take_pending_spawn_reduction(order.client_order_id());
773            log::warn!(
774                "Cannot restore primary order quantity: primary order {exec_spawn_id} not found",
775            );
776            return;
777        };
778
779        let handed_off = ExecutionAlgorithmNative::exec_algorithm_core_mut(self)
780            .primary_was_handed_off(exec_spawn_id);
781
782        if !primary.is_active_local() || handed_off {
783            let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
784            core.take_pending_spawn_reduction(order.client_order_id());
785            core.discard_spawn_fill_debt(exec_spawn_id);
786            log::info!(
787                "Skipped restoring primary order {exec_spawn_id} after spawned order {}: primary is no longer locally mutable",
788                order.client_order_id(),
789            );
790            return;
791        }
792
793        let Some(unfilled_qty) =
794            spawn_unfilled_quantity(order, reduction, primary.quantity().precision)
795        else {
796            ExecutionAlgorithmNative::exec_algorithm_core_mut(self)
797                .take_pending_spawn_reduction(order.client_order_id());
798            return;
799        };
800        let restored_qty = reduction
801            .restored_qty
802            .unwrap_or_else(|| Quantity::zero(unfilled_qty.precision));
803        let restore_qty = unfilled_qty.saturating_sub(restored_qty);
804        reduction.restored_qty = Some(unfilled_qty);
805
806        if restore_qty.is_zero() {
807            ExecutionAlgorithmNative::exec_algorithm_core_mut(self)
808                .set_spawn_reduction(order.client_order_id(), reduction);
809            return;
810        }
811
812        // Discharge uncompensated late-fill debt on this primary before
813        // returning quantity to it
814        let debt_qty = ExecutionAlgorithmNative::exec_algorithm_core_mut(self)
815            .spawn_fill_debt(exec_spawn_id)
816            .unwrap_or_else(|| Quantity::zero(restore_qty.precision));
817        let discharge_qty = restore_qty.min(debt_qty);
818        let net_restore_qty = restore_qty - discharge_qty;
819
820        if net_restore_qty.is_zero() {
821            // The whole restoration discharged debt: keep the record with the
822            // gross released amount so this child's own late fills stay tracked
823            let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
824            core.set_spawn_reduction(order.client_order_id(), reduction);
825            core.set_spawn_fill_debt(exec_spawn_id, debt_qty - discharge_qty);
826            log::info!(
827                "Restoration from spawned order {} fully discharged late-fill debt on primary order {exec_spawn_id}",
828                order.client_order_id(),
829            );
830            return;
831        }
832
833        let mut restored_qty = primary.quantity() + net_restore_qty;
834        restored_qty.precision = primary.quantity().precision;
835
836        let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
837        let ts_now = core.clock_mut().timestamp_ns();
838
839        let updated = OrderUpdated::new(
840            primary.trader_id(),
841            primary.strategy_id(),
842            primary.instrument_id(),
843            primary.client_order_id(),
844            restored_qty,
845            UUID4::new(),
846            ts_now,
847            ts_now,
848            false, // reconciliation
849            primary.venue_order_id(),
850            primary.account_id(),
851            None, // price
852            None, // trigger_price
853            None, // protection_price
854            primary.is_quote_quantity(),
855        );
856
857        let event = OrderEventAny::Updated(updated);
858
859        let primary = {
860            let cache_rc = core.cache_rc();
861            let mut cache = cache_rc.borrow_mut();
862            match cache.update_order(&event) {
863                Ok(primary) => primary,
864                Err(e) => {
865                    log::warn!("Failed to update primary order in cache: {e}");
866                    return;
867                }
868            }
869        };
870
871        // Commit the lifecycle record and debt before publishing: subscribers
872        // run synchronously and may re-enter order handling. The record keeps
873        // the gross released amount (including the debt-discharged portion) as
874        // this child's late-fill accounting budget; only the net reaches the
875        // primary.
876        let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
877        core.set_spawn_reduction(order.client_order_id(), reduction);
878        if !discharge_qty.is_zero() {
879            core.set_spawn_fill_debt(exec_spawn_id, debt_qty - discharge_qty);
880        }
881
882        publish_order_event(&event);
883
884        let outcome = if refused_before_submission {
885            "refused before submission"
886        } else {
887            "updated with unfilled quantity"
888        };
889        log::info!(
890            "Restored primary order {} quantity to {} after spawned order {} was {outcome}",
891            primary.client_order_id(),
892            restored_qty,
893            order.client_order_id()
894        );
895    }
896
897    /// Re-deducts a late spawn fill from a previously restored local primary order.
898    fn rededuct_late_spawn_fill(&mut self, order: &OrderAny)
899    where
900        Self: ExecutionAlgorithmNative,
901    {
902        let spawn_id = order.client_order_id();
903        let Some(exec_spawn_id) = order.exec_spawn_id() else {
904            return;
905        };
906        let Some(reduction) =
907            ExecutionAlgorithmNative::exec_algorithm_core_mut(self).spawn_reduction(spawn_id)
908        else {
909            return;
910        };
911
912        let Some(restored_qty) = reduction.restored_qty else {
913            return;
914        };
915
916        let primary = {
917            let cache = ExecutionAlgorithmNative::exec_algorithm_core_mut(self).cache_ref();
918            cache
919                .order(&exec_spawn_id)
920                .map(|o| <OrderAny as Clone>::clone(&o))
921        };
922        let Some(primary) = primary else {
923            ExecutionAlgorithmNative::exec_algorithm_core_mut(self)
924                .take_pending_spawn_reduction(spawn_id);
925            log::warn!(
926                "Cannot re-deduct late fill from primary order {exec_spawn_id}: order not found",
927            );
928            return;
929        };
930
931        let handed_off = ExecutionAlgorithmNative::exec_algorithm_core_mut(self)
932            .primary_was_handed_off(exec_spawn_id);
933
934        if !primary.is_active_local() || handed_off {
935            let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
936            core.take_pending_spawn_reduction(spawn_id);
937            core.discard_spawn_fill_debt(exec_spawn_id);
938            log::info!(
939                "Skipped re-deducting late fill from primary order {exec_spawn_id}: primary is no longer locally mutable",
940            );
941            return;
942        }
943
944        let Some(unfilled_qty) =
945            spawn_unfilled_quantity(order, reduction, primary.quantity().precision)
946        else {
947            ExecutionAlgorithmNative::exec_algorithm_core_mut(self)
948                .take_pending_spawn_reduction(spawn_id);
949            return;
950        };
951        let uncapped_qty = restored_qty.saturating_sub(unfilled_qty);
952        let primary_qty = primary.quantity();
953        // Restored quantity may already have been reused by a later spawn, so
954        // cap at the primary's remaining quantity; the shortfall becomes debt
955        // discharged against later spawn restorations for this primary.
956        let rededuct_qty = uncapped_qty.min(primary_qty);
957        let shortfall_qty = uncapped_qty - rededuct_qty;
958        if rededuct_qty.is_zero() {
959            if !uncapped_qty.is_zero() {
960                charge_spawn_reduction(
961                    ExecutionAlgorithmNative::exec_algorithm_core_mut(self),
962                    spawn_id,
963                    exec_spawn_id,
964                    reduction,
965                    unfilled_qty,
966                    shortfall_qty,
967                );
968                log::warn!(
969                    "Cannot re-deduct late fill on spawned order {spawn_id} from primary order {exec_spawn_id}: primary quantity exhausted, shortfall recorded as debt",
970                );
971            }
972            return;
973        }
974        let mut new_qty = primary_qty - rededuct_qty;
975        new_qty.precision = primary_qty.precision;
976        let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
977        let ts_now = core.clock_mut().timestamp_ns();
978        let event = OrderEventAny::Updated(OrderUpdated::new(
979            primary.trader_id(),
980            primary.strategy_id(),
981            primary.instrument_id(),
982            primary.client_order_id(),
983            new_qty,
984            UUID4::new(),
985            ts_now,
986            ts_now,
987            false,
988            primary.venue_order_id(),
989            primary.account_id(),
990            None,
991            None,
992            None,
993            primary.is_quote_quantity(),
994        ));
995
996        if let Err(e) = core.cache_rc().borrow_mut().update_order(&event) {
997            log::warn!("Failed to update primary order in cache: {e}");
998            return;
999        }
1000
1001        // Commit the lifecycle record before publishing: subscribers run
1002        // synchronously and may re-enter order handling.
1003        charge_spawn_reduction(
1004            ExecutionAlgorithmNative::exec_algorithm_core_mut(self),
1005            spawn_id,
1006            exec_spawn_id,
1007            reduction,
1008            unfilled_qty,
1009            shortfall_qty,
1010        );
1011
1012        if !shortfall_qty.is_zero() {
1013            log::warn!(
1014                "Late fill on spawned order {spawn_id} partially re-deducted from primary order {exec_spawn_id}: shortfall recorded as debt",
1015            );
1016        }
1017
1018        publish_order_event(&event);
1019    }
1020
1021    /// Submits an order to the execution engine via the risk engine.
1022    ///
1023    /// The command's `order_init` carries the order's current values, so a quantity,
1024    /// price or trigger price changed in place before submission reaches the venue.
1025    ///
1026    /// Orders carrying a live emulation trigger are refused before submission.
1027    /// For new or locally active spawned orders with a pending primary reduction,
1028    /// emulation refusal restores unfilled quantity to a locally active primary
1029    /// that has not been handed off, publishing `OrderUpdated` when its quantity changes.
1030    ///
1031    /// # Errors
1032    ///
1033    /// Returns an error if:
1034    /// - The algorithm is not registered.
1035    /// - A cached order with the same client order ID is not `INITIALIZED`, `EMULATED`,
1036    ///   or `RELEASED`.
1037    /// - The order carries a live emulation trigger.
1038    /// - Order submission fails.
1039    fn submit_order(
1040        &mut self,
1041        order: OrderAny,
1042        position_id: Option<PositionId>,
1043        client_id: Option<ClientId>,
1044    ) -> anyhow::Result<()>
1045    where
1046        Self: ExecutionAlgorithmNative,
1047    {
1048        let trader_id =
1049            registered_trader_id(ExecutionAlgorithmNative::exec_algorithm_core_mut(self))?;
1050
1051        let order_exists = {
1052            let cache = ExecutionAlgorithmNative::exec_algorithm_core_mut(self).cache_ref();
1053            let cached_order = cache.order(&order.client_order_id());
1054
1055            if cached_order
1056                .as_ref()
1057                .is_some_and(|cached_order| !cached_order.is_active_local())
1058            {
1059                anyhow::bail!("Order denied: duplicate {}", order.client_order_id());
1060            }
1061
1062            cached_order.is_some()
1063        };
1064
1065        if order.emulation_trigger().is_some() {
1066            let client_order_id = order.client_order_id();
1067            self.restore_primary_order_quantity(&order, true);
1068            return Err(EmulatedOrderSubmissionError { client_order_id }.into());
1069        }
1070
1071        let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
1072        let ts_init = core.clock_mut().timestamp_ns();
1073
1074        // For spawned orders, use the parent's strategy ID
1075        let strategy_id = order.strategy_id();
1076
1077        let primary_id = order
1078            .exec_spawn_id()
1079            .unwrap_or_else(|| order.client_order_id());
1080        let params = core.submit_params(&primary_id);
1081
1082        {
1083            let cache_rc = core.cache_rc();
1084            let mut cache = cache_rc.borrow_mut();
1085            cache.add_order(order.clone(), position_id, client_id, true)?;
1086        }
1087
1088        if !order_exists {
1089            publish_order_initialized(&order);
1090        }
1091
1092        let command = SubmitOrder::new(
1093            trader_id,
1094            client_id,
1095            strategy_id,
1096            order.instrument_id(),
1097            order.client_order_id(),
1098            OrderInitialized::from(&order),
1099            order.exec_algorithm_id(),
1100            position_id,
1101            params,
1102            UUID4::new(),
1103            ts_init,
1104            None, // correlation_id
1105        );
1106
1107        if core.config.log_commands {
1108            let id = &core.actor.actor_id;
1109            log::info!("{id} {SEND}{CMD} {command}");
1110        }
1111
1112        if order.is_primary() {
1113            core.mark_primary_handed_off(order.client_order_id());
1114        }
1115
1116        msgbus::send_trading_command(
1117            MessagingSwitchboard::risk_engine_queue_execute(),
1118            TradingCommand::SubmitOrder(command),
1119        );
1120
1121        Ok(())
1122    }
1123
1124    /// Modifies an order.
1125    ///
1126    /// # Errors
1127    ///
1128    /// Returns an error if all supplied values are absent or unchanged, or if
1129    /// order modification fails.
1130    fn modify_order(
1131        &mut self,
1132        order: &mut OrderAny,
1133        quantity: Option<Quantity>,
1134        price: Option<Price>,
1135        trigger_price: Option<Price>,
1136        client_id: Option<ClientId>,
1137    ) -> anyhow::Result<()>
1138    where
1139        Self: ExecutionAlgorithmNative,
1140    {
1141        let qty_changing = quantity.is_some_and(|q| q != order.quantity());
1142        let price_changing = price.is_some() && price != order.price();
1143        let trigger_changing = trigger_price.is_some() && trigger_price != order.trigger_price();
1144
1145        if !qty_changing && !price_changing && !trigger_changing {
1146            anyhow::bail!(
1147                "Cannot create command ModifyOrder: \
1148                quantity, price, and trigger were either None \
1149                or the same as existing values"
1150            );
1151        }
1152
1153        if order.is_closed() || order.is_pending_cancel() {
1154            log::warn!(
1155                "Cannot create command ModifyOrder: state is {:?}, {order:?}",
1156                order.status()
1157            );
1158            return Ok(());
1159        }
1160
1161        let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
1162        let trader_id = registered_trader_id(core)?;
1163        let strategy_id = order.strategy_id();
1164
1165        let command_id = UUID4::new();
1166
1167        if !order.is_active_local() {
1168            required_account_id(order, "pending update")?;
1169            let event = self.generate_order_pending_update(order, command_id);
1170            let event = OrderEventAny::PendingUpdate(event);
1171
1172            {
1173                let cache_rc = ExecutionAlgorithmNative::exec_algorithm_core_mut(self).cache_rc();
1174                let mut cache = cache_rc.borrow_mut();
1175                match cache.update_order(&event) {
1176                    Ok(updated) => *order = updated,
1177                    Err(e)
1178                        if matches!(
1179                            e.downcast_ref::<OrderError>(),
1180                            Some(OrderError::InvalidStateTransition)
1181                        ) =>
1182                    {
1183                        log::warn!("InvalidStateTrigger: {e}, did not apply pending update event");
1184                        return Ok(());
1185                    }
1186                    Err(e) => return Err(e),
1187                }
1188            }
1189
1190            let topic = format!("events.order.{strategy_id}");
1191            msgbus::publish_order_event(topic.into(), &event);
1192            msgbus::publish_order_event(
1193                msgbus::switchboard::get_order_pending_update_topic(order.instrument_id()),
1194                &event,
1195            );
1196        }
1197
1198        let ts_init = ExecutionAlgorithmNative::exec_algorithm_core_mut(self)
1199            .clock_mut()
1200            .timestamp_ns();
1201        let command = ModifyOrder::new(
1202            trader_id,
1203            client_id,
1204            strategy_id,
1205            order.instrument_id(),
1206            order.client_order_id(),
1207            order.venue_order_id(),
1208            quantity,
1209            price,
1210            trigger_price,
1211            command_id,
1212            ts_init,
1213            None, // params,
1214            None, // correlation_id
1215        );
1216
1217        if ExecutionAlgorithmNative::exec_algorithm_core_mut(self)
1218            .config
1219            .log_commands
1220        {
1221            let id = &ExecutionAlgorithmNative::exec_algorithm_core_mut(self)
1222                .actor
1223                .actor_id;
1224            log::info!("{id} {SEND}{CMD} {command}");
1225        }
1226
1227        let has_emulation_trigger = order.emulation_trigger().is_some();
1228
1229        if order.is_emulated() || has_emulation_trigger {
1230            msgbus::send_trading_command(
1231                MessagingSwitchboard::order_emulator_execute(),
1232                TradingCommand::ModifyOrder(command),
1233            );
1234        } else {
1235            msgbus::send_trading_command(
1236                MessagingSwitchboard::risk_engine_queue_execute(),
1237                TradingCommand::ModifyOrder(command),
1238            );
1239        }
1240
1241        Ok(())
1242    }
1243
1244    /// Modifies an INITIALIZED or RELEASED order in place without sending a command.
1245    ///
1246    /// This is useful for adjusting order parameters before submission. The order
1247    /// is updated locally by applying an `OrderUpdated` event and updating the cache.
1248    ///
1249    /// At least one parameter must differ from the current order values.
1250    ///
1251    /// # Errors
1252    ///
1253    /// Returns an error if the order status is not INITIALIZED or RELEASED,
1254    /// or if no parameters would change.
1255    fn modify_order_in_place(
1256        &mut self,
1257        order: &mut OrderAny,
1258        quantity: Option<Quantity>,
1259        price: Option<Price>,
1260        trigger_price: Option<Price>,
1261    ) -> anyhow::Result<()>
1262    where
1263        Self: ExecutionAlgorithmNative,
1264    {
1265        // Validate order status
1266        let status = order.status();
1267        if status != OrderStatus::Initialized && status != OrderStatus::Released {
1268            anyhow::bail!(
1269                "Cannot modify order in place: status is {status:?}, expected INITIALIZED or RELEASED"
1270            );
1271        }
1272
1273        // Validate order type compatibility
1274        if price.is_some() && order.price().is_none() {
1275            anyhow::bail!(
1276                "Cannot modify order in place: {} orders do not have a LIMIT price",
1277                order.order_type()
1278            );
1279        }
1280
1281        if trigger_price.is_some() && order.trigger_price().is_none() {
1282            anyhow::bail!(
1283                "Cannot modify order in place: {} orders do not have a STOP trigger price",
1284                order.order_type()
1285            );
1286        }
1287
1288        // Check if any value would actually change
1289        let qty_changing = quantity.is_some_and(|q| q != order.quantity());
1290        let price_changing = price.is_some() && price != order.price();
1291        let trigger_changing = trigger_price.is_some() && trigger_price != order.trigger_price();
1292
1293        if !qty_changing && !price_changing && !trigger_changing {
1294            anyhow::bail!("Cannot modify order in place: no parameters differ from current values");
1295        }
1296
1297        let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
1298        let ts_now = core.clock_mut().timestamp_ns();
1299
1300        let updated = OrderUpdated::new(
1301            order.trader_id(),
1302            order.strategy_id(),
1303            order.instrument_id(),
1304            order.client_order_id(),
1305            quantity.unwrap_or_else(|| order.quantity()),
1306            UUID4::new(),
1307            ts_now,
1308            ts_now,
1309            false, // reconciliation
1310            order.venue_order_id(),
1311            order.account_id(),
1312            price,
1313            trigger_price,
1314            None, // protection_price
1315            order.is_quote_quantity(),
1316        );
1317
1318        let event = OrderEventAny::Updated(updated);
1319
1320        {
1321            let cache_rc = core.cache_rc();
1322            let mut cache = cache_rc.borrow_mut();
1323            *order = cache.update_order(&event)?;
1324        }
1325
1326        publish_order_event(&event);
1327
1328        Ok(())
1329    }
1330
1331    /// Cancels an order.
1332    ///
1333    /// # Errors
1334    ///
1335    /// Returns an error if order cancellation fails.
1336    fn cancel_order(
1337        &mut self,
1338        order: &mut OrderAny,
1339        client_id: Option<ClientId>,
1340    ) -> anyhow::Result<()>
1341    where
1342        Self: ExecutionAlgorithmNative,
1343    {
1344        if order.is_closed() || order.is_pending_cancel() {
1345            log::warn!(
1346                "Cannot cancel order: state is {:?}, {order:?}",
1347                order.status()
1348            );
1349            return Ok(());
1350        }
1351
1352        let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
1353        let trader_id = registered_trader_id(core)?;
1354        let strategy_id = order.strategy_id();
1355
1356        let command_id = UUID4::new();
1357
1358        if !order.is_active_local() {
1359            required_account_id(order, "pending cancel")?;
1360            let event = self.generate_order_pending_cancel(order, command_id);
1361            let event = OrderEventAny::PendingCancel(event);
1362
1363            {
1364                let cache_rc = ExecutionAlgorithmNative::exec_algorithm_core_mut(self).cache_rc();
1365                let mut cache = cache_rc.borrow_mut();
1366                match cache.update_order(&event) {
1367                    Ok(updated) => *order = updated,
1368                    Err(e)
1369                        if matches!(
1370                            e.downcast_ref::<OrderError>(),
1371                            Some(OrderError::InvalidStateTransition)
1372                        ) =>
1373                    {
1374                        log::warn!("InvalidStateTrigger: {e}, did not apply pending cancel event");
1375                        return Ok(());
1376                    }
1377                    Err(e) => return Err(e),
1378                }
1379            }
1380
1381            let topic = format!("events.order.{strategy_id}");
1382            msgbus::publish_order_event(topic.into(), &event);
1383            msgbus::publish_order_event(
1384                msgbus::switchboard::get_order_pending_cancel_topic(order.instrument_id()),
1385                &event,
1386            );
1387        }
1388
1389        let ts_init = ExecutionAlgorithmNative::exec_algorithm_core_mut(self)
1390            .clock_mut()
1391            .timestamp_ns();
1392        let command = CancelOrder::new(
1393            trader_id,
1394            client_id,
1395            strategy_id,
1396            order.instrument_id(),
1397            order.client_order_id(),
1398            order.venue_order_id(),
1399            command_id,
1400            ts_init,
1401            None, // params,
1402            None, // correlation_id
1403        );
1404
1405        if ExecutionAlgorithmNative::exec_algorithm_core_mut(self)
1406            .config
1407            .log_commands
1408        {
1409            let id = &ExecutionAlgorithmNative::exec_algorithm_core_mut(self)
1410                .actor
1411                .actor_id;
1412            log::info!("{id} {SEND}{CMD} {command}");
1413        }
1414
1415        let has_emulation_trigger = order.emulation_trigger().is_some();
1416
1417        if order.is_emulated() || order.status() == OrderStatus::Released || has_emulation_trigger {
1418            msgbus::send_trading_command(
1419                MessagingSwitchboard::order_emulator_execute(),
1420                TradingCommand::CancelOrder(command),
1421            );
1422        } else {
1423            msgbus::send_trading_command(
1424                MessagingSwitchboard::exec_engine_queue_execute(),
1425                TradingCommand::CancelOrder(command),
1426            );
1427        }
1428
1429        Ok(())
1430    }
1431
1432    /// Subscribes to events from a strategy.
1433    ///
1434    /// This is called automatically when the first order is received from a strategy.
1435    fn subscribe_to_strategy_events(&mut self, strategy_id: StrategyId)
1436    where
1437        Self: ExecutionAlgorithmNative,
1438        Self: 'static + std::fmt::Debug + Sized,
1439    {
1440        let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
1441        if core.is_strategy_subscribed(&strategy_id) {
1442            return;
1443        }
1444
1445        let actor_id = core.actor.actor_id.inner();
1446
1447        let order_topic = format!("events.order.{strategy_id}");
1448        let order_actor_id = actor_id;
1449        let order_handler = TypedHandler::from(move |event: &OrderEventAny| {
1450            if let Some(mut algo) = try_get_actor_unchecked::<Self>(&order_actor_id) {
1451                algo.handle_order_event(event.clone());
1452            } else {
1453                log::error!(
1454                    "ExecutionAlgorithm {order_actor_id} not found for order event handling"
1455                );
1456            }
1457        });
1458        msgbus::subscribe_order_events(order_topic.clone().into(), order_handler.clone(), None);
1459
1460        let position_topic = format!("events.position.{strategy_id}");
1461        let position_handler = TypedHandler::from(move |event: &PositionEvent| {
1462            if let Some(mut algo) = try_get_actor_unchecked::<Self>(&actor_id) {
1463                algo.handle_position_event(event.clone());
1464            } else {
1465                log::error!("ExecutionAlgorithm {actor_id} not found for position event handling");
1466            }
1467        });
1468        msgbus::subscribe_position_events(
1469            position_topic.clone().into(),
1470            position_handler.clone(),
1471            None,
1472        );
1473
1474        let handlers = StrategyEventHandlers {
1475            order_topic,
1476            order_handler,
1477            position_topic,
1478            position_handler,
1479        };
1480        core.store_strategy_event_handlers(strategy_id, handlers);
1481
1482        core.add_subscribed_strategy(strategy_id);
1483        log::info!("Subscribed to events for strategy {strategy_id}");
1484    }
1485
1486    /// Unsubscribes from all strategy event handlers.
1487    ///
1488    /// This should be called before reset to properly clean up msgbus subscriptions.
1489    fn unsubscribe_all_strategy_events(&mut self)
1490    where
1491        Self: ExecutionAlgorithmNative,
1492    {
1493        let handlers =
1494            ExecutionAlgorithmNative::exec_algorithm_core_mut(self).take_strategy_event_handlers();
1495
1496        for (strategy_id, h) in handlers {
1497            msgbus::unsubscribe_order_events(h.order_topic.into(), &h.order_handler);
1498            msgbus::unsubscribe_position_events(h.position_topic.into(), &h.position_handler);
1499            log::info!("Unsubscribed from events for strategy {strategy_id}");
1500        }
1501        ExecutionAlgorithmNative::exec_algorithm_core_mut(self).clear_subscribed_strategies();
1502    }
1503
1504    /// Handles an order event, filtering for algorithm-owned orders.
1505    ///
1506    /// For registered algorithms, spawn accounting runs in every component state.
1507    /// Order callbacks require the running state before and after accounting.
1508    fn handle_order_event(&mut self, event: OrderEventAny)
1509    where
1510        Self: ExecutionAlgorithmNative,
1511    {
1512        if !DataActorNative::core(ExecutionAlgorithmNative::exec_algorithm_core(self))
1513            .is_registered()
1514        {
1515            return;
1516        }
1517
1518        let was_running =
1519            DataActorNative::core(ExecutionAlgorithmNative::exec_algorithm_core(self)).state()
1520                == ComponentState::Running;
1521
1522        let order = {
1523            let cache = ExecutionAlgorithmNative::exec_algorithm_core_mut(self).cache_ref();
1524            cache.order(&event.client_order_id()).map(|o| o.clone())
1525        };
1526
1527        let Some(order) = order else {
1528            return;
1529        };
1530
1531        let Some(order_algo_id) = order.exec_algorithm_id() else {
1532            return;
1533        };
1534
1535        if order_algo_id != self.id() {
1536            return;
1537        }
1538
1539        {
1540            let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
1541            if core.config.log_events && was_running {
1542                let id = &core.actor.actor_id;
1543                log::info!("{id} {RECV}{EVT} {event}");
1544            }
1545        }
1546
1547        if order.is_primary() && !order.is_active_local() {
1548            ExecutionAlgorithmNative::exec_algorithm_core_mut(self)
1549                .clear_primary_spawn_state(order.client_order_id());
1550        }
1551
1552        match &event {
1553            OrderEventAny::Denied(_)
1554            | OrderEventAny::Rejected(_)
1555            | OrderEventAny::Canceled(_)
1556            | OrderEventAny::Expired(_) => self.restore_primary_order_quantity(&order, false),
1557            OrderEventAny::Filled(_) => {
1558                self.rededuct_late_spawn_fill(&order);
1559                let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
1560                if order.leaves_qty().is_zero()
1561                    && core
1562                        .spawn_reduction(order.client_order_id())
1563                        .is_some_and(|reduction| reduction.restored_qty.is_none())
1564                {
1565                    core.take_pending_spawn_reduction(order.client_order_id());
1566                }
1567            }
1568            OrderEventAny::FillVoided(_)
1569                if ExecutionAlgorithmNative::exec_algorithm_core_mut(self)
1570                    .spawn_reduction(order.client_order_id())
1571                    .is_some_and(|reduction| reduction.restored_qty.is_some()) =>
1572            {
1573                self.restore_primary_order_quantity(&order, false);
1574            }
1575            _ => {}
1576        }
1577
1578        if !was_running
1579            || DataActorNative::core(ExecutionAlgorithmNative::exec_algorithm_core_mut(self))
1580                .state()
1581                != ComponentState::Running
1582        {
1583            return;
1584        }
1585
1586        match &event {
1587            OrderEventAny::Initialized(e) => self.on_order_initialized(e.clone()),
1588            OrderEventAny::Denied(e) => self.on_order_denied(*e),
1589            OrderEventAny::Emulated(e) => self.on_order_emulated(*e),
1590            OrderEventAny::Released(e) => self.on_order_released(*e),
1591            OrderEventAny::Submitted(e) => self.on_order_submitted(*e),
1592            OrderEventAny::Rejected(e) => self.on_order_rejected(*e),
1593            OrderEventAny::Accepted(e) => self.on_order_accepted(*e),
1594            OrderEventAny::Canceled(e) => self.on_algo_order_canceled(*e),
1595            OrderEventAny::Expired(e) => self.on_order_expired(*e),
1596            OrderEventAny::Triggered(e) => self.on_order_triggered(*e),
1597            OrderEventAny::PendingUpdate(e) => self.on_order_pending_update(*e),
1598            OrderEventAny::PendingCancel(e) => self.on_order_pending_cancel(*e),
1599            OrderEventAny::ModifyDenied(e) => self.on_order_modify_denied(*e),
1600            OrderEventAny::ModifyRejected(e) => self.on_order_modify_rejected(*e),
1601            OrderEventAny::CancelDenied(e) => self.on_order_cancel_denied(*e),
1602            OrderEventAny::CancelRejected(e) => self.on_order_cancel_rejected(*e),
1603            OrderEventAny::Updated(e) => self.on_order_updated(*e),
1604            OrderEventAny::Filled(e) => self.on_algo_order_filled(e.clone()),
1605            OrderEventAny::FillVoided(e) => self.on_order_fill_voided(e),
1606        }
1607
1608        self.on_order_event(event);
1609    }
1610
1611    /// Handles a position event.
1612    fn handle_position_event(&mut self, event: PositionEvent)
1613    where
1614        Self: ExecutionAlgorithmNative,
1615    {
1616        if DataActorNative::core(ExecutionAlgorithmNative::exec_algorithm_core_mut(self)).state()
1617            != ComponentState::Running
1618        {
1619            return;
1620        }
1621
1622        {
1623            let core = ExecutionAlgorithmNative::exec_algorithm_core_mut(self);
1624            if core.config.log_events {
1625                let id = &core.actor.actor_id;
1626                log::info!("{id} {RECV}{EVT} {event:?}");
1627            }
1628        }
1629
1630        match &event {
1631            PositionEvent::PositionOpened(e) => self.on_position_opened(e.clone()),
1632            PositionEvent::PositionChanged(e) => self.on_position_changed(e.clone()),
1633            PositionEvent::PositionClosed(e) => self.on_position_closed(e.clone()),
1634            PositionEvent::PositionAdjusted(_) => {}
1635        }
1636
1637        self.on_position_event(event);
1638    }
1639
1640    /// Called when the algorithm is started.
1641    ///
1642    /// Override this method to implement custom initialization logic.
1643    ///
1644    /// # Errors
1645    ///
1646    /// Returns an error if start fails.
1647    fn on_start(&mut self) -> anyhow::Result<()>
1648    where
1649        Self: ExecutionAlgorithmNative,
1650    {
1651        let id = self.id();
1652        log::info!("Starting {id}");
1653        Ok(())
1654    }
1655
1656    /// Called when the algorithm is stopped.
1657    ///
1658    /// # Errors
1659    ///
1660    /// Returns an error if stop fails.
1661    fn on_stop(&mut self) -> anyhow::Result<()> {
1662        Ok(())
1663    }
1664
1665    /// Called when the algorithm is resumed.
1666    ///
1667    /// # Errors
1668    ///
1669    /// Returns an error if resume fails.
1670    fn on_resume(&mut self) -> anyhow::Result<()> {
1671        Ok(())
1672    }
1673
1674    /// Called when the algorithm is reset.
1675    ///
1676    /// # Errors
1677    ///
1678    /// Returns an error if reset fails.
1679    fn on_reset(&mut self) -> anyhow::Result<()>
1680    where
1681        Self: ExecutionAlgorithmNative,
1682    {
1683        self.unsubscribe_all_strategy_events();
1684        ExecutionAlgorithmNative::exec_algorithm_core_mut(self).reset();
1685        Ok(())
1686    }
1687
1688    /// Called when a time event is received.
1689    ///
1690    /// Override this method for timer-based algorithms like TWAP.
1691    ///
1692    /// # Errors
1693    ///
1694    /// Returns an error if time event handling fails.
1695    fn on_time_event(&mut self, _event: &TimeEvent) -> anyhow::Result<()> {
1696        Ok(())
1697    }
1698
1699    /// Called when an order is initialized.
1700    #[allow(unused_variables)]
1701    fn on_order_initialized(&mut self, event: OrderInitialized) {}
1702
1703    /// Called when an order is denied.
1704    #[allow(unused_variables)]
1705    fn on_order_denied(&mut self, event: OrderDenied) {}
1706
1707    /// Called when an order is emulated.
1708    #[allow(unused_variables)]
1709    fn on_order_emulated(&mut self, event: OrderEmulated) {}
1710
1711    /// Called when an order is released from emulation.
1712    #[allow(unused_variables)]
1713    fn on_order_released(&mut self, event: OrderReleased) {}
1714
1715    /// Called when an order is submitted.
1716    #[allow(unused_variables)]
1717    fn on_order_submitted(&mut self, event: OrderSubmitted) {}
1718
1719    /// Called when an order is rejected.
1720    #[allow(unused_variables)]
1721    fn on_order_rejected(&mut self, event: OrderRejected) {}
1722
1723    /// Called when an order is accepted.
1724    #[allow(unused_variables)]
1725    fn on_order_accepted(&mut self, event: OrderAccepted) {}
1726
1727    /// Called when an order is canceled.
1728    #[allow(unused_variables)]
1729    fn on_algo_order_canceled(&mut self, event: OrderCanceled) {}
1730
1731    /// Called when an order expires.
1732    #[allow(unused_variables)]
1733    fn on_order_expired(&mut self, event: OrderExpired) {}
1734
1735    /// Called when an order is triggered.
1736    #[allow(unused_variables)]
1737    fn on_order_triggered(&mut self, event: OrderTriggered) {}
1738
1739    /// Called when an order modification is pending.
1740    #[allow(unused_variables)]
1741    fn on_order_pending_update(&mut self, event: OrderPendingUpdate) {}
1742
1743    /// Called when an order cancellation is pending.
1744    #[allow(unused_variables)]
1745    fn on_order_pending_cancel(&mut self, event: OrderPendingCancel) {}
1746
1747    /// Called when a modify command is proven not sent; the order remains otherwise unchanged.
1748    #[allow(unused_variables)]
1749    fn on_order_modify_denied(&mut self, event: OrderModifyDenied) {}
1750
1751    /// Called when an order modification is rejected.
1752    #[allow(unused_variables)]
1753    fn on_order_modify_rejected(&mut self, event: OrderModifyRejected) {}
1754
1755    /// Called when a cancel command is proven not sent; the order remains otherwise unchanged.
1756    #[allow(unused_variables)]
1757    fn on_order_cancel_denied(&mut self, event: OrderCancelDenied) {}
1758
1759    /// Called when an order cancellation is rejected.
1760    #[allow(unused_variables)]
1761    fn on_order_cancel_rejected(&mut self, event: OrderCancelRejected) {}
1762
1763    /// Called when an order is updated.
1764    #[allow(unused_variables)]
1765    fn on_order_updated(&mut self, event: OrderUpdated) {}
1766
1767    /// Called when an order is filled.
1768    #[allow(unused_variables)]
1769    fn on_algo_order_filled(&mut self, event: OrderFilled) {}
1770
1771    /// Called when an applied order fill is partly or fully voided.
1772    #[allow(unused_variables)]
1773    fn on_order_fill_voided(&mut self, event: &OrderFillVoided) {}
1774
1775    /// Called for any order event (after specific handler).
1776    #[allow(unused_variables)]
1777    fn on_order_event(&mut self, event: OrderEventAny) {}
1778
1779    /// Called when a position is opened.
1780    #[allow(unused_variables)]
1781    fn on_position_opened(&mut self, event: PositionOpened) {}
1782
1783    /// Called when a position is changed.
1784    #[allow(unused_variables)]
1785    fn on_position_changed(&mut self, event: PositionChanged) {}
1786
1787    /// Called when a position is closed.
1788    #[allow(unused_variables)]
1789    fn on_position_closed(&mut self, event: PositionClosed) {}
1790
1791    /// Called for any position event (after specific handler).
1792    #[allow(unused_variables)]
1793    fn on_position_event(&mut self, event: PositionEvent) {}
1794}
1795
1796#[derive(Debug)]
1797pub(crate) struct EmulatedOrderSubmissionError {
1798    client_order_id: ClientOrderId,
1799}
1800
1801impl Display for EmulatedOrderSubmissionError {
1802    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1803        write!(
1804            f,
1805            "Execution algorithm cannot submit order {} with a live emulation trigger",
1806            self.client_order_id
1807        )
1808    }
1809}
1810
1811impl std::error::Error for EmulatedOrderSubmissionError {}
1812
1813fn spawn_unfilled_quantity(
1814    order: &OrderAny,
1815    reduction: SpawnReduction,
1816    primary_precision: u8,
1817) -> Option<Quantity> {
1818    if reduction.spawn_was_quote_quantity == order.is_quote_quantity() {
1819        return Some(
1820            order
1821                .quantity()
1822                .min(reduction.deducted_qty)
1823                .saturating_sub(order.filled_qty()),
1824        );
1825    }
1826
1827    if !reduction.spawn_was_quote_quantity {
1828        log::warn!(
1829            "Cannot account for spawned order {} quantity: denomination changed from base to quote",
1830            order.client_order_id(),
1831        );
1832        return None;
1833    }
1834
1835    let converted_total = order.quantity();
1836    if converted_total.is_zero() {
1837        log::warn!(
1838            "Cannot account for converted spawned order {} quantity: converted total is zero",
1839            order.client_order_id(),
1840        );
1841        return None;
1842    }
1843
1844    // Voided fills release budget even when the venue does not reopen their leaves
1845    let child_qty = converted_total.saturating_sub(order.filled_qty());
1846
1847    // Fills and leaves never exceed the order total; the clamp makes that a
1848    // structural bound so the quotient below always fits the raw width.
1849    let child_qty = child_qty.min(converted_total);
1850    // QuantityRaw is u64 or u128 depending on the high-precision feature, so
1851    // the widening is real in one build shape and an identity in the other.
1852    #[allow(clippy::useless_conversion)]
1853    let proportional_raw = QuantityRaw::try_from(muldiv_floor_u128(
1854        u128::from(reduction.deducted_qty.raw()),
1855        u128::from(child_qty.raw()),
1856        u128::from(converted_total.raw()),
1857    ))
1858    .expect("Quotient bounded by the deducted quantity");
1859
1860    let precision_increment = Quantity::from_decimal_dp(
1861        rust_decimal::Decimal::new(1, u32::from(primary_precision)),
1862        primary_precision,
1863    )
1864    .expect("Primary quantity precision must be valid")
1865    .raw();
1866    let floored_raw = proportional_raw - proportional_raw % precision_increment;
1867    Some(Quantity::from_raw(floored_raw, primary_precision))
1868}
1869
1870/// Returns `floor(a * b / c)` without intermediate overflow.
1871///
1872/// # Panics
1873///
1874/// Panics if `c` is zero, or if `b > c` and the quotient exceeds `u128`
1875/// (callers bound `b` by `c`, which bounds the quotient by `a`).
1876fn muldiv_floor_u128(a: u128, b: u128, c: u128) -> u128 {
1877    if let Some(product) = a.checked_mul(b) {
1878        return product / c;
1879    }
1880
1881    let (hi, lo) = mul_wide_u128(a, b);
1882    assert!(hi < c, "muldiv_floor_u128 quotient exceeds u128");
1883    div_wide_u128(hi, lo, c)
1884}
1885
1886/// Returns the 256-bit product of two `u128` values as `(high, low)` halves.
1887fn mul_wide_u128(a: u128, b: u128) -> (u128, u128) {
1888    const MASK: u128 = (1u128 << 64) - 1;
1889    let (a_hi, a_lo) = (a >> 64, a & MASK);
1890    let (b_hi, b_lo) = (b >> 64, b & MASK);
1891
1892    let ll = a_lo * b_lo;
1893    let lh = a_lo * b_hi;
1894    let hl = a_hi * b_lo;
1895    let hh = a_hi * b_hi;
1896
1897    let mid = (ll >> 64) + (lh & MASK) + (hl & MASK);
1898    let lo = (mid << 64) | (ll & MASK);
1899    let hi = hh + (lh >> 64) + (hl >> 64) + (mid >> 64);
1900    (hi, lo)
1901}
1902
1903/// Divides the 256-bit value `(hi, lo)` by `c` via restoring long division,
1904/// truncating toward zero. Requires `hi < c` so the quotient fits `u128`.
1905fn div_wide_u128(hi: u128, lo: u128, c: u128) -> u128 {
1906    let mut rem = hi;
1907    let mut quotient = 0u128;
1908
1909    for i in (0..u128::BITS).rev() {
1910        // A carry out of the shift means the true remainder is rem + 2^128,
1911        // which always exceeds c; wrapping_sub then yields the exact value.
1912        let carry = rem >> 127;
1913        rem = (rem << 1) | ((lo >> i) & 1);
1914
1915        if carry == 1 || rem >= c {
1916            rem = rem.wrapping_sub(c);
1917            quotient |= 1 << i;
1918        }
1919    }
1920    quotient
1921}
1922
1923/// Charges a late fill against a spawn reduction record, booking any shortfall
1924/// as debt against the primary order.
1925fn charge_spawn_reduction(
1926    core: &mut ExecutionAlgorithmCore,
1927    spawn_id: ClientOrderId,
1928    primary_id: ClientOrderId,
1929    mut reduction: SpawnReduction,
1930    unfilled_qty: Quantity,
1931    shortfall_qty: Quantity,
1932) {
1933    reduction.restored_qty = Some(unfilled_qty);
1934    core.set_spawn_reduction(spawn_id, reduction);
1935
1936    if !shortfall_qty.is_zero() {
1937        core.add_spawn_fill_debt(primary_id, shortfall_qty);
1938    }
1939}
1940
1941fn deny_modify_command(
1942    core: &mut ExecutionAlgorithmCore,
1943    command: &ModifyOrder,
1944    reason: &str,
1945) -> anyhow::Result<()> {
1946    registered_trader_id(core)?;
1947    let ts_now = core.clock_mut().timestamp_ns();
1948    let order = core
1949        .cache_ref()
1950        .order(&command.client_order_id)
1951        .map(|order| order.clone());
1952
1953    let mut event = OrderModifyDenied::new(
1954        order.as_ref().map_or(command.trader_id, Order::trader_id),
1955        order
1956            .as_ref()
1957            .map_or(command.strategy_id, Order::strategy_id),
1958        order
1959            .as_ref()
1960            .map_or(command.instrument_id, Order::instrument_id),
1961        order
1962            .as_ref()
1963            .map_or(command.client_order_id, Order::client_order_id),
1964        reason.into(),
1965        UUID4::new(),
1966        ts_now,
1967        ts_now,
1968        order
1969            .as_ref()
1970            .and_then(Order::venue_order_id)
1971            .or(command.venue_order_id),
1972        order.as_ref().and_then(Order::account_id),
1973    );
1974    event.causation_id = Some(command.command_id);
1975    let event = OrderEventAny::ModifyDenied(event);
1976    apply_command_denied(core, &event)
1977}
1978
1979fn deny_cancel_command(
1980    core: &mut ExecutionAlgorithmCore,
1981    command: &CancelOrder,
1982    reason: &str,
1983) -> anyhow::Result<()> {
1984    registered_trader_id(core)?;
1985    let ts_now = core.clock_mut().timestamp_ns();
1986    let order = core
1987        .cache_ref()
1988        .order(&command.client_order_id)
1989        .map(|order| order.clone());
1990
1991    let mut event = OrderCancelDenied::new(
1992        order.as_ref().map_or(command.trader_id, Order::trader_id),
1993        order
1994            .as_ref()
1995            .map_or(command.strategy_id, Order::strategy_id),
1996        order
1997            .as_ref()
1998            .map_or(command.instrument_id, Order::instrument_id),
1999        command.client_order_id,
2000        reason.into(),
2001        UUID4::new(),
2002        ts_now,
2003        ts_now,
2004        order
2005            .as_ref()
2006            .and_then(Order::venue_order_id)
2007            .or(command.venue_order_id),
2008        order.as_ref().and_then(Order::account_id),
2009    );
2010    event.causation_id = Some(command.command_id);
2011    apply_command_denied(core, &OrderEventAny::CancelDenied(event))
2012}
2013
2014fn apply_command_denied(
2015    core: &ExecutionAlgorithmCore,
2016    event: &OrderEventAny,
2017) -> anyhow::Result<()> {
2018    if core.cache_ref().order_exists(&event.client_order_id()) {
2019        core.cache_rc().borrow_mut().update_order(event)?;
2020    }
2021
2022    publish_order_event(event);
2023    Ok(())
2024}
2025
2026fn publish_order_initialized(order: &OrderAny) {
2027    let event = OrderEventAny::Initialized(order.init_event().clone());
2028    publish_order_event(&event);
2029}
2030
2031fn publish_order_event(event: &OrderEventAny) {
2032    let topic = format!("events.order.{}", event.strategy_id());
2033    msgbus::publish_order_event(topic.into(), event);
2034
2035    let topic = match event {
2036        OrderEventAny::ModifyDenied(_) => {
2037            msgbus::switchboard::get_order_modify_denied_topic(event.instrument_id())
2038        }
2039        OrderEventAny::CancelDenied(_) => {
2040            msgbus::switchboard::get_order_cancel_denied_topic(event.instrument_id())
2041        }
2042        _ => return,
2043    };
2044
2045    msgbus::publish_order_event(topic, event);
2046}
2047
2048fn registered_trader_id(core: &ExecutionAlgorithmCore) -> anyhow::Result<TraderId> {
2049    DataActorNative::core(core)
2050        .trader_id()
2051        .ok_or_else(|| anyhow::anyhow!("ExecutionAlgorithm not registered: trader_id is not set"))
2052}
2053
2054fn required_account_id(order: &OrderAny, operation: &str) -> anyhow::Result<AccountId> {
2055    order.account_id().ok_or_else(|| {
2056        anyhow::anyhow!(
2057            "Cannot generate {operation} event for {}: account_id is not set",
2058            order.client_order_id()
2059        )
2060    })
2061}
2062
2063#[cfg(test)]
2064mod tests {
2065    use std::{cell::RefCell, rc::Rc};
2066
2067    use nautilus_common::{
2068        actor::DataActor,
2069        cache::Cache,
2070        clock::VirtualClock,
2071        component::Component,
2072        enums::ComponentTrigger,
2073        msgbus::{
2074            self, TypedHandler,
2075            stubs::{TypedIntoMessageSavingHandler, get_typed_into_message_saving_handler},
2076        },
2077    };
2078    use nautilus_model::{
2079        enums::{LiquiditySide, OrderSide, OrderStatus, OrderType},
2080        events::{
2081            OrderAccepted, OrderCanceled, OrderDenied, OrderDeniedReason, OrderRejected,
2082            order::spec::{
2083                OrderAcceptedSpec, OrderCanceledSpec, OrderDeniedSpec, OrderEmulatedSpec,
2084                OrderExpiredSpec, OrderFillVoidedSpec, OrderFilledSpec, OrderRejectedSpec,
2085                OrderReleasedSpec, OrderSubmittedSpec, OrderUpdatedSpec,
2086            },
2087        },
2088        identifiers::{
2089            AccountId, ActorId, ClientOrderId, ExecAlgorithmId, InstrumentId, StrategyId, TradeId,
2090            TraderId, VenueOrderId,
2091        },
2092        orders::{LimitOrder, MarketOrder, OrderAny, OrderTestBuilder, stubs::TestOrderStubs},
2093        types::{Currency, Price, Quantity},
2094    };
2095    use rstest::rstest;
2096
2097    use super::*;
2098    use crate::nautilus_execution_algorithm;
2099
2100    #[derive(Debug)]
2101    struct TestAlgorithm {
2102        core: ExecutionAlgorithmCore,
2103        order_client_ids: Vec<ClientOrderId>,
2104        order_callbacks: Vec<&'static str>,
2105    }
2106
2107    #[derive(Debug)]
2108    struct LifecycleAlgorithm {
2109        core: ExecutionAlgorithmCore,
2110        order_callbacks: Vec<&'static str>,
2111    }
2112
2113    #[derive(Debug)]
2114    struct ModifyDispatchAlgorithm {
2115        core: ExecutionAlgorithmCore,
2116        modify_client_order_ids: Vec<ClientOrderId>,
2117    }
2118
2119    #[derive(Debug)]
2120    struct CoreFreeExecutionAlgorithm {
2121        orders_seen: usize,
2122    }
2123
2124    #[derive(Debug)]
2125    struct MacroTestCustomField {
2126        inner: ExecutionAlgorithmCore,
2127    }
2128
2129    impl DataActor for CoreFreeExecutionAlgorithm {}
2130
2131    impl ExecutionAlgorithm for CoreFreeExecutionAlgorithm {
2132        fn on_order(&mut self, _order: OrderAny) -> anyhow::Result<()> {
2133            self.orders_seen += 1;
2134            Ok(())
2135        }
2136    }
2137
2138    impl DataActor for MacroTestCustomField {}
2139
2140    nautilus_execution_algorithm!(MacroTestCustomField, inner, {
2141        fn on_order(&mut self, _order: OrderAny) -> anyhow::Result<()> {
2142            Ok(())
2143        }
2144    });
2145
2146    impl TestAlgorithm {
2147        fn new(config: ExecutionAlgorithmConfig) -> Self {
2148            Self {
2149                core: ExecutionAlgorithmCore::new(config),
2150                order_client_ids: Vec::new(),
2151                order_callbacks: Vec::new(),
2152            }
2153        }
2154    }
2155
2156    impl DataActor for TestAlgorithm {}
2157
2158    nautilus_execution_algorithm!(TestAlgorithm, {
2159        fn on_order(&mut self, order: OrderAny) -> anyhow::Result<()> {
2160            self.order_client_ids.push(order.client_order_id());
2161            Ok(())
2162        }
2163
2164        fn on_algo_order_canceled(&mut self, _event: OrderCanceled) {
2165            self.order_callbacks.push("canceled");
2166        }
2167
2168        fn on_algo_order_filled(&mut self, _event: OrderFilled) {
2169            self.order_callbacks.push("filled");
2170        }
2171
2172        fn on_order_event(&mut self, _event: OrderEventAny) {
2173            self.order_callbacks.push("event");
2174        }
2175    });
2176
2177    impl DataActor for LifecycleAlgorithm {}
2178
2179    nautilus_execution_algorithm!(LifecycleAlgorithm, {
2180        fn on_order(&mut self, _order: OrderAny) -> anyhow::Result<()> {
2181            Ok(())
2182        }
2183
2184        fn restore_primary_order_quantity(&mut self, _order: &OrderAny, _refused: bool) {
2185            if Component::state(self) == ComponentState::Running {
2186                Component::stop(self).unwrap();
2187            } else {
2188                Component::resume(self).unwrap();
2189            }
2190        }
2191
2192        fn on_algo_order_canceled(&mut self, _event: OrderCanceled) {
2193            self.order_callbacks.push("canceled");
2194        }
2195
2196        fn on_order_event(&mut self, _event: OrderEventAny) {
2197            self.order_callbacks.push("event");
2198        }
2199    });
2200
2201    impl ModifyDispatchAlgorithm {
2202        fn new(config: ExecutionAlgorithmConfig) -> Self {
2203            Self {
2204                core: ExecutionAlgorithmCore::new(config),
2205                modify_client_order_ids: Vec::new(),
2206            }
2207        }
2208    }
2209
2210    impl DataActor for ModifyDispatchAlgorithm {}
2211
2212    nautilus_execution_algorithm!(ModifyDispatchAlgorithm, {
2213        fn on_order(&mut self, _order: OrderAny) -> anyhow::Result<()> {
2214            Ok(())
2215        }
2216
2217        fn handle_modify_order(&mut self, command: ModifyOrder) -> anyhow::Result<()> {
2218            self.modify_client_order_ids.push(command.client_order_id);
2219            Ok(())
2220        }
2221    });
2222
2223    fn create_test_algorithm() -> TestAlgorithm {
2224        // Use unique ID to avoid thread-local registry/msgbus conflicts in parallel tests
2225        let unique_id = format!("TEST-{}", UUID4::new());
2226        let config = ExecutionAlgorithmConfig {
2227            exec_algorithm_id: Some(ExecAlgorithmId::new(&unique_id)),
2228            ..Default::default()
2229        };
2230        TestAlgorithm::new(config)
2231    }
2232
2233    fn register_algorithm(algo: &mut TestAlgorithm) {
2234        let trader_id = TraderId::from("TRADER-001");
2235        let clock = Rc::new(RefCell::new(VirtualClock::new()));
2236        let cache = Rc::new(RefCell::new(Cache::default()));
2237
2238        algo.core.register(trader_id, clock, cache).unwrap();
2239
2240        // Transition to Running state for tests
2241        algo.transition_state(ComponentTrigger::Initialize).unwrap();
2242        algo.transition_state(ComponentTrigger::Start).unwrap();
2243        algo.transition_state(ComponentTrigger::StartCompleted)
2244            .unwrap();
2245    }
2246
2247    fn subscribe_order_topic(
2248        strategy_id: StrategyId,
2249    ) -> (TypedHandler<OrderEventAny>, Rc<RefCell<Vec<OrderEventAny>>>) {
2250        let events = Rc::new(RefCell::new(Vec::new()));
2251        let handler = TypedHandler::from({
2252            let events = events.clone();
2253            move |event: &OrderEventAny| {
2254                events.borrow_mut().push(event.clone());
2255            }
2256        });
2257        msgbus::subscribe_order_events(
2258            format!("events.order.{strategy_id}").into(),
2259            handler.clone(),
2260            None,
2261        );
2262        (handler, events)
2263    }
2264
2265    fn setup_pending_spawn() -> (TestAlgorithm, ClientOrderId, OrderAny) {
2266        let mut algo = create_test_algorithm();
2267        register_algorithm(&mut algo);
2268        let client_order_id = ClientOrderId::from("O-001");
2269        let mut primary = OrderAny::Market(MarketOrder::new(
2270            TraderId::from("TRADER-001"),
2271            StrategyId::from("STRAT-001"),
2272            InstrumentId::from("BTC/USDT.BINANCE"),
2273            client_order_id,
2274            OrderSide::Buy,
2275            Quantity::from("1.0"),
2276            TimeInForce::Gtc,
2277            UUID4::new(),
2278            0.into(),
2279            false,
2280            false,
2281            None,
2282            None,
2283            None,
2284            None,
2285            Some(algo.id()),
2286            None,
2287            Some(client_order_id),
2288            None,
2289        ));
2290        algo.core
2291            .cache_rc()
2292            .borrow_mut()
2293            .add_order(primary.clone(), None, None, false)
2294            .unwrap();
2295        let spawned = algo
2296            .spawn_market(
2297                &mut primary,
2298                Quantity::from("0.5"),
2299                TimeInForce::Fok,
2300                false,
2301                None,
2302                true,
2303            )
2304            .unwrap();
2305        let spawned_order = OrderAny::Market(spawned);
2306        algo.core
2307            .cache_rc()
2308            .borrow_mut()
2309            .add_order(spawned_order.clone(), None, None, false)
2310            .unwrap();
2311        (algo, client_order_id, spawned_order)
2312    }
2313
2314    fn setup_accepted_spawn() -> (TestAlgorithm, ClientOrderId, OrderAny) {
2315        let (mut algo, client_order_id, mut spawned_order) = setup_pending_spawn();
2316        let accepted = OrderAcceptedSpec::builder()
2317            .trader_id(spawned_order.trader_id())
2318            .strategy_id(spawned_order.strategy_id())
2319            .instrument_id(spawned_order.instrument_id())
2320            .client_order_id(spawned_order.client_order_id())
2321            .venue_order_id(VenueOrderId::from("V-123"))
2322            .account_id(AccountId::from("BINANCE-001"))
2323            .build();
2324        spawned_order = algo
2325            .core
2326            .cache_rc()
2327            .borrow_mut()
2328            .update_order(&OrderEventAny::Accepted(accepted))
2329            .unwrap();
2330        algo.handle_order_event(OrderEventAny::Accepted(accepted));
2331        (algo, client_order_id, spawned_order)
2332    }
2333
2334    fn setup_accepted_quote_spawn(
2335        primary_qty: Quantity,
2336        spawn_qty: Quantity,
2337    ) -> (TestAlgorithm, ClientOrderId, OrderAny) {
2338        let mut algo = create_test_algorithm();
2339        register_algorithm(&mut algo);
2340        let client_order_id = ClientOrderId::from("O-QUOTE");
2341        let mut primary = OrderAny::Market(MarketOrder::new(
2342            TraderId::from("TRADER-001"),
2343            StrategyId::from("STRAT-001"),
2344            InstrumentId::from("BTC/USDT.BINANCE"),
2345            client_order_id,
2346            OrderSide::Buy,
2347            primary_qty,
2348            TimeInForce::Gtc,
2349            UUID4::new(),
2350            0.into(),
2351            false,
2352            true,
2353            None,
2354            None,
2355            None,
2356            None,
2357            Some(algo.id()),
2358            None,
2359            Some(client_order_id),
2360            None,
2361        ));
2362        algo.core
2363            .cache_rc()
2364            .borrow_mut()
2365            .add_order(primary.clone(), None, None, false)
2366            .unwrap();
2367        let mut spawned_order = OrderAny::Market(
2368            algo.spawn_market(&mut primary, spawn_qty, TimeInForce::Fok, false, None, true)
2369                .unwrap(),
2370        );
2371        algo.core
2372            .cache_rc()
2373            .borrow_mut()
2374            .add_order(spawned_order.clone(), None, None, false)
2375            .unwrap();
2376        accept_spawned_order(&mut algo, &mut spawned_order);
2377        (algo, client_order_id, spawned_order)
2378    }
2379
2380    fn fill_spawned_order(algo: &mut TestAlgorithm, order: &mut OrderAny, quantity: Quantity) {
2381        let venue_order_id = order
2382            .venue_order_id()
2383            .unwrap_or_else(|| VenueOrderId::from("V-PRIMARY"));
2384        let filled = OrderFilledSpec::builder()
2385            .trader_id(order.trader_id())
2386            .strategy_id(order.strategy_id())
2387            .instrument_id(order.instrument_id())
2388            .client_order_id(order.client_order_id())
2389            .venue_order_id(venue_order_id)
2390            .account_id(AccountId::from("BINANCE-001"))
2391            .trade_id(TradeId::new(UUID4::new().to_string()))
2392            .order_side(order.order_side())
2393            .order_type(order.order_type())
2394            .last_qty(quantity)
2395            .last_px(Price::from("50000.0"))
2396            .currency(Currency::USD())
2397            .liquidity_side(LiquiditySide::Taker)
2398            .build();
2399        *order = algo
2400            .core
2401            .cache_rc()
2402            .borrow_mut()
2403            .update_order(&OrderEventAny::Filled(filled.clone()))
2404            .unwrap();
2405        algo.handle_order_event(OrderEventAny::Filled(filled));
2406    }
2407
2408    fn submit_order_in_cache(algo: &mut TestAlgorithm, order: &mut OrderAny) {
2409        let submitted = OrderSubmittedSpec::builder()
2410            .trader_id(order.trader_id())
2411            .strategy_id(order.strategy_id())
2412            .instrument_id(order.instrument_id())
2413            .client_order_id(order.client_order_id())
2414            .account_id(AccountId::from("BINANCE-001"))
2415            .build();
2416        *order = algo
2417            .core
2418            .cache_rc()
2419            .borrow_mut()
2420            .update_order(&OrderEventAny::Submitted(submitted))
2421            .unwrap();
2422        algo.handle_order_event(OrderEventAny::Submitted(submitted));
2423    }
2424
2425    fn cancel_spawned_order(algo: &mut TestAlgorithm, order: &mut OrderAny) {
2426        let venue_order_id = order
2427            .venue_order_id()
2428            .unwrap_or_else(|| VenueOrderId::from("V-123"));
2429        let canceled = OrderCanceledSpec::builder()
2430            .trader_id(order.trader_id())
2431            .strategy_id(order.strategy_id())
2432            .instrument_id(order.instrument_id())
2433            .client_order_id(order.client_order_id())
2434            .venue_order_id(venue_order_id)
2435            .account_id(AccountId::from("BINANCE-001"))
2436            .build();
2437        *order = algo
2438            .core
2439            .cache_rc()
2440            .borrow_mut()
2441            .update_order(&OrderEventAny::Canceled(canceled))
2442            .unwrap();
2443        algo.handle_order_event(OrderEventAny::Canceled(canceled));
2444    }
2445
2446    fn convert_spawn_to_base(algo: &mut TestAlgorithm, order: &mut OrderAny, quantity: Quantity) {
2447        let updated = OrderUpdatedSpec::builder()
2448            .trader_id(order.trader_id())
2449            .strategy_id(order.strategy_id())
2450            .instrument_id(order.instrument_id())
2451            .client_order_id(order.client_order_id())
2452            .quantity(quantity)
2453            .maybe_venue_order_id(order.venue_order_id())
2454            .maybe_account_id(order.account_id())
2455            .is_quote_quantity(false)
2456            .build();
2457        *order = algo
2458            .core
2459            .cache_rc()
2460            .borrow_mut()
2461            .update_order(&OrderEventAny::Updated(updated))
2462            .unwrap();
2463        algo.handle_order_event(OrderEventAny::Updated(updated));
2464    }
2465
2466    fn expire_spawned_order(algo: &mut TestAlgorithm, order: &mut OrderAny) {
2467        let expired = OrderExpiredSpec::builder()
2468            .trader_id(order.trader_id())
2469            .strategy_id(order.strategy_id())
2470            .instrument_id(order.instrument_id())
2471            .client_order_id(order.client_order_id())
2472            .venue_order_id(VenueOrderId::from("V-123"))
2473            .account_id(AccountId::from("BINANCE-001"))
2474            .build();
2475        *order = algo
2476            .core
2477            .cache_rc()
2478            .borrow_mut()
2479            .update_order(&OrderEventAny::Expired(expired))
2480            .unwrap();
2481        algo.handle_order_event(OrderEventAny::Expired(expired));
2482    }
2483
2484    fn accept_spawned_order(algo: &mut TestAlgorithm, order: &mut OrderAny) {
2485        let venue_order_id = VenueOrderId::from(format!("V-{}", order.client_order_id()).as_str());
2486        let accepted = OrderAcceptedSpec::builder()
2487            .trader_id(order.trader_id())
2488            .strategy_id(order.strategy_id())
2489            .instrument_id(order.instrument_id())
2490            .client_order_id(order.client_order_id())
2491            .venue_order_id(venue_order_id)
2492            .account_id(AccountId::from("BINANCE-001"))
2493            .build();
2494        *order = algo
2495            .core
2496            .cache_rc()
2497            .borrow_mut()
2498            .update_order(&OrderEventAny::Accepted(accepted))
2499            .unwrap();
2500        algo.handle_order_event(OrderEventAny::Accepted(accepted));
2501    }
2502
2503    fn spawn_reduced_child(
2504        algo: &mut TestAlgorithm,
2505        primary_id: ClientOrderId,
2506        quantity: Quantity,
2507    ) -> OrderAny {
2508        let mut primary = algo.cache().order(&primary_id).unwrap();
2509        let child = OrderAny::Market(
2510            algo.spawn_market(&mut primary, quantity, TimeInForce::Fok, false, None, true)
2511                .unwrap(),
2512        );
2513        algo.core
2514            .cache_rc()
2515            .borrow_mut()
2516            .add_order(child.clone(), None, None, false)
2517            .unwrap();
2518        child
2519    }
2520
2521    #[rstest]
2522    fn test_algorithm_creation() {
2523        let algo = create_test_algorithm();
2524        assert!(algo.id().inner().starts_with("TEST-"));
2525        assert!(algo.order_client_ids.is_empty());
2526    }
2527
2528    #[rstest]
2529    fn test_algorithm_registration() {
2530        let mut algo = create_test_algorithm();
2531        register_algorithm(&mut algo);
2532
2533        assert_eq!(algo.trader_id(), Some(TraderId::from("TRADER-001")));
2534    }
2535
2536    #[rstest]
2537    fn test_algorithm_deny_order_updates_cache_and_publishes_once() {
2538        let mut algo = create_test_algorithm();
2539        register_algorithm(&mut algo);
2540
2541        let strategy_id = StrategyId::from("STRAT-ALGO-DENY");
2542        let order = OrderAny::Market(MarketOrder::new(
2543            TraderId::from("TRADER-001"),
2544            strategy_id,
2545            InstrumentId::from("BTC/USDT.BINANCE"),
2546            ClientOrderId::from("O-ALGO-DENY"),
2547            OrderSide::Buy,
2548            Quantity::from("1.0"),
2549            TimeInForce::Gtc,
2550            UUID4::new(),
2551            0.into(),
2552            false,
2553            false,
2554            None,
2555            None,
2556            None,
2557            None,
2558            None,
2559            None,
2560            None,
2561            None,
2562        ));
2563        {
2564            let cache_rc = algo.core.cache_rc();
2565            cache_rc
2566                .borrow_mut()
2567                .add_order(order.clone(), None, None, false)
2568                .unwrap();
2569        }
2570        let reason = OrderDeniedReason::ValidationFailed {
2571            detail: "invalid execution schedule".to_string(),
2572        }
2573        .to_string();
2574        let reason = Ustr::from(&reason);
2575        let (handler, events) = subscribe_order_topic(strategy_id);
2576
2577        algo.deny_order(&order, reason).unwrap();
2578        algo.deny_order(&order, reason).unwrap();
2579
2580        msgbus::unsubscribe_order_events(format!("events.order.{strategy_id}").into(), &handler);
2581        let cached_order = algo.cache().order(&order.client_order_id()).unwrap();
2582        let events = events.borrow();
2583
2584        assert_eq!(cached_order.status(), OrderStatus::Denied);
2585        assert_eq!(events.len(), 1);
2586        assert!(matches!(
2587            &events[0],
2588            OrderEventAny::Denied(event)
2589                if event.reason == reason
2590                    && event.strategy_id == strategy_id
2591                    && event.client_order_id == order.client_order_id()
2592        ));
2593    }
2594
2595    #[rstest]
2596    fn test_algorithm_deny_order_initializes_missing_order_once() {
2597        let mut algo = create_test_algorithm();
2598        register_algorithm(&mut algo);
2599
2600        let strategy_id = StrategyId::from("STRAT-ALGO-DENY-MISSING");
2601        let order = OrderTestBuilder::new(OrderType::Market)
2602            .strategy_id(strategy_id)
2603            .instrument_id(InstrumentId::from("BTC/USDT.BINANCE"))
2604            .client_order_id(ClientOrderId::from("O-ALGO-DENY-MISSING"))
2605            .quantity(Quantity::from("1.0"))
2606            .build();
2607        let reason = Ustr::from("VALIDATION_FAILED: invalid execution schedule");
2608        let (handler, events) = subscribe_order_topic(strategy_id);
2609
2610        algo.deny_order(&order, reason).unwrap();
2611        algo.deny_order(&order, reason).unwrap();
2612
2613        msgbus::unsubscribe_order_events(format!("events.order.{strategy_id}").into(), &handler);
2614        let cached_order = algo.cache().order(&order.client_order_id()).unwrap();
2615        let events = events.borrow();
2616
2617        assert_eq!(cached_order.status(), OrderStatus::Denied);
2618        assert_eq!(cached_order.event_count(), 2);
2619        assert_eq!(events.len(), 2);
2620        assert!(matches!(
2621            &events[0],
2622            OrderEventAny::Initialized(event)
2623                if event.strategy_id == strategy_id
2624                    && event.client_order_id == order.client_order_id()
2625        ));
2626        assert!(matches!(
2627            &events[1],
2628            OrderEventAny::Denied(event)
2629                if event.reason == reason
2630                    && event.strategy_id == strategy_id
2631                    && event.client_order_id == order.client_order_id()
2632        ));
2633    }
2634
2635    #[rstest]
2636    fn test_algorithm_deny_order_does_not_publish_when_apply_fails() {
2637        let mut algo = create_test_algorithm();
2638        register_algorithm(&mut algo);
2639
2640        let strategy_id = StrategyId::from("STRAT-ALGO-DENY-APPLY");
2641        let order = OrderTestBuilder::new(OrderType::Market)
2642            .strategy_id(strategy_id)
2643            .instrument_id(InstrumentId::from("BTC/USDT.BINANCE"))
2644            .client_order_id(ClientOrderId::from("O-ALGO-DENY-APPLY"))
2645            .quantity(Quantity::from("1.0"))
2646            .build();
2647        let order = TestOrderStubs::make_accepted_order(&order);
2648        {
2649            let cache_rc = algo.core.cache_rc();
2650            cache_rc
2651                .borrow_mut()
2652                .add_order(order.clone(), None, None, false)
2653                .unwrap();
2654        }
2655        let (handler, events) = subscribe_order_topic(strategy_id);
2656
2657        let params = nautilus_core::Params::new(
2658            [(
2659                "route".to_string(),
2660                serde_json::Value::String("A".to_string()),
2661            )]
2662            .into(),
2663        );
2664        algo.core
2665            .remember_submit_params(order.client_order_id(), Some(params));
2666
2667        let error = algo
2668            .deny_order(
2669                &order,
2670                Ustr::from("VALIDATION_FAILED: invalid execution schedule"),
2671            )
2672            .unwrap_err();
2673
2674        msgbus::unsubscribe_order_events(format!("events.order.{strategy_id}").into(), &handler);
2675        let cached_order = algo.cache().order(&order.client_order_id()).unwrap();
2676
2677        assert!(matches!(
2678            error.downcast_ref::<OrderError>(),
2679            Some(OrderError::InvalidStateTransition)
2680        ));
2681        assert_eq!(cached_order.status(), OrderStatus::Accepted);
2682        assert!(events.borrow().is_empty());
2683        // A failed denial is not terminal, so the submit params must be retained
2684        assert!(algo.core.submit_params(&order.client_order_id()).is_some());
2685    }
2686
2687    #[rstest]
2688    fn test_algorithm_deny_order_removes_submit_params() {
2689        let mut algo = create_test_algorithm();
2690        register_algorithm(&mut algo);
2691
2692        let strategy_id = StrategyId::from("STRAT-ALGO-DENY-PARAMS");
2693        let order = OrderTestBuilder::new(OrderType::Market)
2694            .strategy_id(strategy_id)
2695            .instrument_id(InstrumentId::from("BTC/USDT.BINANCE"))
2696            .client_order_id(ClientOrderId::from("O-ALGO-DENY-PARAMS"))
2697            .quantity(Quantity::from("1.0"))
2698            .build();
2699        {
2700            let cache_rc = algo.core.cache_rc();
2701            cache_rc
2702                .borrow_mut()
2703                .add_order(order.clone(), None, None, false)
2704                .unwrap();
2705        }
2706
2707        let params = nautilus_core::Params::new(
2708            [(
2709                "route".to_string(),
2710                serde_json::Value::String("A".to_string()),
2711            )]
2712            .into(),
2713        );
2714        algo.core
2715            .remember_submit_params(order.client_order_id(), Some(params));
2716        assert!(algo.core.submit_params(&order.client_order_id()).is_some());
2717
2718        algo.deny_order(&order, Ustr::from("VALIDATION_FAILED: test"))
2719            .unwrap();
2720
2721        assert!(algo.core.submit_params(&order.client_order_id()).is_none());
2722    }
2723
2724    #[rstest]
2725    fn test_submit_order_errors_when_algorithm_not_registered() {
2726        let mut algo = create_test_algorithm();
2727        let order = OrderAny::Market(MarketOrder::new(
2728            TraderId::from("TRADER-001"),
2729            StrategyId::from("STRAT-001"),
2730            InstrumentId::from("BTC/USDT.BINANCE"),
2731            ClientOrderId::from("O-UNREGISTERED-001"),
2732            OrderSide::Buy,
2733            Quantity::from("1.0"),
2734            TimeInForce::Gtc,
2735            UUID4::new(),
2736            0.into(),
2737            false,
2738            false,
2739            None,
2740            None,
2741            None,
2742            None,
2743            None,
2744            None,
2745            None,
2746            None,
2747        ));
2748
2749        let err = algo
2750            .submit_order(order, None, None)
2751            .unwrap_err()
2752            .to_string();
2753
2754        assert_eq!(
2755            err,
2756            "ExecutionAlgorithm not registered: trader_id is not set"
2757        );
2758    }
2759
2760    #[rstest]
2761    fn test_required_account_id_errors_when_missing_for_algorithm_event() {
2762        let order = OrderAny::Market(MarketOrder::new(
2763            TraderId::from("TRADER-001"),
2764            StrategyId::from("STRAT-001"),
2765            InstrumentId::from("BTC/USDT.BINANCE"),
2766            ClientOrderId::from("O-NO-ACCOUNT-001"),
2767            OrderSide::Buy,
2768            Quantity::from("1.0"),
2769            TimeInForce::Gtc,
2770            UUID4::new(),
2771            0.into(),
2772            false,
2773            false,
2774            None,
2775            None,
2776            None,
2777            None,
2778            None,
2779            None,
2780            None,
2781            None,
2782        ));
2783
2784        let err = required_account_id(&order, "pending update")
2785            .unwrap_err()
2786            .to_string();
2787
2788        assert_eq!(
2789            err,
2790            "Cannot generate pending update event for O-NO-ACCOUNT-001: account_id is not set"
2791        );
2792    }
2793
2794    #[rstest]
2795    fn test_algorithm_id() {
2796        let algo = create_test_algorithm();
2797        assert!(algo.id().inner().starts_with("TEST-"));
2798    }
2799
2800    #[rstest]
2801    fn test_execution_algorithm_behavior_does_not_require_native_core_access() {
2802        fn assert_execution_algorithm<T: ExecutionAlgorithm + DataActor>() {}
2803
2804        assert_execution_algorithm::<CoreFreeExecutionAlgorithm>();
2805
2806        let mut algorithm = CoreFreeExecutionAlgorithm { orders_seen: 0 };
2807        let order = OrderTestBuilder::new(OrderType::Market)
2808            .instrument_id(InstrumentId::from("BTC/USDT.BINANCE"))
2809            .quantity(Quantity::from("1.0"))
2810            .build();
2811
2812        algorithm.on_order(order).unwrap();
2813
2814        assert_eq!(algorithm.orders_seen, 1);
2815    }
2816
2817    #[rstest]
2818    fn test_nautilus_execution_algorithm_macro_custom_field() {
2819        let exec_algorithm_id = ExecAlgorithmId::from("MACRO-001");
2820        let algorithm = MacroTestCustomField {
2821            inner: ExecutionAlgorithmCore::new(ExecutionAlgorithmConfig {
2822                exec_algorithm_id: Some(exec_algorithm_id),
2823                ..Default::default()
2824            }),
2825        };
2826
2827        assert_eq!(algorithm.id(), exec_algorithm_id);
2828        assert_eq!(algorithm.actor_id(), ActorId::from("MACRO-001"));
2829    }
2830
2831    #[rstest]
2832    fn test_algorithm_spawn_market_creates_valid_order() {
2833        let mut algo = create_test_algorithm();
2834        register_algorithm(&mut algo);
2835
2836        let instrument_id = InstrumentId::from("BTC/USDT.BINANCE");
2837        let mut primary = OrderAny::Market(MarketOrder::new(
2838            TraderId::from("TRADER-001"),
2839            StrategyId::from("STRAT-001"),
2840            instrument_id,
2841            ClientOrderId::from("O-001"),
2842            OrderSide::Buy,
2843            Quantity::from("1.0"),
2844            TimeInForce::Gtc,
2845            UUID4::new(),
2846            0.into(),
2847            false, // reduce_only
2848            false, // quote_quantity
2849            None,  // contingency_type
2850            None,  // order_list_id
2851            None,  // linked_order_ids
2852            None,  // parent_order_id
2853            None,  // exec_algorithm_id
2854            None,  // exec_algorithm_params
2855            None,  // exec_spawn_id
2856            None,  // tags
2857        ));
2858
2859        let spawned = algo
2860            .spawn_market(
2861                &mut primary,
2862                Quantity::from("0.5"),
2863                TimeInForce::Ioc,
2864                false,
2865                None,  // tags
2866                false, // reduce_primary
2867            )
2868            .unwrap();
2869
2870        assert_eq!(spawned.client_order_id.as_str(), "O-001-E1");
2871        assert_eq!(spawned.instrument_id, instrument_id);
2872        assert_eq!(spawned.order_side(), OrderSide::Buy);
2873        assert_eq!(spawned.quantity, Quantity::from("0.5"));
2874        assert_eq!(spawned.time_in_force, TimeInForce::Ioc);
2875        assert_eq!(spawned.exec_algorithm_id, Some(algo.id()));
2876        assert_eq!(spawned.exec_spawn_id, Some(ClientOrderId::from("O-001")));
2877    }
2878
2879    #[rstest]
2880    #[case::market_gtd(
2881        OrderType::Market,
2882        "0.2",
2883        TimeInForce::Gtd,
2884        None,
2885        None,
2886        "GTD not supported for Market orders"
2887    )]
2888    #[case::market_zero(
2889        OrderType::Market,
2890        "0.0",
2891        TimeInForce::Gtc,
2892        None,
2893        None,
2894        "invalid `Quantity` for 'quantity' not positive, was 0.0"
2895    )]
2896    #[case::limit_zero(
2897        OrderType::Limit,
2898        "0.0",
2899        TimeInForce::Gtc,
2900        None,
2901        None,
2902        "invalid `Quantity` for 'quantity' not positive, was 0.0"
2903    )]
2904    #[case::limit_gtd_missing(
2905        OrderType::Limit,
2906        "0.2",
2907        TimeInForce::Gtd,
2908        None,
2909        None,
2910        "`expire_time` is required for `GTD` order"
2911    )]
2912    #[case::limit_gtd_zero(
2913        OrderType::Limit,
2914        "0.2",
2915        TimeInForce::Gtd,
2916        Some(UnixNanos::default()),
2917        None,
2918        "`expire_time` is required for `GTD` order"
2919    )]
2920    #[case::limit_display(
2921        OrderType::Limit,
2922        "0.2",
2923        TimeInForce::Gtc,
2924        None,
2925        Some(Quantity::from("0.3")),
2926        "`display_qty` may not exceed `quantity`"
2927    )]
2928    #[case::mtl_zero(
2929        OrderType::MarketToLimit,
2930        "0.0",
2931        TimeInForce::Gtc,
2932        None,
2933        None,
2934        "invalid `Quantity` for 'quantity' not positive, was 0.0"
2935    )]
2936    #[case::mtl_gtd_missing(
2937        OrderType::MarketToLimit,
2938        "0.2",
2939        TimeInForce::Gtd,
2940        None,
2941        None,
2942        "`expire_time` is required for `GTD` order"
2943    )]
2944    #[case::mtl_gtd_zero(
2945        OrderType::MarketToLimit,
2946        "0.2",
2947        TimeInForce::Gtd,
2948        Some(UnixNanos::default()),
2949        None,
2950        "`expire_time` is required for `GTD` order"
2951    )]
2952    #[case::mtl_display(
2953        OrderType::MarketToLimit,
2954        "0.2",
2955        TimeInForce::Gtc,
2956        None,
2957        Some(Quantity::from("0.3")),
2958        "`display_qty` may not exceed `quantity`"
2959    )]
2960    fn test_spawn_constructor_failure_preserves_primary(
2961        #[case] order_type: OrderType,
2962        #[case] quantity: Quantity,
2963        #[case] time_in_force: TimeInForce,
2964        #[case] expire_time: Option<UnixNanos>,
2965        #[case] display_qty: Option<Quantity>,
2966        #[case] expected_error: &str,
2967        #[values(true, false)] reduce_primary: bool,
2968    ) {
2969        let (mut algo, primary_id, existing_spawn) = setup_pending_spawn();
2970        let mut primary = algo.cache().order(&primary_id).unwrap();
2971        let snapshot = serde_json::to_value(&primary).unwrap();
2972        let strategy_id = primary.strategy_id();
2973        let (handler, events) = subscribe_order_topic(strategy_id);
2974
2975        let result = match order_type {
2976            OrderType::Market => algo
2977                .spawn_market(
2978                    &mut primary,
2979                    quantity,
2980                    time_in_force,
2981                    false,
2982                    None,
2983                    reduce_primary,
2984                )
2985                .map(OrderAny::from),
2986            OrderType::Limit => algo
2987                .spawn_limit(
2988                    &mut primary,
2989                    quantity,
2990                    Price::from("50001.0"),
2991                    time_in_force,
2992                    expire_time,
2993                    false,
2994                    false,
2995                    display_qty,
2996                    None,
2997                    None,
2998                    reduce_primary,
2999                )
3000                .map(OrderAny::from),
3001            OrderType::MarketToLimit => algo
3002                .spawn_market_to_limit(
3003                    &mut primary,
3004                    quantity,
3005                    time_in_force,
3006                    expire_time,
3007                    false,
3008                    display_qty,
3009                    None,
3010                    None,
3011                    reduce_primary,
3012                )
3013                .map(OrderAny::from),
3014            _ => unreachable!("Only the three spawn order types are tested"),
3015        };
3016
3017        msgbus::unsubscribe_order_events(format!("events.order.{strategy_id}").into(), &handler);
3018        let cached = algo.cache().order(&primary_id).unwrap();
3019        let existing_reduction = algo
3020            .core
3021            .spawn_reduction(existing_spawn.client_order_id())
3022            .unwrap();
3023
3024        assert_eq!(result.unwrap_err().to_string(), expected_error);
3025        assert_eq!(serde_json::to_value(&primary).unwrap(), snapshot);
3026        assert_eq!(serde_json::to_value(&cached).unwrap(), snapshot);
3027        assert!(events.borrow().is_empty());
3028        assert!(
3029            algo.core
3030                .spawn_reduction(ClientOrderId::from("O-001-E2"))
3031                .is_none()
3032        );
3033        assert_eq!(existing_reduction.primary_id, primary_id);
3034        assert_eq!(existing_reduction.deducted_qty, Quantity::from("0.5"));
3035        assert!(!existing_reduction.spawn_was_quote_quantity);
3036        assert_eq!(existing_reduction.restored_qty, None);
3037        assert_eq!(algo.core.spawn_fill_debt(primary_id), None);
3038        assert_eq!(algo.core.spawn_sequence(&primary_id), Some(2));
3039    }
3040
3041    #[rstest]
3042    fn test_spawn_success_updates_primary_after_validation(
3043        #[values(OrderType::Market, OrderType::Limit, OrderType::MarketToLimit)]
3044        order_type: OrderType,
3045        #[values(true, false)] reduce_primary: bool,
3046    ) {
3047        let (mut algo, primary_id, _) = setup_pending_spawn();
3048        let mut primary = algo.cache().order(&primary_id).unwrap();
3049        let strategy_id = primary.strategy_id();
3050        let quantity = Quantity::from("0.2");
3051        let (handler, events) = subscribe_order_topic(strategy_id);
3052
3053        let spawned = match order_type {
3054            OrderType::Market => algo
3055                .spawn_market(
3056                    &mut primary,
3057                    quantity,
3058                    TimeInForce::Ioc,
3059                    false,
3060                    None,
3061                    reduce_primary,
3062                )
3063                .map(OrderAny::from),
3064            OrderType::Limit => algo
3065                .spawn_limit(
3066                    &mut primary,
3067                    quantity,
3068                    Price::from("50001.0"),
3069                    TimeInForce::Gtd,
3070                    Some(UnixNanos::from(1_000_000_000)),
3071                    false,
3072                    false,
3073                    Some(quantity),
3074                    None,
3075                    None,
3076                    reduce_primary,
3077                )
3078                .map(OrderAny::from),
3079            OrderType::MarketToLimit => algo
3080                .spawn_market_to_limit(
3081                    &mut primary,
3082                    quantity,
3083                    TimeInForce::Gtd,
3084                    Some(UnixNanos::from(1_000_000_000)),
3085                    false,
3086                    Some(quantity),
3087                    None,
3088                    None,
3089                    reduce_primary,
3090                )
3091                .map(OrderAny::from),
3092            _ => unreachable!("Only the three spawn order types are tested"),
3093        }
3094        .unwrap();
3095
3096        msgbus::unsubscribe_order_events(format!("events.order.{strategy_id}").into(), &handler);
3097
3098        let expected_qty = if reduce_primary {
3099            Quantity::from("0.3")
3100        } else {
3101            Quantity::from("0.5")
3102        };
3103
3104        let cached = algo.cache().order(&primary_id).unwrap();
3105        let reduction = algo.core.spawn_reduction(spawned.client_order_id());
3106        let events = events.borrow();
3107
3108        assert_eq!(spawned.order_type(), order_type);
3109        assert_eq!(spawned.client_order_id(), ClientOrderId::from("O-001-E2"));
3110        assert_eq!(spawned.quantity(), quantity);
3111        assert_eq!(spawned.exec_algorithm_id(), Some(algo.id()));
3112        assert_eq!(spawned.exec_spawn_id(), Some(primary_id));
3113        assert_eq!(primary.quantity(), expected_qty);
3114        assert_eq!(cached.quantity(), expected_qty);
3115        assert_eq!(events.len(), usize::from(reduce_primary));
3116
3117        if reduce_primary {
3118            let OrderEventAny::Updated(event) = &events[0] else {
3119                panic!("Expected OrderUpdated");
3120            };
3121
3122            assert_eq!(event.client_order_id, primary_id);
3123            assert_eq!(event.quantity, expected_qty);
3124            let reduction = reduction.unwrap();
3125            assert_eq!(reduction.primary_id, primary_id);
3126            assert_eq!(reduction.deducted_qty, quantity);
3127            assert!(!reduction.spawn_was_quote_quantity);
3128            assert_eq!(reduction.restored_qty, None);
3129        } else {
3130            assert!(reduction.is_none());
3131        }
3132    }
3133
3134    #[rstest]
3135    fn test_algorithm_spawn_increments_sequence() {
3136        let mut algo = create_test_algorithm();
3137        register_algorithm(&mut algo);
3138
3139        let mut primary = OrderAny::Market(MarketOrder::new(
3140            TraderId::from("TRADER-001"),
3141            StrategyId::from("STRAT-001"),
3142            InstrumentId::from("BTC/USDT.BINANCE"),
3143            ClientOrderId::from("O-001"),
3144            OrderSide::Buy,
3145            Quantity::from("1.0"),
3146            TimeInForce::Gtc,
3147            UUID4::new(),
3148            0.into(),
3149            false,
3150            false,
3151            None,
3152            None,
3153            None,
3154            None,
3155            None,
3156            None,
3157            None,
3158            None,
3159        ));
3160
3161        let spawned1 = algo
3162            .spawn_market(
3163                &mut primary,
3164                Quantity::from("0.25"),
3165                TimeInForce::Ioc,
3166                false,
3167                None,
3168                false,
3169            )
3170            .unwrap();
3171        let spawned2 = algo
3172            .spawn_market(
3173                &mut primary,
3174                Quantity::from("0.25"),
3175                TimeInForce::Ioc,
3176                false,
3177                None,
3178                false,
3179            )
3180            .unwrap();
3181        let spawned3 = algo
3182            .spawn_market(
3183                &mut primary,
3184                Quantity::from("0.25"),
3185                TimeInForce::Ioc,
3186                false,
3187                None,
3188                false,
3189            )
3190            .unwrap();
3191
3192        assert_eq!(spawned1.client_order_id.as_str(), "O-001-E1");
3193        assert_eq!(spawned2.client_order_id.as_str(), "O-001-E2");
3194        assert_eq!(spawned3.client_order_id.as_str(), "O-001-E3");
3195    }
3196
3197    #[rstest]
3198    fn test_algorithm_default_handlers_do_not_panic() {
3199        let mut algo = create_test_algorithm();
3200
3201        algo.on_order_initialized(OrderInitialized::default());
3202        algo.on_order_denied(OrderDenied::default());
3203        algo.on_order_emulated(OrderEmulated::default());
3204        algo.on_order_released(OrderReleased::default());
3205        algo.on_order_submitted(OrderSubmitted::default());
3206        algo.on_order_rejected(OrderRejected::default());
3207        algo.on_order_accepted(OrderAccepted::default());
3208        algo.on_algo_order_canceled(OrderCanceled::default());
3209        algo.on_order_expired(OrderExpired::default());
3210        algo.on_order_triggered(OrderTriggered::default());
3211        algo.on_order_pending_update(OrderPendingUpdate::default());
3212        algo.on_order_pending_cancel(OrderPendingCancel::default());
3213        algo.on_order_modify_rejected(OrderModifyRejected::default());
3214        algo.on_order_cancel_rejected(OrderCancelRejected::default());
3215        algo.on_order_updated(OrderUpdated::default());
3216        algo.on_algo_order_filled(OrderFilledSpec::builder().build());
3217        algo.on_order_fill_voided(&OrderFillVoidedSpec::builder().build());
3218    }
3219
3220    #[rstest]
3221    fn test_strategy_subscription_tracking() {
3222        let mut algo = create_test_algorithm();
3223        let strategy_id = StrategyId::from("STRAT-001");
3224
3225        assert!(!algo.core.is_strategy_subscribed(&strategy_id));
3226
3227        algo.subscribe_to_strategy_events(strategy_id);
3228        assert!(algo.core.is_strategy_subscribed(&strategy_id));
3229
3230        // Second call should be idempotent
3231        algo.subscribe_to_strategy_events(strategy_id);
3232        assert!(algo.core.is_strategy_subscribed(&strategy_id));
3233    }
3234
3235    #[rstest]
3236    fn test_algorithm_reset() {
3237        let mut algo = create_test_algorithm();
3238        let strategy_id = StrategyId::from("STRAT-001");
3239        let primary_id = ClientOrderId::new("O-001");
3240
3241        let _ = algo.core.spawn_client_order_id(&primary_id);
3242        algo.core.add_subscribed_strategy(strategy_id);
3243
3244        assert!(algo.core.spawn_sequence(&primary_id).is_some());
3245        assert!(algo.core.is_strategy_subscribed(&strategy_id));
3246
3247        ExecutionAlgorithm::on_reset(&mut algo).unwrap();
3248
3249        assert!(algo.core.spawn_sequence(&primary_id).is_none());
3250        assert!(!algo.core.is_strategy_subscribed(&strategy_id));
3251    }
3252
3253    #[rstest]
3254    fn test_algorithm_spawn_limit_creates_valid_order() {
3255        let mut algo = create_test_algorithm();
3256        register_algorithm(&mut algo);
3257
3258        let instrument_id = InstrumentId::from("BTC/USDT.BINANCE");
3259        let mut primary = OrderAny::Market(MarketOrder::new(
3260            TraderId::from("TRADER-001"),
3261            StrategyId::from("STRAT-001"),
3262            instrument_id,
3263            ClientOrderId::from("O-001"),
3264            OrderSide::Buy,
3265            Quantity::from("1.0"),
3266            TimeInForce::Gtc,
3267            UUID4::new(),
3268            0.into(),
3269            false,
3270            false,
3271            None,
3272            None,
3273            None,
3274            None,
3275            None,
3276            None,
3277            None,
3278            None,
3279        ));
3280
3281        let price = Price::from("50000.0");
3282        let spawned = algo
3283            .spawn_limit(
3284                &mut primary,
3285                Quantity::from("0.5"),
3286                price,
3287                TimeInForce::Gtc,
3288                None,  // expire_time
3289                false, // post_only
3290                false, // reduce_only
3291                None,  // display_qty
3292                None,  // emulation_trigger
3293                None,  // tags
3294                false, // reduce_primary
3295            )
3296            .unwrap();
3297
3298        assert_eq!(spawned.client_order_id.as_str(), "O-001-E1");
3299        assert_eq!(spawned.instrument_id, instrument_id);
3300        assert_eq!(spawned.order_side(), OrderSide::Buy);
3301        assert_eq!(spawned.quantity, Quantity::from("0.5"));
3302        assert_eq!(spawned.price, price);
3303        assert_eq!(spawned.time_in_force, TimeInForce::Gtc);
3304        assert_eq!(spawned.exec_algorithm_id, Some(algo.id()));
3305        assert_eq!(spawned.exec_spawn_id, Some(ClientOrderId::from("O-001")));
3306    }
3307
3308    #[rstest]
3309    fn test_algorithm_spawn_market_to_limit_creates_valid_order() {
3310        let mut algo = create_test_algorithm();
3311        register_algorithm(&mut algo);
3312
3313        let instrument_id = InstrumentId::from("BTC/USDT.BINANCE");
3314        let mut primary = OrderAny::Market(MarketOrder::new(
3315            TraderId::from("TRADER-001"),
3316            StrategyId::from("STRAT-001"),
3317            instrument_id,
3318            ClientOrderId::from("O-001"),
3319            OrderSide::Buy,
3320            Quantity::from("1.0"),
3321            TimeInForce::Gtc,
3322            UUID4::new(),
3323            0.into(),
3324            false,
3325            false,
3326            None,
3327            None,
3328            None,
3329            None,
3330            None,
3331            None,
3332            None,
3333            None,
3334        ));
3335
3336        let spawned = algo
3337            .spawn_market_to_limit(
3338                &mut primary,
3339                Quantity::from("0.5"),
3340                TimeInForce::Gtc,
3341                None,  // expire_time
3342                false, // reduce_only
3343                None,  // display_qty
3344                None,  // emulation_trigger
3345                None,  // tags
3346                false, // reduce_primary
3347            )
3348            .unwrap();
3349
3350        assert_eq!(spawned.client_order_id.as_str(), "O-001-E1");
3351        assert_eq!(spawned.instrument_id, instrument_id);
3352        assert_eq!(spawned.order_side(), OrderSide::Buy);
3353        assert_eq!(spawned.quantity, Quantity::from("0.5"));
3354        assert_eq!(spawned.time_in_force, TimeInForce::Gtc);
3355        assert_eq!(spawned.exec_algorithm_id, Some(algo.id()));
3356        assert_eq!(spawned.exec_spawn_id, Some(ClientOrderId::from("O-001")));
3357    }
3358
3359    #[rstest]
3360    fn test_algorithm_spawn_market_with_tags() {
3361        let mut algo = create_test_algorithm();
3362        register_algorithm(&mut algo);
3363
3364        let mut primary = OrderAny::Market(MarketOrder::new(
3365            TraderId::from("TRADER-001"),
3366            StrategyId::from("STRAT-001"),
3367            InstrumentId::from("BTC/USDT.BINANCE"),
3368            ClientOrderId::from("O-001"),
3369            OrderSide::Buy,
3370            Quantity::from("1.0"),
3371            TimeInForce::Gtc,
3372            UUID4::new(),
3373            0.into(),
3374            false,
3375            false,
3376            None,
3377            None,
3378            None,
3379            None,
3380            None,
3381            None,
3382            None,
3383            None,
3384        ));
3385
3386        let tags = vec![ustr::Ustr::from("TAG1"), ustr::Ustr::from("TAG2")];
3387        let spawned = algo
3388            .spawn_market(
3389                &mut primary,
3390                Quantity::from("0.5"),
3391                TimeInForce::Ioc,
3392                false,
3393                Some(tags.clone()),
3394                false,
3395            )
3396            .unwrap();
3397
3398        assert_eq!(spawned.tags, Some(tags));
3399    }
3400
3401    #[rstest]
3402    fn test_algorithm_spawn_propagates_primary_fields() {
3403        let mut algo = create_test_algorithm();
3404        register_algorithm(&mut algo);
3405
3406        let mut params = indexmap::IndexMap::new();
3407        params.insert(ustr::Ustr::from("horizon_secs"), ustr::Ustr::from("30"));
3408        params.insert(ustr::Ustr::from("interval_secs"), ustr::Ustr::from("10"));
3409        let primary_tags = vec![ustr::Ustr::from("PRIMARY_TAG")];
3410        let linked_order_ids = vec![ClientOrderId::from("LINK-1")];
3411        let client_order_id = ClientOrderId::from("O-001");
3412
3413        let mut primary = OrderAny::Market(MarketOrder::new(
3414            TraderId::from("TRADER-001"),
3415            StrategyId::from("STRAT-001"),
3416            InstrumentId::from("BTC/USDT.BINANCE"),
3417            client_order_id,
3418            OrderSide::Buy,
3419            Quantity::from("1.0"),
3420            TimeInForce::Gtc,
3421            UUID4::new(),
3422            0.into(),
3423            false, // reduce_only
3424            true,  // quote_quantity
3425            None,  // contingency_type
3426            None,  // order_list_id
3427            Some(linked_order_ids.clone()),
3428            None, // parent_order_id
3429            Some(algo.id()),
3430            Some(params.clone()),
3431            Some(client_order_id),
3432            Some(primary_tags.clone()),
3433        ));
3434
3435        let spawned_market = algo
3436            .spawn_market(
3437                &mut primary,
3438                Quantity::from("0.25"),
3439                TimeInForce::Ioc,
3440                false,
3441                None, // falls back to primary.tags
3442                false,
3443            )
3444            .unwrap();
3445        assert!(spawned_market.is_quote_quantity);
3446        assert_eq!(spawned_market.exec_algorithm_params, Some(params.clone()));
3447        assert_eq!(spawned_market.tags, Some(primary_tags.clone()));
3448        assert_eq!(
3449            spawned_market.linked_order_ids,
3450            Some(linked_order_ids.clone())
3451        );
3452
3453        let spawned_limit = algo
3454            .spawn_limit(
3455                &mut primary,
3456                Quantity::from("0.25"),
3457                Price::from("50000.0"),
3458                TimeInForce::Gtc,
3459                None,  // expire_time
3460                false, // post_only
3461                false, // reduce_only
3462                None,  // display_qty
3463                None,  // emulation_trigger
3464                None,  // falls back to primary.tags
3465                false,
3466            )
3467            .unwrap();
3468        assert!(spawned_limit.is_quote_quantity);
3469        assert_eq!(spawned_limit.exec_algorithm_params, Some(params.clone()));
3470        assert_eq!(spawned_limit.tags, Some(primary_tags.clone()));
3471        assert_eq!(
3472            spawned_limit.linked_order_ids,
3473            Some(linked_order_ids.clone())
3474        );
3475
3476        let spawned_mtl = algo
3477            .spawn_market_to_limit(
3478                &mut primary,
3479                Quantity::from("0.25"),
3480                TimeInForce::Gtc,
3481                None,  // expire_time
3482                false, // reduce_only
3483                None,  // display_qty
3484                None,  // emulation_trigger
3485                None,  // falls back to primary.tags
3486                false,
3487            )
3488            .unwrap();
3489        assert!(spawned_mtl.is_quote_quantity);
3490        assert_eq!(spawned_mtl.exec_algorithm_params, Some(params));
3491        assert_eq!(spawned_mtl.tags, Some(primary_tags));
3492        assert_eq!(spawned_mtl.linked_order_ids, Some(linked_order_ids));
3493    }
3494
3495    #[rstest]
3496    fn test_muldiv_floor_u128_narrow_path_truncates() {
3497        assert_eq!(muldiv_floor_u128(50, 3, 5), 30);
3498        assert_eq!(muldiv_floor_u128(10, 2, 3), 6);
3499        assert_eq!(muldiv_floor_u128(u128::MAX, 7, 7), u128::MAX);
3500    }
3501
3502    #[rstest]
3503    fn test_muldiv_floor_u128_wide_path_floors_exactly() {
3504        // a * b overflows u128; the exact quotient is a - a/c, fractionally
3505        // under a, so an implementation that rounds instead of flooring
3506        // returns a. This is the shape of the Decimal-fallback defect.
3507        let a = 10u128.pow(30);
3508        let b = 7 * 10u128.pow(30);
3509        let c = b + 1;
3510        assert!(a.checked_mul(b).is_none());
3511        assert_eq!(muldiv_floor_u128(a, b, c), a - 1);
3512    }
3513
3514    #[rstest]
3515    fn test_algorithm_reduce_primary_order() {
3516        let mut algo = create_test_algorithm();
3517        register_algorithm(&mut algo);
3518
3519        let order = OrderAny::Market(MarketOrder::new(
3520            TraderId::from("TRADER-001"),
3521            StrategyId::from("STRAT-001"),
3522            InstrumentId::from("BTC/USDT.BINANCE"),
3523            ClientOrderId::from("O-001"),
3524            OrderSide::Buy,
3525            Quantity::from("1.0"),
3526            TimeInForce::Gtc,
3527            UUID4::new(),
3528            0.into(),
3529            false,
3530            false,
3531            None,
3532            None,
3533            None,
3534            None,
3535            None,
3536            None,
3537            None,
3538            None,
3539        ));
3540
3541        // Make accepted so OrderUpdated can be applied
3542        let mut primary = TestOrderStubs::make_accepted_order(&order);
3543
3544        {
3545            let cache_rc = algo.core.cache_rc();
3546            let mut cache = cache_rc.borrow_mut();
3547            cache.add_order(primary.clone(), None, None, false).unwrap();
3548        }
3549
3550        let spawn_qty = Quantity::from("0.3");
3551        algo.reduce_primary_order(&mut primary, spawn_qty);
3552
3553        assert_eq!(primary.quantity(), Quantity::from("0.7"));
3554    }
3555
3556    #[rstest]
3557    fn test_algorithm_reduce_primary_order_publishes_updated_event() {
3558        let mut algo = create_test_algorithm();
3559        register_algorithm(&mut algo);
3560
3561        let strategy_id = StrategyId::from("STRAT-ALGO-REDUCE-PUBLISH");
3562        let order = OrderAny::Market(MarketOrder::new(
3563            TraderId::from("TRADER-001"),
3564            strategy_id,
3565            InstrumentId::from("BTC/USDT.BINANCE"),
3566            ClientOrderId::from("O-ALGO-REDUCE"),
3567            OrderSide::Buy,
3568            Quantity::from("1.0"),
3569            TimeInForce::Gtc,
3570            UUID4::new(),
3571            0.into(),
3572            false,
3573            false,
3574            None,
3575            None,
3576            None,
3577            None,
3578            None,
3579            None,
3580            None,
3581            None,
3582        ));
3583        let mut primary = TestOrderStubs::make_accepted_order(&order);
3584
3585        {
3586            let cache_rc = algo.core.cache_rc();
3587            let mut cache = cache_rc.borrow_mut();
3588            cache.add_order(primary.clone(), None, None, false).unwrap();
3589        }
3590
3591        let (handler, events) = subscribe_order_topic(strategy_id);
3592
3593        algo.reduce_primary_order(&mut primary, Quantity::from("0.3"));
3594
3595        msgbus::unsubscribe_order_events(format!("events.order.{strategy_id}").into(), &handler);
3596        let events = events.borrow();
3597
3598        assert_eq!(events.len(), 1);
3599        assert!(matches!(
3600            &events[0],
3601            OrderEventAny::Updated(event) if event.quantity == Quantity::from("0.7")
3602        ));
3603    }
3604
3605    #[rstest]
3606    #[case::submitted(OrderStatus::Submitted)]
3607    #[case::accepted(OrderStatus::Accepted)]
3608    #[case::canceled(OrderStatus::Canceled)]
3609    fn test_algorithm_submit_order_rejects_retained_initialized_order_with_non_local_cached_order(
3610        #[case] status: OrderStatus,
3611    ) {
3612        let mut algo = create_test_algorithm();
3613        register_algorithm(&mut algo);
3614        let order = OrderTestBuilder::new(OrderType::Market)
3615            .client_order_id(ClientOrderId::from("O-ALGO-RETAINED-ACCEPTED"))
3616            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
3617            .strategy_id(StrategyId::from("TEST-001"))
3618            .side(OrderSide::Buy)
3619            .quantity(Quantity::from("1.25"))
3620            .build();
3621        let client_order_id = order.client_order_id();
3622        let (risk_handler, risk_messages): (_, TypedIntoMessageSavingHandler<TradingCommand>) =
3623            get_typed_into_message_saving_handler(Some(Ustr::from("RiskEngine.queue_execute")));
3624        msgbus::register_trading_command_endpoint(
3625            MessagingSwitchboard::risk_engine_queue_execute(),
3626            risk_handler,
3627        );
3628        let (handler, events) = subscribe_order_topic(order.strategy_id());
3629
3630        algo.submit_order(order.clone(), None, None).unwrap();
3631        let mut before = order.clone();
3632        submit_order_in_cache(&mut algo, &mut before);
3633        if status != OrderStatus::Submitted {
3634            accept_spawned_order(&mut algo, &mut before);
3635        }
3636
3637        if status == OrderStatus::Canceled {
3638            cancel_spawned_order(&mut algo, &mut before);
3639        }
3640
3641        let snapshot = serde_json::to_value(&before).unwrap();
3642
3643        let result = algo.submit_order(order.clone(), None, None);
3644
3645        msgbus::unsubscribe_order_events(
3646            format!("events.order.{}", order.strategy_id()).into(),
3647            &handler,
3648        );
3649        let cache = algo.cache();
3650        let cached = cache.order(&client_order_id).unwrap();
3651        assert_eq!(
3652            result.unwrap_err().to_string(),
3653            format!("Order denied: duplicate {client_order_id}")
3654        );
3655        assert_eq!(risk_messages.get_messages().len(), 1);
3656        assert_eq!(
3657            *events.borrow(),
3658            vec![OrderEventAny::Initialized(order.init_event().clone())]
3659        );
3660        assert_eq!(cached.status(), status);
3661        assert_eq!(cached.events(), before.events());
3662        assert_eq!(serde_json::to_value(&cached).unwrap(), snapshot);
3663    }
3664
3665    #[rstest]
3666    #[case::initialized(OrderStatus::Initialized)]
3667    #[case::emulated(OrderStatus::Emulated)]
3668    #[case::released(OrderStatus::Released)]
3669    fn test_algorithm_submit_order_replaces_active_local_cached_order(#[case] status: OrderStatus) {
3670        let mut algo = create_test_algorithm();
3671        register_algorithm(&mut algo);
3672        let client_order_id = ClientOrderId::from("O-LOCAL-REPLACE");
3673        let mut local = OrderTestBuilder::new(OrderType::StopMarket)
3674            .instrument_id(InstrumentId::from("BTCUSDT.BINANCE"))
3675            .strategy_id(StrategyId::from("TEST-001"))
3676            .client_order_id(client_order_id)
3677            .side(OrderSide::Sell)
3678            .quantity(Quantity::from("1.25"))
3679            .trigger_price(Price::from("51000.0"))
3680            .emulation_trigger(TriggerType::BidAsk)
3681            .build();
3682
3683        if status == OrderStatus::Emulated {
3684            let event = OrderEmulatedSpec::builder()
3685                .trader_id(local.trader_id())
3686                .strategy_id(local.strategy_id())
3687                .instrument_id(local.instrument_id())
3688                .client_order_id(client_order_id)
3689                .build();
3690            local.apply(OrderEventAny::Emulated(event)).unwrap();
3691        } else if status == OrderStatus::Released {
3692            let event = OrderReleasedSpec::builder()
3693                .trader_id(local.trader_id())
3694                .strategy_id(local.strategy_id())
3695                .instrument_id(local.instrument_id())
3696                .client_order_id(client_order_id)
3697                .released_price(Price::from("51001.0"))
3698                .build();
3699            local.apply(OrderEventAny::Released(event)).unwrap();
3700        }
3701
3702        let cache_rc = algo.core.cache_rc();
3703        cache_rc
3704            .borrow_mut()
3705            .add_order(local.clone(), None, None, false)
3706            .unwrap();
3707        let order = OrderTestBuilder::new(OrderType::Market)
3708            .instrument_id(local.instrument_id())
3709            .strategy_id(local.strategy_id())
3710            .client_order_id(client_order_id)
3711            .side(OrderSide::Buy)
3712            .quantity(Quantity::from("2.50"))
3713            .build();
3714        let (risk_handler, risk_messages): (_, TypedIntoMessageSavingHandler<TradingCommand>) =
3715            get_typed_into_message_saving_handler(Some(Ustr::from("RiskEngine.queue_execute")));
3716        msgbus::register_trading_command_endpoint(
3717            MessagingSwitchboard::risk_engine_queue_execute(),
3718            risk_handler,
3719        );
3720
3721        algo.submit_order(order.clone(), None, None).unwrap();
3722
3723        let cache = cache_rc.borrow();
3724        let cached = cache.order(&client_order_id).unwrap();
3725        assert_eq!(local.status(), status);
3726        assert_eq!(cached.status(), OrderStatus::Initialized);
3727        assert_eq!(cached.events(), order.events());
3728        assert_eq!(
3729            serde_json::to_value(&*cached).unwrap(),
3730            serde_json::to_value(&order).unwrap()
3731        );
3732        let messages = risk_messages.get_messages();
3733        assert_eq!(messages.len(), 1);
3734
3735        let TradingCommand::SubmitOrder(command) = &messages[0] else {
3736            panic!("Expected SubmitOrder");
3737        };
3738
3739        assert_eq!(command.order_init, *order.init_event());
3740    }
3741
3742    #[rstest]
3743    fn test_algorithm_submit_order_publishes_initialized_for_new_order() {
3744        let mut algo = create_test_algorithm();
3745        register_algorithm(&mut algo);
3746
3747        let strategy_id = StrategyId::from("STRAT-ALGO-INIT-PUBLISH");
3748        let order = OrderAny::Market(MarketOrder::new(
3749            TraderId::from("TRADER-001"),
3750            strategy_id,
3751            InstrumentId::from("BTC/USDT.BINANCE"),
3752            ClientOrderId::from("O-ALGO-INIT"),
3753            OrderSide::Buy,
3754            Quantity::from("1.0"),
3755            TimeInForce::Gtc,
3756            UUID4::new(),
3757            0.into(),
3758            false,
3759            false,
3760            None,
3761            None,
3762            None,
3763            None,
3764            None,
3765            None,
3766            None,
3767            None,
3768        ));
3769        let (handler, events) = subscribe_order_topic(strategy_id);
3770
3771        algo.submit_order(order.clone(), None, None).unwrap();
3772
3773        msgbus::unsubscribe_order_events(format!("events.order.{strategy_id}").into(), &handler);
3774        let events = events.borrow();
3775
3776        assert_eq!(events.len(), 1);
3777        assert!(matches!(
3778            &events[0],
3779            OrderEventAny::Initialized(event) if event.client_order_id == order.client_order_id()
3780        ));
3781    }
3782
3783    #[rstest]
3784    fn test_algorithm_submit_order_does_not_republish_initialized_for_existing_order() {
3785        let mut algo = create_test_algorithm();
3786        register_algorithm(&mut algo);
3787
3788        let strategy_id = StrategyId::from("STRAT-ALGO-INIT-EXISTING");
3789        let order = OrderAny::Market(MarketOrder::new(
3790            TraderId::from("TRADER-001"),
3791            strategy_id,
3792            InstrumentId::from("BTC/USDT.BINANCE"),
3793            ClientOrderId::from("O-ALGO-INIT-EXISTING"),
3794            OrderSide::Buy,
3795            Quantity::from("1.0"),
3796            TimeInForce::Gtc,
3797            UUID4::new(),
3798            0.into(),
3799            false,
3800            false,
3801            None,
3802            None,
3803            None,
3804            None,
3805            None,
3806            None,
3807            None,
3808            None,
3809        ));
3810        {
3811            let cache_rc = algo.core.cache_rc();
3812            let mut cache = cache_rc.borrow_mut();
3813            cache.add_order(order.clone(), None, None, true).unwrap();
3814        }
3815        let (handler, events) = subscribe_order_topic(strategy_id);
3816
3817        algo.submit_order(order, None, None).unwrap();
3818
3819        msgbus::unsubscribe_order_events(format!("events.order.{strategy_id}").into(), &handler);
3820        assert!(events.borrow().is_empty());
3821    }
3822
3823    #[rstest]
3824    fn test_algorithm_submit_order_rejects_accepted_emulated_spawn_before_restoring_primary() {
3825        let (mut algo, primary_id, _) = setup_pending_spawn();
3826        let mut primary = algo.cache().order(&primary_id).unwrap();
3827        let spawned = algo
3828            .spawn_limit(
3829                &mut primary,
3830                Quantity::from("0.2"),
3831                Price::from("50000.0"),
3832                TimeInForce::Gtc,
3833                None,
3834                false,
3835                false,
3836                None,
3837                Some(TriggerType::BidAsk),
3838                None,
3839                true,
3840            )
3841            .unwrap();
3842        let retained = OrderAny::Limit(spawned);
3843        let mut accepted = retained.clone();
3844        accepted.set_emulation_trigger(None);
3845        let (risk_handler, risk_messages): (_, TypedIntoMessageSavingHandler<TradingCommand>) =
3846            get_typed_into_message_saving_handler(Some(Ustr::from("RiskEngine.queue_execute")));
3847        msgbus::register_trading_command_endpoint(
3848            MessagingSwitchboard::risk_engine_queue_execute(),
3849            risk_handler,
3850        );
3851
3852        algo.submit_order(accepted.clone(), None, None).unwrap();
3853        submit_order_in_cache(&mut algo, &mut accepted);
3854        accept_spawned_order(&mut algo, &mut accepted);
3855        let primary_before = algo.cache().order(&primary_id).unwrap();
3856        let (handler, events) = subscribe_order_topic(retained.strategy_id());
3857
3858        let result = algo.submit_order(retained.clone(), None, None);
3859
3860        msgbus::unsubscribe_order_events(
3861            format!("events.order.{}", retained.strategy_id()).into(),
3862            &handler,
3863        );
3864        let cache = algo.cache();
3865        let primary_after = cache.order(&primary_id).unwrap();
3866        let cached = cache.order(&retained.client_order_id()).unwrap();
3867        assert_eq!(
3868            result.unwrap_err().to_string(),
3869            format!("Order denied: duplicate {}", retained.client_order_id())
3870        );
3871        assert_eq!(risk_messages.get_messages().len(), 1);
3872        assert!(events.borrow().is_empty());
3873        assert_eq!(primary_after.quantity(), Quantity::from("0.3"));
3874        assert_eq!(primary_after.events(), primary_before.events());
3875        assert_eq!(
3876            serde_json::to_value(&primary_after).unwrap(),
3877            serde_json::to_value(&primary_before).unwrap()
3878        );
3879        assert_eq!(cached.status(), OrderStatus::Accepted);
3880        assert_eq!(cached.events(), accepted.events());
3881        assert_eq!(
3882            serde_json::to_value(&cached).unwrap(),
3883            serde_json::to_value(&accepted).unwrap()
3884        );
3885    }
3886
3887    #[rstest]
3888    fn test_algorithm_submit_order_refuses_emulated_limit_spawn() {
3889        let mut algo = create_test_algorithm();
3890        register_algorithm(&mut algo);
3891
3892        let strategy_id = StrategyId::from("STRAT-ALGO-EMULATED-LIMIT");
3893        let order = OrderTestBuilder::new(OrderType::Market)
3894            .strategy_id(strategy_id)
3895            .instrument_id(InstrumentId::from("BTC/USDT.BINANCE"))
3896            .client_order_id(ClientOrderId::from("O-ALGO-EMULATED-LIMIT"))
3897            .quantity(Quantity::from("1.0"))
3898            .build();
3899        let mut primary = TestOrderStubs::make_accepted_order(&order);
3900        {
3901            let cache_rc = algo.core.cache_rc();
3902            let mut cache = cache_rc.borrow_mut();
3903            cache.add_order(primary.clone(), None, None, false).unwrap();
3904        }
3905        let (event_handler, events) = subscribe_order_topic(strategy_id);
3906        let (risk_handler, risk_messages): (_, TypedIntoMessageSavingHandler<TradingCommand>) =
3907            get_typed_into_message_saving_handler(Some(Ustr::from("RiskEngine.queue_execute")));
3908        msgbus::register_trading_command_endpoint(
3909            MessagingSwitchboard::risk_engine_queue_execute(),
3910            risk_handler,
3911        );
3912        let (emulator_handler, emulator_messages): (
3913            _,
3914            TypedIntoMessageSavingHandler<TradingCommand>,
3915        ) = get_typed_into_message_saving_handler(Some(Ustr::from("OrderEmulator.execute")));
3916        msgbus::register_trading_command_endpoint(
3917            MessagingSwitchboard::order_emulator_execute(),
3918            emulator_handler,
3919        );
3920
3921        let spawned = algo
3922            .spawn_limit(
3923                &mut primary,
3924                Quantity::from("0.4"),
3925                Price::from("50000.0"),
3926                TimeInForce::Gtc,
3927                None,
3928                false,
3929                false,
3930                None,
3931                Some(TriggerType::BidAsk),
3932                None,
3933                true,
3934            )
3935            .unwrap();
3936        let spawned = OrderAny::Limit(spawned);
3937        let client_order_id = spawned.client_order_id();
3938        let result = algo.submit_order(spawned, None, None);
3939
3940        msgbus::unsubscribe_order_events(
3941            format!("events.order.{strategy_id}").into(),
3942            &event_handler,
3943        );
3944        let cache = algo.core.cache_ref();
3945        let error = result.unwrap_err();
3946        assert!(
3947            error
3948                .downcast_ref::<EmulatedOrderSubmissionError>()
3949                .is_some()
3950        );
3951        let error = error.to_string();
3952        assert!(error.contains("live emulation trigger"), "{error}");
3953        assert!(error.contains(client_order_id.as_str()), "{error}");
3954        assert!(risk_messages.get_messages().is_empty());
3955        assert!(emulator_messages.get_messages().is_empty());
3956        assert!(!cache.order_exists(&client_order_id));
3957        assert!(!events.borrow().iter().any(|event| matches!(
3958            event,
3959            OrderEventAny::Initialized(initialized)
3960                if initialized.client_order_id == client_order_id
3961        )));
3962        // The spawn already reduced the accepted primary locally (the venue
3963        // still works 1.0); restoration declines to mutate a non-local
3964        // primary, so the local deduction stands.
3965        assert_eq!(
3966            cache.order(&primary.client_order_id()).unwrap().quantity(),
3967            Quantity::from("0.6"),
3968        );
3969        drop(cache);
3970        assert!(
3971            algo.core
3972                .take_pending_spawn_reduction(client_order_id)
3973                .is_none()
3974        );
3975    }
3976
3977    #[rstest]
3978    fn test_algorithm_submit_order_routes_unemulated_spawn_to_risk() {
3979        let mut algo = create_test_algorithm();
3980        register_algorithm(&mut algo);
3981
3982        let mut primary = OrderTestBuilder::new(OrderType::Market)
3983            .instrument_id(InstrumentId::from("BTC/USDT.BINANCE"))
3984            .client_order_id(ClientOrderId::from("O-ALGO-UNEMULATED"))
3985            .quantity(Quantity::from("1.0"))
3986            .build();
3987        let (risk_handler, risk_messages): (_, TypedIntoMessageSavingHandler<TradingCommand>) =
3988            get_typed_into_message_saving_handler(Some(Ustr::from("RiskEngine.queue_execute")));
3989        msgbus::register_trading_command_endpoint(
3990            MessagingSwitchboard::risk_engine_queue_execute(),
3991            risk_handler,
3992        );
3993
3994        let spawned = algo
3995            .spawn_limit(
3996                &mut primary,
3997                Quantity::from("0.4"),
3998                Price::from("50000.0"),
3999                TimeInForce::Gtc,
4000                None,
4001                false,
4002                false,
4003                None,
4004                None,
4005                None,
4006                false,
4007            )
4008            .unwrap();
4009        let client_order_id = spawned.client_order_id;
4010        algo.submit_order(OrderAny::Limit(spawned), None, None)
4011            .unwrap();
4012
4013        let risk_messages = risk_messages.get_messages();
4014        assert_eq!(risk_messages.len(), 1);
4015        assert!(matches!(
4016            risk_messages.first(),
4017            Some(TradingCommand::SubmitOrder(command))
4018                if command.client_order_id == client_order_id
4019        ));
4020    }
4021
4022    #[rstest]
4023    fn test_algorithm_spawn_market_with_reduce_primary() {
4024        let mut algo = create_test_algorithm();
4025        register_algorithm(&mut algo);
4026
4027        let order = OrderAny::Market(MarketOrder::new(
4028            TraderId::from("TRADER-001"),
4029            StrategyId::from("STRAT-001"),
4030            InstrumentId::from("BTC/USDT.BINANCE"),
4031            ClientOrderId::from("O-001"),
4032            OrderSide::Buy,
4033            Quantity::from("1.0"),
4034            TimeInForce::Gtc,
4035            UUID4::new(),
4036            0.into(),
4037            false,
4038            false,
4039            None,
4040            None,
4041            None,
4042            None,
4043            None,
4044            None,
4045            None,
4046            None,
4047        ));
4048
4049        // Make accepted so OrderUpdated can be applied
4050        let mut primary = TestOrderStubs::make_accepted_order(&order);
4051
4052        {
4053            let cache_rc = algo.core.cache_rc();
4054            let mut cache = cache_rc.borrow_mut();
4055            cache.add_order(primary.clone(), None, None, false).unwrap();
4056        }
4057
4058        let spawned = algo
4059            .spawn_market(
4060                &mut primary,
4061                Quantity::from("0.4"),
4062                TimeInForce::Ioc,
4063                false,
4064                None,
4065                true, // reduce_primary = true
4066            )
4067            .unwrap();
4068
4069        assert_eq!(spawned.quantity, Quantity::from("0.4"));
4070        assert_eq!(primary.quantity(), Quantity::from("0.6"));
4071    }
4072    #[rstest]
4073    fn test_algorithm_forwards_captured_params_to_spawned_order() {
4074        let mut algo = create_test_algorithm();
4075        register_algorithm(&mut algo);
4076
4077        let strategy_id = StrategyId::from("STRAT-FWD-001");
4078        let mut primary = OrderAny::Market(MarketOrder::new(
4079            TraderId::from("TRADER-001"),
4080            strategy_id,
4081            InstrumentId::from("BTC/USDT.BINANCE"),
4082            ClientOrderId::from("O-FWD-001"),
4083            OrderSide::Buy,
4084            Quantity::from("1.0"),
4085            TimeInForce::Gtc,
4086            UUID4::new(),
4087            0.into(),
4088            false,
4089            false,
4090            None,
4091            None,
4092            None,
4093            None,
4094            None,
4095            None,
4096            None,
4097            None,
4098        ));
4099        {
4100            let cache_rc = algo.core.cache_rc();
4101            let mut cache = cache_rc.borrow_mut();
4102            cache.add_order(primary.clone(), None, None, true).unwrap();
4103        }
4104
4105        let params = nautilus_core::Params::new(
4106            [("is_leverage".to_string(), serde_json::Value::Bool(true))].into(),
4107        );
4108
4109        let command = SubmitOrder::new(
4110            TraderId::from("TRADER-001"),
4111            None,
4112            strategy_id,
4113            primary.instrument_id(),
4114            primary.client_order_id(),
4115            primary.init_event().clone(),
4116            primary.exec_algorithm_id(),
4117            None,
4118            Some(params),
4119            UUID4::new(),
4120            0.into(),
4121            None,
4122        );
4123        algo.execute(TradingCommand::SubmitOrder(command)).unwrap();
4124
4125        let received = Rc::new(RefCell::new(None::<SubmitOrder>));
4126        let handler = msgbus::TypedIntoHandler::from({
4127            let captured = received.clone();
4128            move |cmd: TradingCommand| {
4129                if let TradingCommand::SubmitOrder(cmd) = cmd {
4130                    *captured.borrow_mut() = Some(cmd);
4131                }
4132            }
4133        });
4134        msgbus::register_trading_command_endpoint(
4135            MessagingSwitchboard::risk_engine_queue_execute(),
4136            handler,
4137        );
4138
4139        let spawned = algo
4140            .spawn_market(
4141                &mut primary,
4142                Quantity::from("0.4"),
4143                TimeInForce::Ioc,
4144                false,
4145                None,
4146                false, // reduce_primary
4147            )
4148            .unwrap();
4149        algo.submit_order(OrderAny::Market(spawned), None, None)
4150            .unwrap();
4151
4152        let captured = received.borrow();
4153        let cmd = captured.as_ref().expect("expected a forwarded SubmitOrder");
4154        assert_eq!(cmd.client_order_id, ClientOrderId::from("O-FWD-001-E1"));
4155        assert_eq!(
4156            cmd.params.as_ref().and_then(|p| p.get_bool("is_leverage")),
4157            Some(true),
4158        );
4159    }
4160
4161    #[rstest]
4162    fn test_algorithm_routes_modify_and_cancel_commands_through_engine_queues() {
4163        let mut modify_algo = create_test_algorithm();
4164        let mut cancel_algo = create_test_algorithm();
4165        register_algorithm(&mut modify_algo);
4166        register_algorithm(&mut cancel_algo);
4167
4168        let (risk_handler, risk_messages): (_, TypedIntoMessageSavingHandler<TradingCommand>) =
4169            get_typed_into_message_saving_handler(Some(Ustr::from("RiskEngine.queue_execute")));
4170        msgbus::register_trading_command_endpoint(
4171            MessagingSwitchboard::risk_engine_queue_execute(),
4172            risk_handler,
4173        );
4174        let (exec_handler, exec_messages): (_, TypedIntoMessageSavingHandler<TradingCommand>) =
4175            get_typed_into_message_saving_handler(Some(Ustr::from("ExecEngine.queue_execute")));
4176        msgbus::register_trading_command_endpoint(
4177            MessagingSwitchboard::exec_engine_queue_execute(),
4178            exec_handler,
4179        );
4180
4181        let mut modify_order = TestOrderStubs::make_accepted_order(
4182            &OrderTestBuilder::new(OrderType::Limit)
4183                .strategy_id(StrategyId::from("STRAT-ALGO-ROUTING"))
4184                .instrument_id(InstrumentId::from("BTC/USDT.BINANCE"))
4185                .client_order_id(ClientOrderId::from("O-ALGO-MODIFY"))
4186                .quantity(Quantity::from("1.0"))
4187                .price(Price::from("50000.0"))
4188                .build(),
4189        );
4190        let mut cancel_order = TestOrderStubs::make_accepted_order(
4191            &OrderTestBuilder::new(OrderType::Market)
4192                .strategy_id(StrategyId::from("STRAT-ALGO-ROUTING"))
4193                .instrument_id(InstrumentId::from("BTC/USDT.BINANCE"))
4194                .client_order_id(ClientOrderId::from("O-ALGO-CANCEL"))
4195                .quantity(Quantity::from("1.0"))
4196                .build(),
4197        );
4198        {
4199            let cache_rc = modify_algo.core.cache_rc();
4200            let mut cache = cache_rc.borrow_mut();
4201            cache
4202                .add_order(modify_order.clone(), None, None, false)
4203                .unwrap();
4204        }
4205        {
4206            let cache_rc = cancel_algo.core.cache_rc();
4207            let mut cache = cache_rc.borrow_mut();
4208            cache
4209                .add_order(cancel_order.clone(), None, None, false)
4210                .unwrap();
4211        }
4212
4213        modify_algo
4214            .modify_order(
4215                &mut modify_order,
4216                None,
4217                Some(Price::from("51000.0")),
4218                None,
4219                None,
4220            )
4221            .unwrap();
4222        cancel_algo.cancel_order(&mut cancel_order, None).unwrap();
4223
4224        let risk_messages = risk_messages.get_messages();
4225        let exec_messages = exec_messages.get_messages();
4226        assert_eq!(risk_messages.len(), 1);
4227        assert!(matches!(
4228            risk_messages.first(),
4229            Some(TradingCommand::ModifyOrder(command))
4230                if command.client_order_id == modify_order.client_order_id()
4231        ));
4232        assert_eq!(exec_messages.len(), 1);
4233        assert!(matches!(
4234            exec_messages.first(),
4235            Some(TradingCommand::CancelOrder(command))
4236                if command.client_order_id == cancel_order.client_order_id()
4237        ));
4238    }
4239
4240    #[rstest]
4241    fn test_algorithm_submit_order_list_captures_params_per_order() {
4242        use nautilus_common::messages::execution::SubmitOrderList;
4243        use nautilus_model::identifiers::OrderListId;
4244
4245        let mut algo = create_test_algorithm();
4246        register_algorithm(&mut algo);
4247
4248        let strategy_id = StrategyId::from("STRAT-LIST-001");
4249        let order1 = OrderAny::Market(MarketOrder::new(
4250            TraderId::from("TRADER-001"),
4251            strategy_id,
4252            InstrumentId::from("BTC/USDT.BINANCE"),
4253            ClientOrderId::from("O-LIST-001"),
4254            OrderSide::Buy,
4255            Quantity::from("1.0"),
4256            TimeInForce::Gtc,
4257            UUID4::new(),
4258            0.into(),
4259            false,
4260            false,
4261            None,
4262            None,
4263            None,
4264            None,
4265            None,
4266            None,
4267            None,
4268            None,
4269        ));
4270        let order2 = OrderAny::Market(MarketOrder::new(
4271            TraderId::from("TRADER-001"),
4272            strategy_id,
4273            InstrumentId::from("BTC/USDT.BINANCE"),
4274            ClientOrderId::from("O-LIST-002"),
4275            OrderSide::Buy,
4276            Quantity::from("1.0"),
4277            TimeInForce::Gtc,
4278            UUID4::new(),
4279            0.into(),
4280            false,
4281            false,
4282            None,
4283            None,
4284            None,
4285            None,
4286            None,
4287            None,
4288            None,
4289            None,
4290        ));
4291        {
4292            let cache_rc = algo.core.cache_rc();
4293            let mut cache = cache_rc.borrow_mut();
4294            cache.add_order(order1.clone(), None, None, true).unwrap();
4295            cache.add_order(order2.clone(), None, None, true).unwrap();
4296        }
4297
4298        let order_list = OrderList::new(
4299            OrderListId::from("OL-001"),
4300            order1.instrument_id(),
4301            strategy_id,
4302            vec![order1.client_order_id(), order2.client_order_id()],
4303            0.into(),
4304        );
4305
4306        let params = nautilus_core::Params::new(
4307            [("is_leverage".to_string(), serde_json::Value::Bool(true))].into(),
4308        );
4309
4310        let command = SubmitOrderList::new(
4311            TraderId::from("TRADER-001"),
4312            None,
4313            strategy_id,
4314            order_list,
4315            vec![order1.init_event().clone(), order2.init_event().clone()],
4316            order1.exec_algorithm_id(),
4317            None,
4318            Some(params),
4319            UUID4::new(),
4320            0.into(),
4321            None,
4322        );
4323        algo.execute(TradingCommand::SubmitOrderList(command))
4324            .unwrap();
4325
4326        assert_eq!(
4327            algo.order_client_ids,
4328            [
4329                ClientOrderId::from("O-LIST-001"),
4330                ClientOrderId::from("O-LIST-002"),
4331            ],
4332        );
4333
4334        for id in ["O-LIST-001", "O-LIST-002"] {
4335            assert_eq!(
4336                algo.core
4337                    .submit_params(&ClientOrderId::from(id))
4338                    .and_then(|p| p.get_bool("is_leverage")),
4339                Some(true),
4340                "expected forwarded params for {id}",
4341            );
4342        }
4343    }
4344
4345    #[rstest]
4346    fn test_algorithm_generate_order_canceled() {
4347        let mut algo = create_test_algorithm();
4348        register_algorithm(&mut algo);
4349
4350        let order = OrderAny::Market(MarketOrder::new(
4351            TraderId::from("TRADER-001"),
4352            StrategyId::from("STRAT-001"),
4353            InstrumentId::from("BTC/USDT.BINANCE"),
4354            ClientOrderId::from("O-001"),
4355            OrderSide::Buy,
4356            Quantity::from("1.0"),
4357            TimeInForce::Gtc,
4358            UUID4::new(),
4359            0.into(),
4360            false,
4361            false,
4362            None,
4363            None,
4364            None,
4365            None,
4366            None,
4367            None,
4368            None,
4369            None,
4370        ));
4371
4372        let event = algo.generate_order_canceled(&order);
4373
4374        assert_eq!(event.trader_id, TraderId::from("TRADER-001"));
4375        assert_eq!(event.strategy_id, StrategyId::from("STRAT-001"));
4376        assert_eq!(event.instrument_id, InstrumentId::from("BTC/USDT.BINANCE"));
4377        assert_eq!(event.client_order_id, ClientOrderId::from("O-001"));
4378    }
4379
4380    #[rstest]
4381    fn test_algorithm_handle_cancel_order_publishes_instrument_canceled_topic() {
4382        let mut algo = create_test_algorithm();
4383        register_algorithm(&mut algo);
4384
4385        let strategy_id = StrategyId::from("STRAT-ALGO-CANCEL-PUBLISH");
4386        let instrument_id = InstrumentId::from("BTC/USDT.BINANCE");
4387        let order = OrderAny::Market(MarketOrder::new(
4388            TraderId::from("TRADER-001"),
4389            strategy_id,
4390            instrument_id,
4391            ClientOrderId::from("O-ALGO-CANCEL"),
4392            OrderSide::Buy,
4393            Quantity::from("1.0"),
4394            TimeInForce::Gtc,
4395            UUID4::new(),
4396            0.into(),
4397            false,
4398            false,
4399            None,
4400            None,
4401            None,
4402            None,
4403            None,
4404            None,
4405            None,
4406            None,
4407        ));
4408        let order = TestOrderStubs::make_accepted_order(&order);
4409
4410        {
4411            let cache_rc = algo.core.cache_rc();
4412            let mut cache = cache_rc.borrow_mut();
4413            cache.add_order(order.clone(), None, None, false).unwrap();
4414        }
4415
4416        let received = Rc::new(RefCell::new(Vec::<OrderEventAny>::new()));
4417        let handler = TypedHandler::from({
4418            let received = received.clone();
4419            move |event: &OrderEventAny| {
4420                received.borrow_mut().push(event.clone());
4421            }
4422        });
4423        let topic = msgbus::switchboard::get_order_canceled_topic(instrument_id);
4424        msgbus::subscribe_order_events(topic.into(), handler.clone(), None);
4425
4426        let command = CancelOrder::new(
4427            order.trader_id(),
4428            None,
4429            strategy_id,
4430            instrument_id,
4431            order.client_order_id(),
4432            order.venue_order_id(),
4433            UUID4::new(),
4434            0.into(),
4435            None,
4436            None,
4437        );
4438        algo.handle_cancel_order(command).unwrap();
4439
4440        msgbus::unsubscribe_order_events(topic.into(), &handler);
4441        let received = received.borrow();
4442        assert_eq!(received.len(), 1);
4443        assert!(matches!(received[0], OrderEventAny::Canceled(_)));
4444        assert_eq!(received[0].client_order_id(), order.client_order_id());
4445        assert_eq!(received[0].instrument_id(), instrument_id);
4446    }
4447
4448    #[rstest]
4449    #[case(false)]
4450    #[case(true)]
4451    fn test_algorithm_cancel_refusal_publishes_without_changing_lifecycle(#[case] cached: bool) {
4452        let mut algo = create_test_algorithm();
4453        register_algorithm(&mut algo);
4454        let strategy_id = StrategyId::from("STRAT-ALGO-CANCEL-DENY");
4455        let mut order = OrderTestBuilder::new(OrderType::Market)
4456            .trader_id(TraderId::from("TRADER-001"))
4457            .instrument_id(InstrumentId::from("BTC/USDT.BINANCE"))
4458            .strategy_id(strategy_id)
4459            .client_order_id(ClientOrderId::from("O-ALGO-CANCEL-DENY"))
4460            .quantity(Quantity::from("2.5"))
4461            .build();
4462
4463        if cached {
4464            let canceled = OrderCanceledSpec::builder()
4465                .trader_id(order.trader_id())
4466                .strategy_id(strategy_id)
4467                .instrument_id(order.instrument_id())
4468                .client_order_id(order.client_order_id())
4469                .build();
4470            order.apply(OrderEventAny::Canceled(canceled)).unwrap();
4471            algo.core
4472                .cache_rc()
4473                .borrow_mut()
4474                .add_order(order.clone(), None, None, false)
4475                .unwrap();
4476        }
4477
4478        let (handler, events) = subscribe_order_topic(strategy_id);
4479        let cause = UUID4::new();
4480
4481        let command = CancelOrder::new(
4482            order.trader_id(),
4483            None,
4484            if cached {
4485                StrategyId::from("OTHER-REQUESTER")
4486            } else {
4487                strategy_id
4488            },
4489            order.instrument_id(),
4490            order.client_order_id(),
4491            order.venue_order_id(),
4492            cause,
4493            UnixNanos::from(17),
4494            None,
4495            None,
4496        );
4497
4498        algo.handle_cancel_order(command).unwrap();
4499        msgbus::unsubscribe_order_events(format!("events.order.{strategy_id}").into(), &handler);
4500        let events = events.borrow();
4501
4502        let [OrderEventAny::CancelDenied(event)] = events.as_slice() else {
4503            panic!("expected one cancel denial: {events:?}")
4504        };
4505
4506        assert_eq!(event.trader_id, order.trader_id());
4507        assert_eq!(event.strategy_id, strategy_id);
4508        assert_eq!(event.instrument_id, order.instrument_id());
4509        assert_eq!(event.client_order_id, order.client_order_id());
4510        assert_eq!(event.venue_order_id, order.venue_order_id());
4511        assert_eq!(event.account_id, order.account_id());
4512        assert_eq!(event.causation_id, Some(cause));
4513        assert_eq!(
4514            event.reason,
4515            if cached {
4516                "Order already closed"
4517            } else {
4518                "Order not found in cache"
4519            }
4520        );
4521        let cache = algo.cache();
4522        if cached {
4523            let actual = cache.order(&order.client_order_id()).unwrap();
4524            assert_eq!(actual.status(), order.status());
4525            assert_eq!(actual.quantity(), order.quantity());
4526            assert_eq!(actual.filled_qty(), order.filled_qty());
4527            assert_eq!(actual.ts_closed(), order.ts_closed());
4528        } else {
4529            assert!(!cache.order_exists(&order.client_order_id()));
4530        }
4531    }
4532
4533    #[rstest]
4534    fn test_algorithm_execute_dispatches_modify_order_to_handler() {
4535        let unique_id = format!("TEST-{}", UUID4::new());
4536        let config = ExecutionAlgorithmConfig {
4537            exec_algorithm_id: Some(ExecAlgorithmId::new(&unique_id)),
4538            ..Default::default()
4539        };
4540        let mut algo = ModifyDispatchAlgorithm::new(config);
4541        algo.core
4542            .register(
4543                TraderId::from("TRADER-001"),
4544                Rc::new(RefCell::new(VirtualClock::new())),
4545                Rc::new(RefCell::new(Cache::default())),
4546            )
4547            .unwrap();
4548        algo.transition_state(ComponentTrigger::Initialize).unwrap();
4549        algo.transition_state(ComponentTrigger::Start).unwrap();
4550        algo.transition_state(ComponentTrigger::StartCompleted)
4551            .unwrap();
4552
4553        let client_order_id = ClientOrderId::from("O-ALGO-DISPATCH");
4554        let command = ModifyOrder::new(
4555            TraderId::from("TRADER-001"),
4556            None,
4557            StrategyId::from("STRAT-ALGO-DISPATCH"),
4558            InstrumentId::from("BTC/USDT.BINANCE"),
4559            client_order_id,
4560            None,
4561            Some(Quantity::from("0.5")),
4562            None,
4563            None,
4564            UUID4::new(),
4565            0.into(),
4566            None,
4567            None,
4568        );
4569
4570        algo.execute(TradingCommand::ModifyOrder(command)).unwrap();
4571
4572        assert_eq!(algo.modify_client_order_ids, vec![client_order_id]);
4573    }
4574
4575    #[rstest]
4576    fn test_algorithm_handle_modify_order_denies_active_local_order() {
4577        let mut algo = create_test_algorithm();
4578        register_algorithm(&mut algo);
4579
4580        let strategy_id = StrategyId::from("STRAT-ALGO-MODIFY");
4581        let order = OrderTestBuilder::new(OrderType::Market)
4582            .trader_id(TraderId::from("TRADER-001"))
4583            .strategy_id(strategy_id)
4584            .instrument_id(InstrumentId::from("BTC/USDT.BINANCE"))
4585            .client_order_id(ClientOrderId::from("O-ALGO-MODIFY"))
4586            .quantity(Quantity::from("1.0"))
4587            .exec_algorithm_id(algo.id())
4588            .exec_spawn_id(ClientOrderId::from("O-ALGO-MODIFY"))
4589            .build();
4590        {
4591            let cache_rc = algo.core.cache_rc();
4592            cache_rc
4593                .borrow_mut()
4594                .add_order(order.clone(), None, None, false)
4595                .unwrap();
4596        }
4597        let (handler, events) = subscribe_order_topic(strategy_id);
4598        let command = ModifyOrder::new(
4599            order.trader_id(),
4600            None,
4601            strategy_id,
4602            order.instrument_id(),
4603            order.client_order_id(),
4604            None,
4605            Some(Quantity::from("0.5")),
4606            None,
4607            None,
4608            UUID4::new(),
4609            0.into(),
4610            None,
4611            None,
4612        );
4613
4614        let command_id = command.command_id;
4615        algo.execute(TradingCommand::ModifyOrder(command)).unwrap();
4616
4617        msgbus::unsubscribe_order_events(format!("events.order.{strategy_id}").into(), &handler);
4618        let cached_order = algo.cache().order(&order.client_order_id()).unwrap();
4619        assert_eq!(cached_order.status(), OrderStatus::Initialized);
4620        assert_eq!(cached_order.quantity(), Quantity::from("1.0"));
4621        let events = events.borrow();
4622        assert_eq!(events.len(), 1);
4623
4624        let OrderEventAny::ModifyDenied(denied) = &events[0] else {
4625            panic!("Expected modify denial");
4626        };
4627
4628        assert_eq!(denied.causation_id, Some(command_id));
4629        assert_eq!(denied.client_order_id, order.client_order_id());
4630        assert_eq!(denied.strategy_id, strategy_id);
4631        assert_eq!(denied.instrument_id, order.instrument_id());
4632        assert_eq!(denied.reason, "Order is being executed by this algorithm");
4633        assert_eq!(cached_order.price(), order.price());
4634        assert_eq!(cached_order.trigger_price(), order.trigger_price());
4635        assert_eq!(cached_order.exec_algorithm_id(), order.exec_algorithm_id());
4636        assert_eq!(cached_order.exec_spawn_id(), order.exec_spawn_id());
4637        assert_eq!(cached_order.ts_closed(), None);
4638    }
4639
4640    #[rstest]
4641    fn test_algorithm_modify_order_in_place_updates_quantity() {
4642        let mut algo = create_test_algorithm();
4643        register_algorithm(&mut algo);
4644
4645        let strategy_id = StrategyId::from("STRAT-ALGO-MODIFY-IN-PLACE");
4646        let mut order = OrderAny::Limit(LimitOrder::new(
4647            TraderId::from("TRADER-001"),
4648            strategy_id,
4649            InstrumentId::from("BTC/USDT.BINANCE"),
4650            ClientOrderId::from("O-001"),
4651            OrderSide::Buy,
4652            Quantity::from("1.0"),
4653            Price::from("50000.0"),
4654            TimeInForce::Gtc,
4655            None,  // expire_time
4656            false, // post_only
4657            false, // reduce_only
4658            false, // quote_quantity
4659            None,  // display_qty
4660            None,  // emulation_trigger
4661            None,  // trigger_instrument_id
4662            None,  // contingency_type
4663            None,  // order_list_id
4664            None,  // linked_order_ids
4665            None,  // parent_order_id
4666            None,  // exec_algorithm_id
4667            None,  // exec_algorithm_params
4668            None,  // exec_spawn_id
4669            None,  // tags
4670            UUID4::new(),
4671            0.into(),
4672        ));
4673
4674        {
4675            let cache_rc = algo.core.cache_rc();
4676            let mut cache = cache_rc.borrow_mut();
4677            cache.add_order(order.clone(), None, None, false).unwrap();
4678        }
4679
4680        let new_qty = Quantity::from("0.5");
4681        let (handler, events) = subscribe_order_topic(strategy_id);
4682
4683        algo.modify_order_in_place(&mut order, Some(new_qty), None, None)
4684            .unwrap();
4685
4686        msgbus::unsubscribe_order_events(format!("events.order.{strategy_id}").into(), &handler);
4687        let events = events.borrow();
4688
4689        assert_eq!(order.quantity(), new_qty);
4690        assert_eq!(events.len(), 1);
4691        assert!(matches!(
4692            &events[0],
4693            OrderEventAny::Updated(event) if event.quantity == new_qty
4694        ));
4695    }
4696
4697    #[rstest]
4698    fn test_algorithm_modify_order_in_place_rejects_no_changes() {
4699        let mut algo = create_test_algorithm();
4700        register_algorithm(&mut algo);
4701
4702        let mut order = OrderAny::Limit(LimitOrder::new(
4703            TraderId::from("TRADER-001"),
4704            StrategyId::from("STRAT-001"),
4705            InstrumentId::from("BTC/USDT.BINANCE"),
4706            ClientOrderId::from("O-001"),
4707            OrderSide::Buy,
4708            Quantity::from("1.0"),
4709            Price::from("50000.0"),
4710            TimeInForce::Gtc,
4711            None,
4712            false,
4713            false,
4714            false,
4715            None,
4716            None,
4717            None,
4718            None,
4719            None,
4720            None,
4721            None,
4722            None,
4723            None,
4724            None,
4725            None,
4726            UUID4::new(),
4727            0.into(),
4728        ));
4729
4730        // Try to modify with same quantity - should fail
4731        let result =
4732            algo.modify_order_in_place(&mut order, Some(Quantity::from("1.0")), None, None);
4733
4734        assert!(result.is_err());
4735        assert!(
4736            result
4737                .unwrap_err()
4738                .to_string()
4739                .contains("no parameters differ")
4740        );
4741    }
4742
4743    #[rstest]
4744    fn test_spawned_order_denied_restores_primary_quantity() {
4745        let mut algo = create_test_algorithm();
4746        register_algorithm(&mut algo);
4747
4748        let instrument_id = InstrumentId::from("BTC/USDT.BINANCE");
4749        let exec_algorithm_id = algo.id();
4750        let client_order_id = ClientOrderId::from("O-001");
4751
4752        let mut primary = OrderAny::Market(MarketOrder::new(
4753            TraderId::from("TRADER-001"),
4754            StrategyId::from("STRAT-001"),
4755            instrument_id,
4756            client_order_id,
4757            OrderSide::Buy,
4758            Quantity::from("1.0"),
4759            TimeInForce::Gtc,
4760            UUID4::new(),
4761            0.into(),
4762            false,
4763            false,
4764            None,
4765            None,
4766            None,
4767            None,
4768            Some(exec_algorithm_id),
4769            None,
4770            Some(client_order_id),
4771            None,
4772        ));
4773
4774        {
4775            let cache_rc = algo.core.cache_rc();
4776            let mut cache = cache_rc.borrow_mut();
4777            cache.add_order(primary.clone(), None, None, false).unwrap();
4778        }
4779
4780        let spawned = algo
4781            .spawn_market(
4782                &mut primary,
4783                Quantity::from("0.5"),
4784                TimeInForce::Fok,
4785                false,
4786                None,
4787                true,
4788            )
4789            .unwrap();
4790
4791        assert_eq!(primary.quantity(), Quantity::from("0.5"));
4792
4793        let spawned_order = OrderAny::Market(spawned);
4794        {
4795            let cache_rc = algo.core.cache_rc();
4796            let mut cache = cache_rc.borrow_mut();
4797            cache
4798                .add_order(spawned_order.clone(), None, None, false)
4799                .unwrap();
4800        }
4801
4802        let denied = OrderDeniedSpec::builder()
4803            .trader_id(spawned_order.trader_id())
4804            .strategy_id(spawned_order.strategy_id())
4805            .instrument_id(spawned_order.instrument_id())
4806            .client_order_id(spawned_order.client_order_id())
4807            .reason("TEST_DENIAL".into())
4808            .build();
4809
4810        {
4811            let cache_rc = algo.core.cache_rc();
4812            let mut cache = cache_rc.borrow_mut();
4813            cache.update_order(&OrderEventAny::Denied(denied)).unwrap();
4814        }
4815
4816        algo.handle_order_event(OrderEventAny::Denied(denied));
4817
4818        let restored_primary = algo.cache().order(&client_order_id).unwrap();
4819        assert_eq!(restored_primary.quantity(), Quantity::from("1.0"));
4820    }
4821
4822    #[rstest]
4823    fn test_spawned_order_rejected_restores_primary_quantity() {
4824        let mut algo = create_test_algorithm();
4825        register_algorithm(&mut algo);
4826
4827        let instrument_id = InstrumentId::from("BTC/USDT.BINANCE");
4828        let exec_algorithm_id = algo.id();
4829        let client_order_id = ClientOrderId::from("O-001");
4830
4831        let mut primary = OrderAny::Market(MarketOrder::new(
4832            TraderId::from("TRADER-001"),
4833            StrategyId::from("STRAT-001"),
4834            instrument_id,
4835            client_order_id,
4836            OrderSide::Buy,
4837            Quantity::from("1.0"),
4838            TimeInForce::Gtc,
4839            UUID4::new(),
4840            0.into(),
4841            false,
4842            false,
4843            None,
4844            None,
4845            None,
4846            None,
4847            Some(exec_algorithm_id),
4848            None,
4849            Some(client_order_id),
4850            None,
4851        ));
4852
4853        {
4854            let cache_rc = algo.core.cache_rc();
4855            let mut cache = cache_rc.borrow_mut();
4856            cache.add_order(primary.clone(), None, None, false).unwrap();
4857        }
4858
4859        let spawned = algo
4860            .spawn_market(
4861                &mut primary,
4862                Quantity::from("0.5"),
4863                TimeInForce::Fok,
4864                false,
4865                None,
4866                true,
4867            )
4868            .unwrap();
4869
4870        assert_eq!(primary.quantity(), Quantity::from("0.5"));
4871
4872        let spawned_order = OrderAny::Market(spawned);
4873        {
4874            let cache_rc = algo.core.cache_rc();
4875            let mut cache = cache_rc.borrow_mut();
4876            cache
4877                .add_order(spawned_order.clone(), None, None, false)
4878                .unwrap();
4879        }
4880
4881        let rejected = OrderRejectedSpec::builder()
4882            .trader_id(spawned_order.trader_id())
4883            .strategy_id(spawned_order.strategy_id())
4884            .instrument_id(spawned_order.instrument_id())
4885            .client_order_id(spawned_order.client_order_id())
4886            .account_id(AccountId::from("BINANCE-001"))
4887            .reason("TEST_REJECTION".into())
4888            .build();
4889
4890        {
4891            let cache_rc = algo.core.cache_rc();
4892            let mut cache = cache_rc.borrow_mut();
4893            cache
4894                .update_order(&OrderEventAny::Rejected(rejected))
4895                .unwrap();
4896        }
4897
4898        algo.handle_order_event(OrderEventAny::Rejected(rejected));
4899
4900        let restored_primary = algo.cache().order(&client_order_id).unwrap();
4901        assert_eq!(restored_primary.quantity(), Quantity::from("1.0"));
4902    }
4903
4904    #[rstest]
4905    fn test_spawned_order_with_reduce_primary_false_does_not_restore() {
4906        let mut algo = create_test_algorithm();
4907        register_algorithm(&mut algo);
4908
4909        let instrument_id = InstrumentId::from("BTC/USDT.BINANCE");
4910        let exec_algorithm_id = algo.id();
4911        let client_order_id = ClientOrderId::from("O-001");
4912
4913        let mut primary = OrderAny::Market(MarketOrder::new(
4914            TraderId::from("TRADER-001"),
4915            StrategyId::from("STRAT-001"),
4916            instrument_id,
4917            client_order_id,
4918            OrderSide::Buy,
4919            Quantity::from("1.0"),
4920            TimeInForce::Gtc,
4921            UUID4::new(),
4922            0.into(),
4923            false,
4924            false,
4925            None,
4926            None,
4927            None,
4928            None,
4929            Some(exec_algorithm_id),
4930            None,
4931            Some(client_order_id),
4932            None,
4933        ));
4934
4935        {
4936            let cache_rc = algo.core.cache_rc();
4937            let mut cache = cache_rc.borrow_mut();
4938            cache.add_order(primary.clone(), None, None, false).unwrap();
4939        }
4940
4941        let spawned = algo
4942            .spawn_market(
4943                &mut primary,
4944                Quantity::from("0.5"),
4945                TimeInForce::Fok,
4946                false,
4947                None,
4948                false,
4949            )
4950            .unwrap();
4951
4952        assert_eq!(primary.quantity(), Quantity::from("1.0"));
4953
4954        let spawned_order = OrderAny::Market(spawned);
4955        {
4956            let cache_rc = algo.core.cache_rc();
4957            let mut cache = cache_rc.borrow_mut();
4958            cache
4959                .add_order(spawned_order.clone(), None, None, false)
4960                .unwrap();
4961        }
4962
4963        let denied = OrderDeniedSpec::builder()
4964            .trader_id(spawned_order.trader_id())
4965            .strategy_id(spawned_order.strategy_id())
4966            .instrument_id(spawned_order.instrument_id())
4967            .client_order_id(spawned_order.client_order_id())
4968            .reason("TEST_DENIAL".into())
4969            .build();
4970
4971        {
4972            let cache_rc = algo.core.cache_rc();
4973            let mut cache = cache_rc.borrow_mut();
4974            cache.update_order(&OrderEventAny::Denied(denied)).unwrap();
4975        }
4976
4977        algo.handle_order_event(OrderEventAny::Denied(denied));
4978
4979        let final_primary = algo.cache().order(&client_order_id).unwrap();
4980        assert_eq!(final_primary.quantity(), Quantity::from("1.0"));
4981    }
4982
4983    #[rstest]
4984    fn test_multiple_spawns_with_one_denied_restores_correctly() {
4985        let mut algo = create_test_algorithm();
4986        register_algorithm(&mut algo);
4987
4988        let instrument_id = InstrumentId::from("BTC/USDT.BINANCE");
4989        let exec_algorithm_id = algo.id();
4990        let client_order_id = ClientOrderId::from("O-001");
4991
4992        let mut primary = OrderAny::Market(MarketOrder::new(
4993            TraderId::from("TRADER-001"),
4994            StrategyId::from("STRAT-001"),
4995            instrument_id,
4996            client_order_id,
4997            OrderSide::Buy,
4998            Quantity::from("1.0"),
4999            TimeInForce::Gtc,
5000            UUID4::new(),
5001            0.into(),
5002            false,
5003            false,
5004            None,
5005            None,
5006            None,
5007            None,
5008            Some(exec_algorithm_id),
5009            None,
5010            Some(client_order_id),
5011            None,
5012        ));
5013
5014        {
5015            let cache_rc = algo.core.cache_rc();
5016            let mut cache = cache_rc.borrow_mut();
5017            cache.add_order(primary.clone(), None, None, false).unwrap();
5018        }
5019
5020        let spawned1 = algo
5021            .spawn_market(
5022                &mut primary,
5023                Quantity::from("0.3"),
5024                TimeInForce::Fok,
5025                false,
5026                None,
5027                true,
5028            )
5029            .unwrap();
5030        let spawned2 = algo
5031            .spawn_market(
5032                &mut primary,
5033                Quantity::from("0.4"),
5034                TimeInForce::Fok,
5035                false,
5036                None,
5037                true,
5038            )
5039            .unwrap();
5040        assert_eq!(primary.quantity(), Quantity::from("0.3"));
5041
5042        let spawned_order1 = OrderAny::Market(spawned1);
5043        let spawned_order2 = OrderAny::Market(spawned2);
5044        {
5045            let cache_rc = algo.core.cache_rc();
5046            let mut cache = cache_rc.borrow_mut();
5047            cache.add_order(spawned_order1, None, None, false).unwrap();
5048            cache
5049                .add_order(spawned_order2.clone(), None, None, false)
5050                .unwrap();
5051        }
5052
5053        let denied = OrderDeniedSpec::builder()
5054            .trader_id(spawned_order2.trader_id())
5055            .strategy_id(spawned_order2.strategy_id())
5056            .instrument_id(spawned_order2.instrument_id())
5057            .client_order_id(spawned_order2.client_order_id())
5058            .reason("TEST_DENIAL".into())
5059            .build();
5060
5061        {
5062            let cache_rc = algo.core.cache_rc();
5063            let mut cache = cache_rc.borrow_mut();
5064            cache.update_order(&OrderEventAny::Denied(denied)).unwrap();
5065        }
5066
5067        let (handler, events) = subscribe_order_topic(spawned_order2.strategy_id());
5068
5069        algo.handle_order_event(OrderEventAny::Denied(denied));
5070
5071        msgbus::unsubscribe_order_events(
5072            format!("events.order.{}", spawned_order2.strategy_id()).into(),
5073            &handler,
5074        );
5075        let events = events.borrow();
5076
5077        let restored_primary = algo.cache().order(&client_order_id).unwrap();
5078        assert_eq!(restored_primary.quantity(), Quantity::from("0.7"));
5079        assert_eq!(events.len(), 1);
5080        assert!(matches!(
5081            &events[0],
5082            OrderEventAny::Updated(event) if event.quantity == Quantity::from("0.7")
5083        ));
5084    }
5085
5086    #[rstest]
5087    fn test_spawned_order_accepted_then_canceled_restores_reduction() {
5088        let (mut algo, client_order_id, mut spawned_order) = setup_accepted_spawn();
5089
5090        let primary_after_accept = algo.cache().order(&client_order_id).unwrap();
5091        assert_eq!(primary_after_accept.quantity(), Quantity::from("0.5"));
5092
5093        // Per the maintainer's ruling, acceptance preserves the reduction until terminal outcome
5094        cancel_spawned_order(&mut algo, &mut spawned_order);
5095
5096        let final_primary = algo.cache().order(&client_order_id).unwrap();
5097        assert_eq!(final_primary.quantity(), Quantity::from("1.0"));
5098    }
5099
5100    #[rstest]
5101    fn test_spawned_order_canceled_after_primary_submission_does_not_restore_reduction() {
5102        let (mut algo, client_order_id, mut spawned_order) = setup_accepted_spawn();
5103        let mut primary = algo.cache().order(&client_order_id).unwrap();
5104        submit_order_in_cache(&mut algo, &mut primary);
5105
5106        cancel_spawned_order(&mut algo, &mut spawned_order);
5107
5108        let mut submitted_primary = algo.cache().order(&client_order_id).unwrap();
5109        assert_eq!(submitted_primary.quantity(), Quantity::from("0.5"));
5110        assert!(
5111            algo.core
5112                .take_pending_spawn_reduction(spawned_order.client_order_id())
5113                .is_none()
5114        );
5115        fill_spawned_order(&mut algo, &mut submitted_primary, Quantity::from("0.5"));
5116        assert!(submitted_primary.is_closed());
5117        assert_eq!(submitted_primary.status(), OrderStatus::Filled);
5118    }
5119
5120    #[rstest]
5121    fn test_spawned_order_canceled_during_primary_submission_handoff_does_not_restore() {
5122        let (mut algo, client_order_id, mut spawned_order) = setup_accepted_spawn();
5123        let primary = algo.cache().order(&client_order_id).unwrap();
5124        algo.core
5125            .add_spawn_fill_debt(client_order_id, Quantity::from("0.1"));
5126        let (risk_handler, risk_messages): (_, TypedIntoMessageSavingHandler<TradingCommand>) =
5127            get_typed_into_message_saving_handler(Some(Ustr::from("RiskEngine.queue_execute")));
5128        msgbus::register_trading_command_endpoint(
5129            MessagingSwitchboard::risk_engine_queue_execute(),
5130            risk_handler,
5131        );
5132        let strategy_id = primary.strategy_id();
5133        let (event_handler, events) = subscribe_order_topic(strategy_id);
5134
5135        algo.submit_order(primary, None, None).unwrap();
5136        assert_eq!(
5137            algo.cache().order(&client_order_id).unwrap().status(),
5138            OrderStatus::Initialized,
5139        );
5140        cancel_spawned_order(&mut algo, &mut spawned_order);
5141
5142        msgbus::unsubscribe_order_events(
5143            format!("events.order.{strategy_id}").into(),
5144            &event_handler,
5145        );
5146        let risk_messages = risk_messages.get_messages();
5147        let [TradingCommand::SubmitOrder(command)] = risk_messages.as_slice() else {
5148            panic!("Expected exactly one SubmitOrder command");
5149        };
5150        assert_eq!(command.client_order_id, client_order_id);
5151        // The command carries the primary's reduced quantity at submission,
5152        // matching the cached order asserted below.
5153        assert_eq!(command.order_init.quantity, Quantity::from("0.5"));
5154        assert_eq!(
5155            algo.cache().order(&client_order_id).unwrap().quantity(),
5156            Quantity::from("0.5"),
5157        );
5158        assert!(!events.borrow().iter().any(|event| matches!(
5159            event,
5160            OrderEventAny::Updated(updated) if updated.client_order_id == client_order_id
5161        )));
5162        assert!(
5163            algo.core
5164                .take_pending_spawn_reduction(spawned_order.client_order_id())
5165                .is_none()
5166        );
5167        assert!(algo.core.spawn_fill_debt(client_order_id).is_none());
5168    }
5169
5170    #[rstest]
5171    fn test_late_spawn_fill_rededucts_restored_primary_before_final_submission() {
5172        let (mut algo, client_order_id, mut spawned_order) = setup_accepted_spawn();
5173        cancel_spawned_order(&mut algo, &mut spawned_order);
5174        assert_eq!(
5175            algo.cache().order(&client_order_id).unwrap().quantity(),
5176            Quantity::from("1.0"),
5177        );
5178
5179        fill_spawned_order(&mut algo, &mut spawned_order, Quantity::from("0.5"));
5180
5181        let mut primary = algo.cache().order(&client_order_id).unwrap();
5182        assert_eq!(primary.quantity(), Quantity::from("0.5"));
5183        submit_order_in_cache(&mut algo, &mut primary);
5184        assert_eq!(
5185            spawned_order.filled_qty() + primary.quantity(),
5186            Quantity::from("1.0"),
5187        );
5188    }
5189
5190    #[rstest]
5191    fn test_late_spawn_fill_during_primary_submission_handoff_does_not_rededuct() {
5192        let (mut algo, client_order_id, mut spawned_order) = setup_accepted_spawn();
5193        cancel_spawned_order(&mut algo, &mut spawned_order);
5194        let primary = algo.cache().order(&client_order_id).unwrap();
5195        algo.core
5196            .add_spawn_fill_debt(client_order_id, Quantity::from("0.1"));
5197        let (risk_handler, risk_messages): (_, TypedIntoMessageSavingHandler<TradingCommand>) =
5198            get_typed_into_message_saving_handler(Some(Ustr::from("RiskEngine.queue_execute")));
5199        msgbus::register_trading_command_endpoint(
5200            MessagingSwitchboard::risk_engine_queue_execute(),
5201            risk_handler,
5202        );
5203        let strategy_id = primary.strategy_id();
5204        let (event_handler, events) = subscribe_order_topic(strategy_id);
5205
5206        algo.submit_order(primary, None, None).unwrap();
5207        assert_eq!(
5208            algo.cache().order(&client_order_id).unwrap().status(),
5209            OrderStatus::Initialized,
5210        );
5211        fill_spawned_order(&mut algo, &mut spawned_order, Quantity::from("0.5"));
5212
5213        msgbus::unsubscribe_order_events(
5214            format!("events.order.{strategy_id}").into(),
5215            &event_handler,
5216        );
5217        let risk_messages = risk_messages.get_messages();
5218        let [TradingCommand::SubmitOrder(command)] = risk_messages.as_slice() else {
5219            panic!("Expected exactly one SubmitOrder command");
5220        };
5221        assert_eq!(command.client_order_id, client_order_id);
5222        // The cancellation restored the primary to 1.0 before submission, so
5223        // the command carries the full quantity.
5224        assert_eq!(command.order_init.quantity, Quantity::from("1.0"));
5225        assert_eq!(
5226            algo.cache().order(&client_order_id).unwrap().quantity(),
5227            Quantity::from("1.0"),
5228        );
5229        assert!(!events.borrow().iter().any(|event| matches!(
5230            event,
5231            OrderEventAny::Updated(updated) if updated.client_order_id == client_order_id
5232        )));
5233        assert!(
5234            algo.core
5235                .take_pending_spawn_reduction(spawned_order.client_order_id())
5236                .is_none()
5237        );
5238        assert!(algo.core.spawn_fill_debt(client_order_id).is_none());
5239    }
5240
5241    #[rstest]
5242    fn test_converted_quote_spawn_canceled_unfilled_restores_full_quote_quantity() {
5243        let (mut algo, client_order_id, mut spawned_order) =
5244            setup_accepted_quote_spawn(Quantity::from("100"), Quantity::from("50"));
5245        convert_spawn_to_base(&mut algo, &mut spawned_order, Quantity::from("5"));
5246
5247        cancel_spawned_order(&mut algo, &mut spawned_order);
5248
5249        assert_eq!(
5250            algo.cache().order(&client_order_id).unwrap().quantity(),
5251            Quantity::from("100"),
5252        );
5253        assert!(
5254            algo.cache()
5255                .order(&client_order_id)
5256                .unwrap()
5257                .is_quote_quantity()
5258        );
5259        assert_eq!(
5260            algo.core
5261                .spawn_reduction(spawned_order.client_order_id())
5262                .unwrap()
5263                .restored_qty
5264                .unwrap(),
5265            Quantity::from("50"),
5266        );
5267    }
5268
5269    #[rstest]
5270    fn test_converted_quote_spawn_partial_fill_restores_proportional_quote_quantity() {
5271        let (mut algo, client_order_id, mut spawned_order) =
5272            setup_accepted_quote_spawn(Quantity::from("100"), Quantity::from("50"));
5273        convert_spawn_to_base(&mut algo, &mut spawned_order, Quantity::from("5"));
5274        fill_spawned_order(&mut algo, &mut spawned_order, Quantity::from("2"));
5275
5276        cancel_spawned_order(&mut algo, &mut spawned_order);
5277
5278        assert_eq!(
5279            algo.cache().order(&client_order_id).unwrap().quantity(),
5280            Quantity::from("80"),
5281        );
5282        assert!(
5283            algo.cache()
5284                .order(&client_order_id)
5285                .unwrap()
5286                .is_quote_quantity()
5287        );
5288        assert_eq!(
5289            algo.core
5290                .spawn_reduction(spawned_order.client_order_id())
5291                .unwrap()
5292                .restored_qty
5293                .unwrap(),
5294            Quantity::from("30"),
5295        );
5296    }
5297
5298    #[rstest]
5299    fn test_converted_quote_spawn_late_fill_charges_proportional_quote_quantity() {
5300        let (mut algo, client_order_id, mut spawned_order) =
5301            setup_accepted_quote_spawn(Quantity::from("100"), Quantity::from("50"));
5302        convert_spawn_to_base(&mut algo, &mut spawned_order, Quantity::from("5"));
5303        cancel_spawned_order(&mut algo, &mut spawned_order);
5304
5305        fill_spawned_order(&mut algo, &mut spawned_order, Quantity::from("1"));
5306
5307        assert_eq!(
5308            algo.cache().order(&client_order_id).unwrap().quantity(),
5309            Quantity::from("90"),
5310        );
5311        assert!(
5312            algo.cache()
5313                .order(&client_order_id)
5314                .unwrap()
5315                .is_quote_quantity()
5316        );
5317        assert_eq!(
5318            algo.core
5319                .spawn_reduction(spawned_order.client_order_id())
5320                .unwrap()
5321                .restored_qty
5322                .unwrap(),
5323            Quantity::from("40"),
5324        );
5325    }
5326
5327    #[rstest]
5328    fn test_converted_quote_spawn_restoration_rounds_down_to_primary_precision() {
5329        let (mut algo, client_order_id, mut spawned_order) =
5330            setup_accepted_quote_spawn(Quantity::from("20.00"), Quantity::from("10.00"));
5331        convert_spawn_to_base(&mut algo, &mut spawned_order, Quantity::from("3.000"));
5332        fill_spawned_order(&mut algo, &mut spawned_order, Quantity::from("1.000"));
5333
5334        cancel_spawned_order(&mut algo, &mut spawned_order);
5335
5336        assert_eq!(
5337            algo.cache().order(&client_order_id).unwrap().quantity(),
5338            Quantity::from("16.66"),
5339        );
5340        assert!(
5341            algo.cache()
5342                .order(&client_order_id)
5343                .unwrap()
5344                .is_quote_quantity()
5345        );
5346        assert_eq!(
5347            algo.core
5348                .spawn_reduction(spawned_order.client_order_id())
5349                .unwrap()
5350                .restored_qty
5351                .unwrap(),
5352            Quantity::from("6.66"),
5353        );
5354    }
5355
5356    #[rstest]
5357    fn test_converted_quote_spawn_repeated_fractional_late_fills_conserve_budget() {
5358        let (mut algo, client_order_id, mut spawned_order) =
5359            setup_accepted_quote_spawn(Quantity::from("20.00"), Quantity::from("10.00"));
5360        convert_spawn_to_base(&mut algo, &mut spawned_order, Quantity::from("3.000"));
5361        cancel_spawned_order(&mut algo, &mut spawned_order);
5362
5363        for (primary_qty, restored_qty) in [
5364            (Quantity::from("16.66"), Quantity::from("6.66")),
5365            (Quantity::from("13.33"), Quantity::from("3.33")),
5366            (Quantity::from("10.00"), Quantity::from("0.00")),
5367        ] {
5368            fill_spawned_order(&mut algo, &mut spawned_order, Quantity::from("1.000"));
5369            assert_eq!(
5370                algo.cache().order(&client_order_id).unwrap().quantity(),
5371                primary_qty,
5372            );
5373            assert_eq!(
5374                algo.core
5375                    .spawn_reduction(spawned_order.client_order_id())
5376                    .unwrap()
5377                    .restored_qty
5378                    .unwrap(),
5379                restored_qty,
5380            );
5381        }
5382    }
5383
5384    #[rstest]
5385    #[case::single_fill(Quantity::from("3.0"), 1)]
5386    #[case::split_fills(Quantity::from("0.1"), 30)]
5387    fn test_converted_quote_spawn_fill_partition_preserves_total(
5388        #[case] fill_qty: Quantity,
5389        #[case] fills: usize,
5390    ) {
5391        let (mut algo, primary_id, mut child) =
5392            setup_accepted_quote_spawn(Quantity::from("20"), Quantity::from("10"));
5393        convert_spawn_to_base(&mut algo, &mut child, Quantity::from("3.0"));
5394        cancel_spawned_order(&mut algo, &mut child);
5395
5396        for _ in 0..fills {
5397            fill_spawned_order(&mut algo, &mut child, fill_qty);
5398        }
5399
5400        assert_eq!(child.filled_qty(), Quantity::from("3.0"));
5401        assert_eq!(
5402            algo.cache().order(&primary_id).unwrap().quantity(),
5403            Quantity::from("10")
5404        );
5405        assert_eq!(
5406            algo.core
5407                .spawn_reduction(child.client_order_id())
5408                .unwrap()
5409                .restored_qty,
5410            Some(Quantity::from("0"))
5411        );
5412        assert!(algo.core.spawn_fill_debt(primary_id).is_none());
5413    }
5414
5415    #[rstest]
5416    fn test_increased_spawn_late_fill_debits_original_restoration() {
5417        let (mut algo, primary_id, mut child) = setup_pending_spawn();
5418        algo.modify_order_in_place(&mut child, Some(Quantity::from("0.8")), None, None)
5419            .unwrap();
5420        accept_spawned_order(&mut algo, &mut child);
5421        cancel_spawned_order(&mut algo, &mut child);
5422
5423        fill_spawned_order(&mut algo, &mut child, Quantity::from("0.1"));
5424
5425        assert_eq!(child.quantity(), Quantity::from("0.8"));
5426        assert_eq!(child.filled_qty(), Quantity::from("0.1"));
5427        assert_eq!(
5428            algo.cache().order(&primary_id).unwrap().quantity(),
5429            Quantity::from("0.9")
5430        );
5431        assert_eq!(
5432            algo.core
5433                .spawn_reduction(child.client_order_id())
5434                .unwrap()
5435                .restored_qty,
5436            Some(Quantity::from("0.4"))
5437        );
5438        assert!(algo.core.spawn_fill_debt(primary_id).is_none());
5439
5440        void_last_spawn_fill(&mut algo, &mut child, Quantity::from("0.1"));
5441
5442        assert_eq!(
5443            algo.cache().order(&primary_id).unwrap().quantity(),
5444            Quantity::from("1.0")
5445        );
5446    }
5447
5448    #[rstest]
5449    #[case::partial_fill(Quantity::from("0.1"))]
5450    #[case::full_fill(Quantity::from("0.5"))]
5451    fn test_voided_late_spawn_fill_restores_primary_quantity(
5452        #[case] fill_qty: Quantity,
5453        #[values(false, true)] stopped: bool,
5454    ) {
5455        let (mut algo, primary_id, mut child) = setup_accepted_spawn();
5456        cancel_spawned_order(&mut algo, &mut child);
5457        fill_spawned_order(&mut algo, &mut child, fill_qty);
5458        if stopped {
5459            Component::stop(&mut algo).unwrap();
5460        }
5461
5462        void_last_spawn_fill(&mut algo, &mut child, fill_qty);
5463
5464        assert_eq!(child.filled_qty(), Quantity::from("0.0"));
5465        assert_eq!(
5466            algo.cache().order(&primary_id).unwrap().quantity(),
5467            Quantity::from("1.0")
5468        );
5469        assert!(algo.core.spawn_fill_debt(primary_id).is_none());
5470        assert_eq!(
5471            algo.core
5472                .spawn_reduction(child.client_order_id())
5473                .unwrap()
5474                .restored_qty,
5475            Some(Quantity::from("0.5"))
5476        );
5477    }
5478
5479    #[rstest]
5480    #[case::debt_only(
5481        Quantity::from("0.1"),
5482        Quantity::from("0.0"),
5483        Some(Quantity::from("0.1"))
5484    )]
5485    #[case::debt_and_quantity(Quantity::from("0.3"), Quantity::from("0.1"), None)]
5486    fn test_voided_late_spawn_fill_discharges_debt_before_restoring_quantity(
5487        #[case] voided_qty: Quantity,
5488        #[case] primary_qty: Quantity,
5489        #[case] debt_qty: Option<Quantity>,
5490    ) {
5491        let (mut algo, primary_id, mut child) = setup_accepted_spawn();
5492        cancel_spawned_order(&mut algo, &mut child);
5493        let _second = spawn_reduced_child(&mut algo, primary_id, Quantity::from("0.8"));
5494        fill_spawned_order(&mut algo, &mut child, Quantity::from("0.4"));
5495        assert_eq!(
5496            algo.core.spawn_fill_debt(primary_id),
5497            Some(Quantity::from("0.2"))
5498        );
5499
5500        void_last_spawn_fill(&mut algo, &mut child, voided_qty);
5501
5502        assert_eq!(
5503            algo.cache().order(&primary_id).unwrap().quantity(),
5504            primary_qty
5505        );
5506        assert_eq!(algo.core.spawn_fill_debt(primary_id), debt_qty);
5507        assert_eq!(child.filled_qty(), Quantity::from("0.4") - voided_qty);
5508        assert_eq!(
5509            algo.core
5510                .spawn_reduction(child.client_order_id())
5511                .unwrap()
5512                .restored_qty,
5513            Some(Quantity::from("0.1") + voided_qty)
5514        );
5515    }
5516
5517    #[rstest]
5518    fn test_spawn_fill_void_before_restoration_preserves_reserved_quantity() {
5519        let (mut algo, primary_id, mut child) = setup_accepted_spawn();
5520        fill_spawned_order(&mut algo, &mut child, Quantity::from("0.1"));
5521
5522        void_last_spawn_fill(&mut algo, &mut child, Quantity::from("0.1"));
5523
5524        assert_eq!(
5525            algo.cache().order(&primary_id).unwrap().quantity(),
5526            Quantity::from("0.5")
5527        );
5528        assert_eq!(
5529            algo.core
5530                .spawn_reduction(child.client_order_id())
5531                .unwrap()
5532                .restored_qty,
5533            None
5534        );
5535        cancel_spawned_order(&mut algo, &mut child);
5536        assert_eq!(
5537            algo.cache().order(&primary_id).unwrap().quantity(),
5538            Quantity::from("1.0")
5539        );
5540    }
5541
5542    #[rstest]
5543    fn test_spawn_fill_void_after_primary_handoff_preserves_submitted_quantity() {
5544        let (mut algo, primary_id, mut child) = setup_accepted_spawn();
5545        cancel_spawned_order(&mut algo, &mut child);
5546        fill_spawned_order(&mut algo, &mut child, Quantity::from("0.1"));
5547        let primary = algo.cache().order(&primary_id).unwrap();
5548        let (handler, _messages): (_, TypedIntoMessageSavingHandler<TradingCommand>) =
5549            get_typed_into_message_saving_handler(Some(Ustr::from("RiskEngine.queue_execute")));
5550        msgbus::register_trading_command_endpoint(
5551            MessagingSwitchboard::risk_engine_queue_execute(),
5552            handler,
5553        );
5554        algo.submit_order(primary, None, None).unwrap();
5555
5556        void_last_spawn_fill(&mut algo, &mut child, Quantity::from("0.1"));
5557
5558        assert_eq!(
5559            algo.cache().order(&primary_id).unwrap().quantity(),
5560            Quantity::from("0.9")
5561        );
5562        assert_eq!(
5563            algo.cache().order(&primary_id).unwrap().status(),
5564            OrderStatus::Initialized
5565        );
5566        assert!(algo.core.primary_was_handed_off(primary_id));
5567        assert!(algo.core.spawn_reduction(child.client_order_id()).is_none());
5568        assert!(algo.core.spawn_fill_debt(primary_id).is_none());
5569    }
5570
5571    #[rstest]
5572    fn test_converted_quote_spawn_fill_void_restores_cumulative_budget_once() {
5573        let (mut algo, primary_id, mut child) =
5574            setup_accepted_quote_spawn(Quantity::from("20.00"), Quantity::from("10.00"));
5575        convert_spawn_to_base(&mut algo, &mut child, Quantity::from("3.000"));
5576        cancel_spawned_order(&mut algo, &mut child);
5577        fill_spawned_order(&mut algo, &mut child, Quantity::from("1.000"));
5578        fill_spawned_order(&mut algo, &mut child, Quantity::from("1.000"));
5579
5580        void_last_spawn_fill(&mut algo, &mut child, Quantity::from("0.500"));
5581        assert_eq!(
5582            algo.cache().order(&primary_id).unwrap().quantity(),
5583            Quantity::from("15.00")
5584        );
5585        void_last_spawn_fill(&mut algo, &mut child, Quantity::from("1.000"));
5586        let duplicate = child.events().into_iter().last().unwrap().clone();
5587        algo.handle_order_event(duplicate);
5588
5589        assert_eq!(child.filled_qty(), Quantity::from("1.000"));
5590        assert_eq!(
5591            algo.cache().order(&primary_id).unwrap().quantity(),
5592            Quantity::from("16.66")
5593        );
5594        assert_eq!(
5595            algo.core
5596                .spawn_reduction(child.client_order_id())
5597                .unwrap()
5598                .restored_qty,
5599            Some(Quantity::from("6.66"))
5600        );
5601        assert!(algo.core.spawn_fill_debt(primary_id).is_none());
5602    }
5603
5604    fn void_last_spawn_fill(algo: &mut TestAlgorithm, order: &mut OrderAny, quantity: Quantity) {
5605        let fill = order
5606            .events()
5607            .into_iter()
5608            .rev()
5609            .find_map(|event| match event {
5610                OrderEventAny::Filled(fill) => Some(fill.clone()),
5611                _ => None,
5612            })
5613            .unwrap();
5614        let voided = OrderFillVoidedSpec::builder()
5615            .trader_id(fill.trader_id)
5616            .strategy_id(fill.strategy_id)
5617            .instrument_id(fill.instrument_id)
5618            .client_order_id(fill.client_order_id)
5619            .venue_order_id(fill.venue_order_id)
5620            .account_id(fill.account_id)
5621            .trade_id(fill.trade_id)
5622            .voided_qty(quantity)
5623            .order_side(fill.order_side)
5624            .order_type(fill.order_type)
5625            .last_px(fill.last_px)
5626            .currency(fill.currency)
5627            .liquidity_side(fill.liquidity_side)
5628            .build();
5629        *order = algo
5630            .core
5631            .cache_rc()
5632            .borrow_mut()
5633            .update_order(&OrderEventAny::FillVoided(voided.clone()))
5634            .unwrap();
5635        algo.handle_order_event(OrderEventAny::FillVoided(voided));
5636    }
5637
5638    #[rstest]
5639    fn test_primary_handoff_clears_spawn_accounting_without_child_events() {
5640        let (mut algo, primary_id, mut child) = setup_accepted_spawn();
5641        cancel_spawned_order(&mut algo, &mut child);
5642        let primary = algo.cache().order(&primary_id).unwrap();
5643        let (handler, _messages): (_, TypedIntoMessageSavingHandler<TradingCommand>) =
5644            get_typed_into_message_saving_handler(Some(Ustr::from("RiskEngine.queue_execute")));
5645        msgbus::register_trading_command_endpoint(
5646            MessagingSwitchboard::risk_engine_queue_execute(),
5647            handler,
5648        );
5649
5650        algo.submit_order(primary, None, None).unwrap();
5651
5652        assert!(algo.core.spawn_reduction(child.client_order_id()).is_none());
5653        assert!(algo.core.spawn_fill_debt(primary_id).is_none());
5654        assert!(algo.core.primary_was_handed_off(primary_id));
5655
5656        let mut primary = algo.cache().order(&primary_id).unwrap();
5657        submit_order_in_cache(&mut algo, &mut primary);
5658        assert!(!algo.core.primary_was_handed_off(primary_id));
5659    }
5660
5661    #[rstest]
5662    #[case(false)]
5663    #[case(true)]
5664    fn test_primary_cancellation_clears_spawn_accounting(#[case] stopped: bool) {
5665        let (mut algo, primary_id, mut child) = setup_accepted_spawn();
5666        cancel_spawned_order(&mut algo, &mut child);
5667        let second = spawn_reduced_child(&mut algo, primary_id, Quantity::from("0.8"));
5668        fill_spawned_order(&mut algo, &mut child, Quantity::from("0.4"));
5669        let mut primary = algo.cache().order(&primary_id).unwrap();
5670        if stopped {
5671            Component::stop(&mut algo).unwrap();
5672        }
5673
5674        cancel_spawned_order(&mut algo, &mut primary);
5675
5676        assert_eq!(primary.status(), OrderStatus::Canceled);
5677        assert!(algo.core.spawn_reduction(child.client_order_id()).is_none());
5678        assert!(
5679            algo.core
5680                .spawn_reduction(second.client_order_id())
5681                .is_none()
5682        );
5683        assert!(algo.core.spawn_fill_debt(primary_id).is_none());
5684        assert!(!algo.core.primary_was_handed_off(primary_id));
5685    }
5686
5687    #[rstest]
5688    fn test_converted_quote_spawn_partial_cancel_then_late_fill_charges_restored_budget() {
5689        let (mut algo, client_order_id, mut spawned_order) =
5690            setup_accepted_quote_spawn(Quantity::from("100"), Quantity::from("50"));
5691        convert_spawn_to_base(&mut algo, &mut spawned_order, Quantity::from("5"));
5692        fill_spawned_order(&mut algo, &mut spawned_order, Quantity::from("2"));
5693        cancel_spawned_order(&mut algo, &mut spawned_order);
5694
5695        assert_eq!(
5696            algo.cache().order(&client_order_id).unwrap().quantity(),
5697            Quantity::from("80"),
5698        );
5699        assert_eq!(
5700            algo.core
5701                .spawn_reduction(spawned_order.client_order_id())
5702                .unwrap()
5703                .restored_qty
5704                .unwrap(),
5705            Quantity::from("30"),
5706        );
5707
5708        fill_spawned_order(&mut algo, &mut spawned_order, Quantity::from("1"));
5709
5710        assert_eq!(
5711            algo.cache().order(&client_order_id).unwrap().quantity(),
5712            Quantity::from("70"),
5713        );
5714        assert_eq!(
5715            algo.core
5716                .spawn_reduction(spawned_order.client_order_id())
5717                .unwrap()
5718                .restored_qty
5719                .unwrap(),
5720            Quantity::from("20"),
5721        );
5722    }
5723
5724    #[rstest]
5725    fn test_unmarked_submitted_primary_cancellation_discards_reduction_and_debt() {
5726        let (mut algo, client_order_id, mut spawned_order) = setup_accepted_spawn();
5727        let mut primary = algo.cache().order(&client_order_id).unwrap();
5728        algo.core
5729            .add_spawn_fill_debt(client_order_id, Quantity::from("0.1"));
5730
5731        submit_order_in_cache(&mut algo, &mut primary);
5732        assert!(algo.core.spawn_fill_debt(client_order_id).is_none());
5733        cancel_spawned_order(&mut algo, &mut spawned_order);
5734
5735        assert_eq!(
5736            algo.cache().order(&client_order_id).unwrap().quantity(),
5737            Quantity::from("0.5"),
5738        );
5739        assert!(
5740            algo.core
5741                .spawn_reduction(spawned_order.client_order_id())
5742                .is_none()
5743        );
5744        assert!(algo.core.spawn_fill_debt(client_order_id).is_none());
5745    }
5746
5747    #[rstest]
5748    #[case::denied(true)]
5749    #[case::rejected(false)]
5750    fn test_spawn_refusal_does_not_restore_submitted_primary(#[case] denied: bool) {
5751        let (mut algo, client_order_id, spawned_order) = setup_pending_spawn();
5752        let spawned_id = spawned_order.client_order_id();
5753        let mut primary = algo.cache().order(&client_order_id).unwrap();
5754        submit_order_in_cache(&mut algo, &mut primary);
5755
5756        if denied {
5757            let event = OrderDeniedSpec::builder()
5758                .trader_id(spawned_order.trader_id())
5759                .strategy_id(spawned_order.strategy_id())
5760                .instrument_id(spawned_order.instrument_id())
5761                .client_order_id(spawned_id)
5762                .reason("TEST_DENIAL".into())
5763                .build();
5764            algo.handle_order_event(OrderEventAny::Denied(event));
5765        } else {
5766            let event = OrderRejectedSpec::builder()
5767                .trader_id(spawned_order.trader_id())
5768                .strategy_id(spawned_order.strategy_id())
5769                .instrument_id(spawned_order.instrument_id())
5770                .client_order_id(spawned_id)
5771                .account_id(AccountId::from("BINANCE-001"))
5772                .reason("TEST_REJECTION".into())
5773                .build();
5774            algo.handle_order_event(OrderEventAny::Rejected(event));
5775        }
5776
5777        assert_eq!(
5778            algo.cache().order(&client_order_id).unwrap().quantity(),
5779            Quantity::from("0.5"),
5780        );
5781        assert!(algo.core.take_pending_spawn_reduction(spawned_id).is_none());
5782    }
5783
5784    #[rstest]
5785    #[case::resume(ComponentState::Stopped, ComponentState::Running)]
5786    #[case::stop(ComponentState::Running, ComponentState::Stopped)]
5787    fn test_order_event_suppresses_callbacks_after_synchronous_state_change(
5788        #[case] state_before: ComponentState,
5789        #[case] state_after: ComponentState,
5790    ) {
5791        let (algo, _primary_id, child) = setup_accepted_spawn();
5792
5793        let mut algo = LifecycleAlgorithm {
5794            core: algo.core,
5795            order_callbacks: Vec::new(),
5796        };
5797
5798        if state_before == ComponentState::Stopped {
5799            Component::stop(&mut algo).unwrap();
5800        }
5801
5802        let canceled = OrderCanceledSpec::builder()
5803            .trader_id(child.trader_id())
5804            .strategy_id(child.strategy_id())
5805            .instrument_id(child.instrument_id())
5806            .client_order_id(child.client_order_id())
5807            .maybe_venue_order_id(child.venue_order_id())
5808            .maybe_account_id(child.account_id())
5809            .build();
5810        algo.core
5811            .cache_rc()
5812            .borrow_mut()
5813            .update_order(&OrderEventAny::Canceled(canceled))
5814            .unwrap();
5815
5816        algo.handle_order_event(OrderEventAny::Canceled(canceled));
5817
5818        assert_eq!(Component::state(&algo), state_after);
5819        assert!(algo.order_callbacks.is_empty());
5820    }
5821
5822    #[rstest]
5823    fn test_unregistered_algorithm_ignores_order_event() {
5824        let mut algo = create_test_algorithm();
5825        let event = OrderCanceledSpec::builder().build();
5826
5827        algo.handle_order_event(OrderEventAny::Canceled(event));
5828
5829        assert!(algo.order_callbacks.is_empty());
5830    }
5831
5832    #[rstest]
5833    #[case(false, false, vec!["canceled", "event"])]
5834    #[case(false, true, vec!["filled", "event"])]
5835    #[case(true, false, vec![])]
5836    #[case(true, true, vec![])]
5837    fn test_spawn_accounting_preserves_callback_state_gate(
5838        #[case] stopped: bool,
5839        #[case] late_fill: bool,
5840        #[case] expected_callbacks: Vec<&str>,
5841    ) {
5842        let (mut algo, primary_id, mut child) = setup_accepted_spawn();
5843        if late_fill {
5844            cancel_spawned_order(&mut algo, &mut child);
5845        }
5846
5847        if stopped {
5848            Component::stop(&mut algo).unwrap();
5849        }
5850
5851        algo.order_callbacks.clear();
5852        if late_fill {
5853            fill_spawned_order(&mut algo, &mut child, Quantity::from("0.2"));
5854        } else {
5855            cancel_spawned_order(&mut algo, &mut child);
5856        }
5857
5858        let primary = algo.cache().order(&primary_id).unwrap();
5859        assert_eq!(algo.order_callbacks, expected_callbacks);
5860        assert_eq!(
5861            primary.quantity(),
5862            if late_fill {
5863                Quantity::from("0.8")
5864            } else {
5865                Quantity::from("1.0")
5866            },
5867        );
5868        assert_eq!(
5869            child.filled_qty() + primary.quantity(),
5870            Quantity::from("1.0")
5871        );
5872    }
5873
5874    #[rstest]
5875    fn test_multiple_late_partial_fills_net_only_the_restored_quantity() {
5876        let (mut algo, client_order_id, mut spawned_order) = setup_accepted_spawn();
5877        fill_spawned_order(&mut algo, &mut spawned_order, Quantity::from("0.2"));
5878        cancel_spawned_order(&mut algo, &mut spawned_order);
5879
5880        fill_spawned_order(&mut algo, &mut spawned_order, Quantity::from("0.1"));
5881        assert_eq!(
5882            algo.cache().order(&client_order_id).unwrap().quantity(),
5883            Quantity::from("0.7"),
5884        );
5885
5886        fill_spawned_order(&mut algo, &mut spawned_order, Quantity::from("0.2"));
5887        assert_eq!(
5888            algo.cache().order(&client_order_id).unwrap().quantity(),
5889            Quantity::from("0.5"),
5890        );
5891        assert_eq!(
5892            algo.core
5893                .spawn_reduction(spawned_order.client_order_id())
5894                .unwrap()
5895                .restored_qty,
5896            Some(Quantity::from("0.0")),
5897        );
5898    }
5899
5900    #[rstest]
5901    fn test_late_spawn_fill_after_restored_quantity_reused_caps_at_primary_quantity() {
5902        let (mut algo, client_order_id, mut spawned_order) = setup_accepted_spawn();
5903        cancel_spawned_order(&mut algo, &mut spawned_order);
5904        assert_eq!(
5905            algo.cache().order(&client_order_id).unwrap().quantity(),
5906            Quantity::from("1.0"),
5907        );
5908
5909        // Reuse most of the restored quantity through a second spawn
5910        let mut primary = algo.cache().order(&client_order_id).unwrap();
5911        let second_order = OrderAny::Market(
5912            algo.spawn_market(
5913                &mut primary,
5914                Quantity::from("0.8"),
5915                TimeInForce::Fok,
5916                false,
5917                None,
5918                true,
5919            )
5920            .unwrap(),
5921        );
5922        algo.core
5923            .cache_rc()
5924            .borrow_mut()
5925            .add_order(second_order.clone(), None, None, false)
5926            .unwrap();
5927        assert_eq!(
5928            algo.cache().order(&client_order_id).unwrap().quantity(),
5929            Quantity::from("0.2"),
5930        );
5931
5932        // The late fill exceeds the primary's remaining quantity: the
5933        // re-deduction caps at zero and the shortfall becomes debt
5934        fill_spawned_order(&mut algo, &mut spawned_order, Quantity::from("0.5"));
5935        assert_eq!(
5936            algo.cache().order(&client_order_id).unwrap().quantity(),
5937            Quantity::from("0.0"),
5938        );
5939        assert_eq!(
5940            algo.core
5941                .spawn_reduction(spawned_order.client_order_id())
5942                .unwrap()
5943                .restored_qty,
5944            Some(Quantity::from("0.0")),
5945        );
5946        assert_eq!(
5947            algo.core.spawn_fill_debt(client_order_id),
5948            Some(Quantity::from("0.3")),
5949        );
5950
5951        // The second spawn terminating unfilled discharges the debt before
5952        // returning quantity: 0.8 restores only 0.5
5953        let rejected = OrderRejectedSpec::builder()
5954            .trader_id(second_order.trader_id())
5955            .strategy_id(second_order.strategy_id())
5956            .instrument_id(second_order.instrument_id())
5957            .client_order_id(second_order.client_order_id())
5958            .account_id(AccountId::from("BINANCE-001"))
5959            .reason("TEST_REJECTION".into())
5960            .build();
5961        algo.handle_order_event(OrderEventAny::Rejected(rejected));
5962
5963        let final_primary = algo.cache().order(&client_order_id).unwrap();
5964        assert_eq!(final_primary.quantity(), Quantity::from("0.5"));
5965        assert!(algo.core.spawn_fill_debt(client_order_id).is_none());
5966        assert_eq!(
5967            spawned_order.filled_qty() + final_primary.quantity(),
5968            Quantity::from("1.0"),
5969        );
5970    }
5971
5972    #[rstest]
5973    fn test_late_fill_on_child_that_fully_discharged_debt_recreates_debt() {
5974        let (mut algo, client_order_id, mut spawned_order) = setup_accepted_spawn();
5975        cancel_spawned_order(&mut algo, &mut spawned_order);
5976
5977        let mut child_b = spawn_reduced_child(&mut algo, client_order_id, Quantity::from("0.3"));
5978        let mut child_c = spawn_reduced_child(&mut algo, client_order_id, Quantity::from("0.5"));
5979        accept_spawned_order(&mut algo, &mut child_b);
5980        accept_spawned_order(&mut algo, &mut child_c);
5981        assert_eq!(
5982            algo.cache().order(&client_order_id).unwrap().quantity(),
5983            Quantity::from("0.2"),
5984        );
5985
5986        fill_spawned_order(&mut algo, &mut spawned_order, Quantity::from("0.5"));
5987        assert_eq!(
5988            algo.cache().order(&client_order_id).unwrap().quantity(),
5989            Quantity::from("0.0"),
5990        );
5991        assert_eq!(
5992            algo.core.spawn_fill_debt(client_order_id),
5993            Some(Quantity::from("0.3")),
5994        );
5995
5996        // B's cancellation fully discharges the debt; its record keeps the
5997        // gross released amount for late-fill tracking
5998        cancel_spawned_order(&mut algo, &mut child_b);
5999        assert_eq!(
6000            algo.cache().order(&client_order_id).unwrap().quantity(),
6001            Quantity::from("0.0"),
6002        );
6003        assert!(algo.core.spawn_fill_debt(client_order_id).is_none());
6004        assert_eq!(
6005            algo.core
6006                .spawn_reduction(child_b.client_order_id())
6007                .unwrap()
6008                .restored_qty
6009                .unwrap(),
6010            Quantity::from("0.3"),
6011        );
6012
6013        // B's late fill reverses the settlement for the filled amount
6014        fill_spawned_order(&mut algo, &mut child_b, Quantity::from("0.2"));
6015        assert_eq!(
6016            algo.cache().order(&client_order_id).unwrap().quantity(),
6017            Quantity::from("0.0"),
6018        );
6019        assert_eq!(
6020            algo.core.spawn_fill_debt(client_order_id),
6021            Some(Quantity::from("0.2")),
6022        );
6023
6024        cancel_spawned_order(&mut algo, &mut child_c);
6025        let final_primary = algo.cache().order(&client_order_id).unwrap();
6026        assert_eq!(final_primary.quantity(), Quantity::from("0.3"));
6027        assert!(algo.core.spawn_fill_debt(client_order_id).is_none());
6028        assert_eq!(
6029            spawned_order.filled_qty() + child_b.filled_qty() + final_primary.quantity(),
6030            Quantity::from("1.0"),
6031        );
6032    }
6033
6034    #[rstest]
6035    fn test_late_fill_on_child_after_partial_debt_discharge_nets_from_primary() {
6036        let (mut algo, client_order_id, mut spawned_order) = setup_accepted_spawn();
6037        cancel_spawned_order(&mut algo, &mut spawned_order);
6038
6039        let mut child_b = spawn_reduced_child(&mut algo, client_order_id, Quantity::from("0.8"));
6040        accept_spawned_order(&mut algo, &mut child_b);
6041        fill_spawned_order(&mut algo, &mut spawned_order, Quantity::from("0.5"));
6042        assert_eq!(
6043            algo.core.spawn_fill_debt(client_order_id),
6044            Some(Quantity::from("0.3")),
6045        );
6046
6047        // B's cancellation discharges 0.3 of debt and restores the net 0.5;
6048        // its record keeps the gross 0.8
6049        cancel_spawned_order(&mut algo, &mut child_b);
6050        assert_eq!(
6051            algo.cache().order(&client_order_id).unwrap().quantity(),
6052            Quantity::from("0.5"),
6053        );
6054        assert!(algo.core.spawn_fill_debt(client_order_id).is_none());
6055        assert_eq!(
6056            algo.core
6057                .spawn_reduction(child_b.client_order_id())
6058                .unwrap()
6059                .restored_qty
6060                .unwrap(),
6061            Quantity::from("0.8"),
6062        );
6063
6064        fill_spawned_order(&mut algo, &mut child_b, Quantity::from("0.3"));
6065        let final_primary = algo.cache().order(&client_order_id).unwrap();
6066        assert_eq!(final_primary.quantity(), Quantity::from("0.2"));
6067        assert_eq!(
6068            spawned_order.filled_qty() + child_b.filled_qty() + final_primary.quantity(),
6069            Quantity::from("1.0"),
6070        );
6071    }
6072
6073    #[rstest]
6074    fn test_emulated_spawn_refusal_restores_initialized_primary() {
6075        let (mut algo, client_order_id, _spawned_order) = setup_pending_spawn();
6076        let mut primary = algo.cache().order(&client_order_id).unwrap();
6077        let spawned = algo
6078            .spawn_limit(
6079                &mut primary,
6080                Quantity::from("0.3"),
6081                Price::from("50000.0"),
6082                TimeInForce::Gtc,
6083                None,
6084                false,
6085                false,
6086                None,
6087                Some(TriggerType::BidAsk),
6088                None,
6089                true,
6090            )
6091            .unwrap();
6092        assert_eq!(
6093            algo.cache().order(&client_order_id).unwrap().quantity(),
6094            Quantity::from("0.2"),
6095        );
6096
6097        let result = algo.submit_order(OrderAny::Limit(spawned), None, None);
6098
6099        assert!(result.is_err());
6100        assert_eq!(
6101            algo.cache().order(&client_order_id).unwrap().quantity(),
6102            Quantity::from("0.5"),
6103        );
6104    }
6105
6106    #[rstest]
6107    #[case(false)]
6108    #[case(true)]
6109    fn test_spawned_order_accepted_then_expired_restores_reduction(#[case] stopped: bool) {
6110        let (mut algo, client_order_id, mut spawned_order) = setup_accepted_spawn();
6111        if stopped {
6112            Component::stop(&mut algo).unwrap();
6113        }
6114
6115        expire_spawned_order(&mut algo, &mut spawned_order);
6116
6117        let final_primary = algo.cache().order(&client_order_id).unwrap();
6118        assert_eq!(final_primary.quantity(), Quantity::from("1.0"));
6119    }
6120
6121    #[rstest]
6122    fn test_partially_filled_spawned_order_canceled_restores_leaves_quantity() {
6123        let (mut algo, client_order_id, mut spawned_order) = setup_accepted_spawn();
6124        fill_spawned_order(&mut algo, &mut spawned_order, Quantity::from("0.2"));
6125
6126        cancel_spawned_order(&mut algo, &mut spawned_order);
6127
6128        let final_primary = algo.cache().order(&client_order_id).unwrap();
6129        assert_eq!(final_primary.quantity(), Quantity::from("0.8"));
6130    }
6131
6132    #[rstest]
6133    fn test_partially_filled_spawned_order_expired_restores_leaves_quantity() {
6134        let (mut algo, client_order_id, mut spawned_order) = setup_accepted_spawn();
6135        fill_spawned_order(&mut algo, &mut spawned_order, Quantity::from("0.2"));
6136
6137        expire_spawned_order(&mut algo, &mut spawned_order);
6138
6139        let final_primary = algo.cache().order(&client_order_id).unwrap();
6140        assert_eq!(final_primary.quantity(), Quantity::from("0.8"));
6141    }
6142
6143    #[rstest]
6144    #[case(false)]
6145    #[case(true)]
6146    fn test_fully_filled_spawned_order_consumes_reduction_without_restoration(
6147        #[case] stopped: bool,
6148    ) {
6149        let (mut algo, client_order_id, mut spawned_order) = setup_accepted_spawn();
6150        let spawned_id = spawned_order.client_order_id();
6151
6152        if stopped {
6153            Component::stop(&mut algo).unwrap();
6154        }
6155
6156        fill_spawned_order(&mut algo, &mut spawned_order, Quantity::from("0.5"));
6157
6158        let final_primary = algo.cache().order(&client_order_id).unwrap();
6159        assert_eq!(final_primary.quantity(), Quantity::from("0.5"));
6160        assert!(algo.core.take_pending_spawn_reduction(spawned_id).is_none());
6161    }
6162
6163    #[rstest]
6164    #[case::denied(true)]
6165    #[case::rejected(false)]
6166    fn test_spawned_order_refusal_then_terminal_event_restores_only_once(
6167        #[case] denied: bool,
6168        #[values(false, true)] stopped: bool,
6169    ) {
6170        // A canceled event after a denial/rejection is not an applicable state
6171        // transition and the engine drops such races before publication; the
6172        // second event is dispatched directly to exercise the handler's own
6173        // idempotence (the accounted unfilled quantity is unchanged).
6174        let (mut algo, client_order_id, spawned_order) = setup_pending_spawn();
6175        if stopped {
6176            Component::stop(&mut algo).unwrap();
6177        }
6178
6179        if denied {
6180            let event = OrderDeniedSpec::builder()
6181                .trader_id(spawned_order.trader_id())
6182                .strategy_id(spawned_order.strategy_id())
6183                .instrument_id(spawned_order.instrument_id())
6184                .client_order_id(spawned_order.client_order_id())
6185                .reason("TEST_DENIAL".into())
6186                .build();
6187            algo.core
6188                .cache_rc()
6189                .borrow_mut()
6190                .update_order(&OrderEventAny::Denied(event))
6191                .unwrap();
6192            algo.handle_order_event(OrderEventAny::Denied(event));
6193        } else {
6194            let event = OrderRejectedSpec::builder()
6195                .trader_id(spawned_order.trader_id())
6196                .strategy_id(spawned_order.strategy_id())
6197                .instrument_id(spawned_order.instrument_id())
6198                .client_order_id(spawned_order.client_order_id())
6199                .account_id(AccountId::from("BINANCE-001"))
6200                .reason("TEST_REJECTION".into())
6201                .build();
6202            algo.core
6203                .cache_rc()
6204                .borrow_mut()
6205                .update_order(&OrderEventAny::Rejected(event))
6206                .unwrap();
6207            algo.handle_order_event(OrderEventAny::Rejected(event));
6208        }
6209
6210        assert_eq!(
6211            algo.cache().order(&client_order_id).unwrap().quantity(),
6212            Quantity::from("1.0"),
6213        );
6214
6215        let canceled = OrderCanceledSpec::builder()
6216            .trader_id(spawned_order.trader_id())
6217            .strategy_id(spawned_order.strategy_id())
6218            .instrument_id(spawned_order.instrument_id())
6219            .client_order_id(spawned_order.client_order_id())
6220            .build();
6221        algo.handle_order_event(OrderEventAny::Canceled(canceled));
6222
6223        let final_primary = algo.cache().order(&client_order_id).unwrap();
6224        assert_eq!(final_primary.quantity(), Quantity::from("1.0"));
6225    }
6226
6227    #[rstest]
6228    #[should_panic(expected = "exceeds primary leaves_qty")]
6229    fn test_spawn_quantity_exceeds_leaves_qty_panics() {
6230        let mut algo = create_test_algorithm();
6231        register_algorithm(&mut algo);
6232
6233        let instrument_id = InstrumentId::from("BTC/USDT.BINANCE");
6234        let exec_algorithm_id = algo.id();
6235        let client_order_id = ClientOrderId::from("O-001");
6236
6237        let mut primary = OrderAny::Market(MarketOrder::new(
6238            TraderId::from("TRADER-001"),
6239            StrategyId::from("STRAT-001"),
6240            instrument_id,
6241            client_order_id,
6242            OrderSide::Buy,
6243            Quantity::from("1.0"),
6244            TimeInForce::Gtc,
6245            UUID4::new(),
6246            0.into(),
6247            false,
6248            false,
6249            None,
6250            None,
6251            None,
6252            None,
6253            Some(exec_algorithm_id),
6254            None,
6255            Some(client_order_id),
6256            None,
6257        ));
6258
6259        {
6260            let cache_rc = algo.core.cache_rc();
6261            let mut cache = cache_rc.borrow_mut();
6262            cache.add_order(primary.clone(), None, None, false).unwrap();
6263        }
6264
6265        let _ = algo
6266            .spawn_market(
6267                &mut primary,
6268                Quantity::from("0.8"),
6269                TimeInForce::Fok,
6270                false,
6271                None,
6272                true,
6273            )
6274            .unwrap();
6275
6276        assert_eq!(primary.quantity(), Quantity::from("0.2"));
6277        assert_eq!(primary.leaves_qty(), Quantity::from("0.2"));
6278
6279        // Should panic - spawning 0.5 when only 0.2 leaves_qty remains
6280        let _ = algo
6281            .spawn_market(
6282                &mut primary,
6283                Quantity::from("0.5"),
6284                TimeInForce::Fok,
6285                false,
6286                None,
6287                true,
6288            )
6289            .unwrap();
6290    }
6291}