Rust edition: this page follows the live DeepWiki structure but treats the current Rust crates as implementation authority. Non-Rust surfaces are identified at their boundary and are not presented as Rust APIs.
Execution Algorithms
Relevant Rust source files
crates/trading/src/algorithm/mod.rscrates/trading/src/algorithm/core.rs
This page documents the execution algorithm framework in NautilusTrader, covering the ExecAlgorithm base class, implementation mechanics, the OrderManager for contingent routing, and guidance for creating custom algorithms. Execution algorithms enable automated execution strategies (e.g., TWAP, VWAP) by spawning and managing child orders to fill a parent "primary" order.
Overview
Execution algorithms are specialized actors that intercept primary orders and decompose them into a series of child orders. This process, known as spawning, allows for minimizing market impact, achieving benchmark prices, or implementing complex contingent logic.
Key Components
| Component | Role |
|---|---|
ExecAlgorithm |
Base class for execution logic, handling order spawning and event routing. |
OrderManager |
Manages the lifecycle of orders, including OTO (One-Triggers-Other) and OCO (One-Cancels-Other) contingencies. |
SubmitOrder |
The command used to initiate a parent order targeted at an algorithm. |
OrderList |
A container for multiple orders that can be submitted atomically with contingency instructions. |
Data Flow and Routing
The following diagram illustrates how a primary order is routed to an execution algorithm and subsequently spawned as child orders.
"SimulatedExchange""OrderManager""ExecAlgorithm (e.g. TwapAlgorithm)""RiskEngine""Strategy""SimulatedExchange""OrderManager""ExecAlgorithm (e.g. TwapAlgorithm)""RiskEngine""Strategy""Logic: Split 1000 units into 10 slices"loop[Every interval]"SubmitOrder(exec_algorithm_id='TWAP')""TradingCommand::SubmitOrder""spawn_market(primary, qty=100)""cache_submit_order_command(SubmitOrder)""SubmitOrder(child_order)""OrderFilled""on_order_filled(OrderFilled)""Primary Order Complete"
The ExecAlgorithm Base Class
The ExecAlgorithm class extends Actor, providing access to the Portfolio, Clock, and MessageBus. It is designed to be subclassed for specific execution logic. In the Rust implementation, ExecutionAlgorithm extends DataActor because algorithms do not own positions; they act as order processors for a parent Strategy
Core Implementation
The base class provides internal mechanics for tracking the relationship between primary orders and their spawned children using _exec_spawn_ids and _pending_spawn_reductions.
An ExecAlgorithm extends actor behavior with an algorithm identity, clock, message bus, cache, portfolio access and order-management operations. It emits ordinary canonical commands into the shared execution path.
Order Spawning Mechanics
When an algorithm "spawns" an order, it creates a new order linked to the primary.
spawn_market: Creates aMarketOrderchild.spawn_limit: Creates aLimitOrderchild with specified price and optionalpost_onlyordisplay_qty.reduce_primary: If set toTrue, the algorithm will automatically reduce the remaining quantity of the primary order as child orders are filled.
Event Handlers
Algorithms react to the order lifecycle through specific hooks:
on_order_initialized: Called when a primary order is first assigned to the algorithm.on_order_filled: Crucial for tracking the progress of child orders and determining when the parent is finished.on_order_rejected/on_order_denied: Used to handle execution failures or risk breaches.
OrderManager and Contingencies
The Rust OrderManager is used by execution algorithms and the OrderEmulator to manage complex order state and contingency triggers.
Responsibilities
- Contingency Handling: Manages
ContingencyTypesuch asOTO(One-Triggers-Other),OCO(One-Cancels-Other), andOUO(One-Updates-Other). - Command Caching: Stores
SubmitOrdercommands for orders that are not yet active (e.g., the "Then" part of an OTO). - Egress Routing: Provides methods to route commands back to the
ExecutionEngine,RiskEngine, orOrderEmulator.
Contingency Logic Flow
Contingency handling reacts to order events: OTO releases children, OCO cancels siblings, and OUO updates linked orders according to the owning OrderManager policy.
Order Emulation
The OrderEmulator is a specialized actor that provides local emulation for order types or triggers not supported natively by a venue (e.g., local Stop orders in a backtest or for certain live venues).
Matching Core
The emulator uses MatchingCore (Rust: OrderMatchingCore) to determine when an order should be triggered or filled based on market data updates.
- Trigger Types: Supports
TriggerType.DEFAULT,BID_ASK, andLAST_PRICE. - Market Data: Processes
QuoteTick,TradeTick, andOrderBookDeltasto advance the matching state.
Order emulation observes quotes and trades, evaluates matching-core trigger conditions, and releases or fills locally modeled orders without bypassing downstream risk and execution semantics.
Implementation Example: TWAP
The Time-Weighted Average Price (TWAP) algorithm is a standard example of using the framework to slice a large order over a fixed time horizon.
Configuration
The TwapAlgorithmConfig defines the execution parameters:
horizon_secs: Total duration of the execution.interval_secs: Time between slices.
Execution Logic
- On Start: The algorithm calculates the number of slices based on the horizon and interval.
- On Order: It receives the primary order via
on_order(order)and begins the slicing schedule. - Timer Callback: Every interval, it calls
spawn_marketorspawn_limitfor the calculated slice quantity. - Completion: Once the total quantity is filled or the horizon is reached, the primary order is marked as complete.
Custom Algorithm Implementation
To implement a custom algorithm, follow these steps:
- Define Config: Create an
ExecutionAlgorithmConfigvalue for the Rust algorithm. - Subclass ExecAlgorithm: Implement the
on_order_initializedandon_order_filledmethods. - Manage State: Use the
portfolioandcacheto monitor positions and existing orders. - Registration: Register the algorithm with the
TraderorStrategyusing a uniqueExecAlgorithmId.
ID Generation
Child orders generated by algorithms typically use a suffix to differentiate them from the primary order. The spawn_client_order_id function handles this by appending an incrementing integer to the primary ClientOrderId.
Handling Risk
All spawned orders are routed back through the RiskEngine. If a child order is rejected due to a risk check, the algorithm receives an OrderRejected event and must decide whether to retry, adjust parameters, or fail the primary order.
System Integration
Execution algorithms bridge the gap between high-level strategy intent and low-level venue execution. In backtesting, the BacktestEngine coordinates these components through simulated exchanges.
Summary of Key Classes
| Class | File Path | Description |
|---|---|---|
ExecutionAlgorithm |
crates/trading/src/algorithm/mod.rs |
Rust execution-algorithm contract. |
ExecutionAlgorithm |
crates/trading/src/algorithm/mod.rs |
Core trait for execution algorithms (Rust). |
OrderManager |
crates/execution/src/order_manager/manager.rs |
Utility for contingent order lifecycle management. |
OrderEmulator |
crates/execution/src/order_emulator/emulator.rs |
Component providing local order emulation for supported triggers. |
ExecutionAlgorithmCore |
crates/trading/src/algorithm/core.rs |
Rust core state management for algorithms. |