NAUTILUS / RUST source 3eb18933
Pages

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.rs
  • crates/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 a MarketOrder child.
  • spawn_limit: Creates a LimitOrder child with specified price and optional post_only or display_qty.
  • reduce_primary: If set to True, 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

  1. Contingency Handling: Manages ContingencyType such as OTO (One-Triggers-Other), OCO (One-Cancels-Other), and OUO (One-Updates-Other).
  2. Command Caching: Stores SubmitOrder commands for orders that are not yet active (e.g., the "Then" part of an OTO).
  3. Egress Routing: Provides methods to route commands back to the ExecutionEngine, RiskEngine, or OrderEmulator.

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, and LAST_PRICE.
  • Market Data: Processes QuoteTick, TradeTick, and OrderBookDeltas to 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

  1. On Start: The algorithm calculates the number of slices based on the horizon and interval.
  2. On Order: It receives the primary order via on_order(order) and begins the slicing schedule.
  3. Timer Callback: Every interval, it calls spawn_market or spawn_limit for the calculated slice quantity.
  4. 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:

  1. Define Config: Create an ExecutionAlgorithmConfig value for the Rust algorithm.
  2. Subclass ExecAlgorithm: Implement the on_order_initialized and on_order_filled methods.
  3. Manage State: Use the portfolio and cache to monitor positions and existing orders.
  4. Registration: Register the algorithm with the Trader or Strategy using a unique ExecAlgorithmId.

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.

Execution algorithms feeding canonical commands into the shared RiskEngine and ExecutionEngine path.


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.