Order Types & Execution
Relevant source files
The following files were used as context for generating this wiki page:
The Order Types & Execution system in Backtrader provides a robust framework for creating, managing, and tracking financial transactions. It supports both internal broker simulations for backtesting and live execution through external interfaces like Interactive Brokers (IB). The system architecture decouples order definition from the underlying transport and execution mechanism, allowing strategies to remain agnostic of whether they are running against historical data or a live market.
Orders are characterized by their execution type (Market, Limit, Stop, etc.), status lifecycle, and execution tracking through "bits" that record partial or full fills. Live execution modules translate these abstract order objects into broker-specific protocols, handling the asynchronous nature of market responses including submissions, acceptances, and execution details.
Order Lifecycle and Status
An order moves through a defined state machine from the moment it is created by a strategy until it reaches a "Done" state (Completed, Canceled, or Rejected).
Order States
The system tracks the status of an order via the Status attribute. Key states include:
- Created: Initial state when the strategy logic triggers a buy or sell.
- Submitted: Sent to the broker (simulated or live) and awaiting confirmation.
- Accepted: Acknowledged by the broker as a valid order in the system.
- Partial: The order has been partially filled but remains active for the remaining size.
- Completed: The order has been fully filled.
- Canceled: The user or strategy explicitly revoked the order.
- Rejected: The broker refused the order (e.g., due to insufficient margin or invalid parameters).
Sources: backtrader/order.py:461-496, backtrader/stores/ibstores/order.py:165-188
State Machine Flow
The following diagram illustrates the typical transitions of an order within the system.
This diagram shows the progression from order initiation to terminal states.
Sources: backtrader/order.py:461-480, samples/order-execution/order-execution.py:53-76
Supported Order Types
Backtrader supports a variety of execution types that dictate how the broker should interact with price action.
| Execution Type | Description | Key Parameters |
|---|---|---|
| Market | Executes immediately at the current market price. | size |
| Close | Intended to execute as close to the session close as possible. | size |
| Limit | Executes only at a specified price or better. | price |
| Stop | Becomes a market order once a trigger price is reached. | price |
| StopLimit | Becomes a limit order once a trigger price is reached. | price (trigger), plimit (limit) |
| StopTrail | A stop order where the trigger price follows the market at a set distance. | trailamount or trailpercent |
| StopTrailLimit | A trailing stop that converts to a limit order. | trailamount, plimit offset |
Sources: backtrader/order.py:438-456, backtrader/stores/ibstores/order.py:108-158, samples/order-execution/order-execution.py:115-167
Data Structures and Execution Tracking
The system uses specific classes to encapsulate order requirements and the resulting execution data.
OrderData
The OrderData class is used twice within an Order instance: once for created (the request) and once for executed (the outcome). It maintains the historical record of execution "bits" for partial fills.
- exbits: A collection of
OrderExecutionBitobjects. - remsize: The remaining size to be filled.
- price/psize: Cumulative average price and current open position size resulting from the order.
Sources: backtrader/order.py:122-171, backtrader/order.py:230-264
OrderExecutionBit
This structure holds the granular details of a specific fill event.
- dt: Execution timestamp.
- size: Quantity executed in this bit.
- price: Price at which this bit was filled.
- opened/closed: How much of the fill opened a new position vs. closing an existing one.
- pnl: Profit and loss generated if the bit closed a position.
Sources: backtrader/order.py:40-101
Live Execution via Interactive Brokers
Live execution is handled by stores like IBStoreInsync, which manages communication with the IB API.
Execution Flow
When an order is placed in a live environment, the IBStoreInsync translates the Backtrader order into an IB-compatible Order object and sends it via the Client.
This sequence illustrates the asynchronous communication loop between strategy logic and the live broker.
Sources: backtrader/stores/ibstore_insync.py:848-875, backtrader/stores/ibstores/client.py:400-590, backtrader/stores/ibstores/decoder.py:133-145
Live Order Translation
The Decoder class is responsible for deserializing messages from the broker socket. It maps message IDs to specific handlers like openOrder, orderStatus, and execDetails.
- Message ID 3: Handled by
orderStatusto update fill quantities and avg prices. - Message ID 5: Handled by
openOrderto sync orders existing in the broker but not yet in the strategy. - Message ID 11: Handled by
execDetailsto provide specific fill information for every transaction.
Sources: backtrader/stores/ibstores/decoder.py:38-125, backtrader/stores/ibstores/decoder.py:400-435
Order Targets
Strategies can utilize helper methods to target specific portfolio states rather than calculating sizes manually.
- order_target_size: Adjusts position to reach a specific number of units.
- order_target_value: Adjusts position to reach a specific monetary value.
- order_target_percent: Adjusts position to represent a specific percentage of the total portfolio value.
Sources: samples/order_target/order_target.py:84-118
Conclusion
The Order Types & Execution system provides a comprehensive abstraction layer that supports the full lifecycle of a trade. By using standardized status codes and execution bits, Backtrader ensures that strategies can precisely track their market exposure and financial performance. The decoupling of order definitions from the Interactive Brokers store allows for seamless transitions between high-fidelity backtesting and live trading.