backtrader.order module¶
Backtrader Order Module.
This module provides order data structures and execution tracking.
- Key Classes:
OrderExecutionBit: Holds information about a single order execution. OrderData: Holds the full order data including creation and execution details.
- The order system supports:
Order creation and execution tracking
Partial execution handling
Commission calculation
PnL calculation for closed positions
Position size and price tracking
- class backtrader.order.OrderExecutionBit[source]¶
Bases:
objectIntended to hold information about order execution. A “bit” does not determine if the order has been fully/partially executed, it just holds information.
Member Attributes:
dt: datetime (float) execution time
# Execution time, float - size: how much was executed # How much was executed - price: execution price # Execution price - closed: how much of the execution closed an existing position # How much of existing position was closed - opened: how much of the execution opened a new position # How much new position was opened - openedvalue: market value of the “opened” part # Market value of opened position - closedvalue: market value of the “closed” part # Market value of closed position part - closedcomm: commission for the “closed” part # Commission for closed position part - openedcomm: commission for the “opened” part # Commission for opened position part - value: market value for the entire bit size # Market value of entire position - comm: commission for the entire bit execution # Commission for entire position - pnl: pnl generated by this bit (if something was closed) # PnL from closing part of position - psize: current open position size # Size of already opened position - pprice: current open position price # Price of already opened position
- __init__(dt=None, size=0, price=0.0, closed=0, closedvalue=0.0, closedcomm=0.0, opened=0, openedvalue=0.0, openedcomm=0.0, pnl=0.0, psize=0, pprice=0.0)[source]¶
Initialize order execution bit information.
- Parameters:
dt – Execution datetime.
size – Executed size.
price – Execution price.
closed – Size of position closed.
closedvalue – Value of closed position.
closedcomm – Commission for closed position.
opened – Size of new position opened.
openedvalue – Value of opened position.
openedcomm – Commission for opened position.
pnl – Profit/loss from closed position.
psize – Current position size.
pprice – Current position price.
- class backtrader.order.OrderData[source]¶
Bases:
objectHolds actual order data for Creation and Execution.
In the case of Creation the request made and in the case of Execution the actual outcome.
Member Attributes:
exbits : iterable of OrderExecutionBits for this OrderData # Serialized order execution information for this order
dt: datetime (float) creation/execution time # Order creation or execution time, string format
size: requested/executed size # Creation or execution size
price: execution price # Execution price. If no price or limit price is given, the order creation # or current closing price will be used as reference Note: if no price is given and no pricelimite is given, the closing price at the time or order creation will be used as reference
pricelimit: holds pricelimit for StopLimit (which has trigger first) # Limit price for stop limit (triggered first)
trailamount: absolute price distance in trailing stops # Absolute price distance in trailing stop
trailpercent: percentage price distance in trailing stops # Percentage distance in trailing stop
value: market value for the entire bit size # Market value of entire position
comm: commission for the entire bit execution # Commission for entire position execution
pnl: pnl generated by this bit (if something was closed) # PnL after closing position
margin: margin incurred by the Order (if any) # Margin required for order
psize: current open position size # Current position size
pprice: current open position price # Current position price
- __init__(dt=None, size=0, price=0.0, pricelimit=0.0, remsize=0, pclose=0.0, trailamount=0.0, trailpercent=0.0)[source]¶
Initialize order data.
- Parameters:
dt – Order datetime.
size – Order size.
price – Order price.
pricelimit – Limit price for stop orders.
remsize – Remaining size to execute.
pclose – Previous close price.
trailamount – Trailing amount for stop orders.
trailpercent – Trailing percent for stop orders.
- property plimit¶
- add(dt, size, price, closed=0, closedvalue=0.0, closedcomm=0.0, opened=0, openedvalue=0.0, openedcomm=0.0, pnl=0.0, psize=0, pprice=0.0)[source]¶
Add execution information to this order.
- Parameters:
dt – Execution datetime.
size – Executed size.
price – Execution price.
closed – Size of position closed.
closedvalue – Value of closed position.
closedcomm – Commission for closed position.
opened – Size of new position opened.
openedvalue – Value of opened position.
openedcomm – Commission for opened position.
pnl – Profit/loss from closed position.
psize – Current position size.
pprice – Current position price.
- addbit(exbit)[source]¶
Store an execution bit and recalculate order values.
- Parameters:
exbit – OrderExecutionBit to add.
- getpending()[source]¶
Get list of pending execution bits.
- Returns:
List of pending OrderExecutionBit objects.
- Return type:
- iterpending()[source]¶
Iterate over pending execution bits.
- Returns:
Iterator over pending OrderExecutionBit objects.
- Return type:
iterator
- class backtrader.order.OrderParams[source]¶
Bases:
objectSimple parameter container for Order classes.
Stores order parameters like owner, data, size, price, execution type, etc.
- __init__(**kwargs)[source]¶
Initialize order parameters with defaults.
- Parameters:
**kwargs – Keyword arguments to override default parameters.
- Raises:
AttributeError – If an invalid parameter is provided.
- class backtrader.order.OrderBase[source]¶
Bases:
objectBase class for order objects.
Provides the foundation for all order types with common attributes and methods for order tracking, status management, and execution.
- Class Attributes:
DAY: Constant for day order identification. Market, Close, Limit, Stop, StopLimit, StopTrail, StopTrailLimit: Order execution types. Buy, Sell: Order direction types. Created, Submitted, Accepted, Partial, Completed, Canceled, Expired, Margin, Rejected: Order status codes.
- ref¶
Unique order reference number.
- broker¶
Broker instance handling this order.
- p¶
OrderParams instance containing order parameters.
- DAY = datetime.timedelta(0)¶
- T_Close = 0¶
- T_Day = 1¶
- T_Date = 2¶
- T_None = 3¶
- V_None = range(0, 1)¶
- Market = 0¶
- Close = 1¶
- Limit = 2¶
- Stop = 3¶
- StopLimit = 4¶
- StopTrail = 5¶
- StopTrailLimit = 6¶
- Historical = 7¶
- ExecTypes = ['Market', 'Close', 'Limit', 'Stop', 'StopLimit', 'StopTrail', 'StopTrailLimit', 'Historical']¶
- OrdTypes = ['Buy', 'Sell']¶
- Buy = 0¶
- Sell = 1¶
- Created = 0¶
- Submitted = 1¶
- Accepted = 2¶
- Partial = 3¶
- Completed = 4¶
- Canceled = 5¶
- Expired = 6¶
- Margin = 7¶
- Rejected = 8¶
- Cancelled = 5¶
- Status = ['Created', 'Submitted', 'Accepted', 'Partial', 'Completed', 'Canceled', 'Expired', 'Margin', 'Rejected']¶
- refbasis = count(1)¶
- __init__(**kwargs)[source]¶
Initialize the order base instance.
- Parameters:
**kwargs – Order parameters (owner, data, size, price, etc.).
- property plimit¶
- clone()[source]¶
Clone the order.
- Returns:
A cloned copy with cloned executed OrderData.
- Return type:
- classmethod ExecType(exectype)[source]¶
Get the execution type constant from the class.
- Parameters:
exectype – String name of the execution type.
- Returns:
The execution type constant.
- Return type:
- active()[source]¶
Check if the order is active.
- Returns:
True if order is active, False otherwise.
- Return type:
- addinfo(**kwargs)[source]¶
Add the keys, values of kwargs to the internal info dictionary to hold custom information in the order
- submit(broker=None)[source]¶
Marks an order as submitted and stores the broker to which it was submitted
- brokerstatus()[source]¶
Tries to retrieve the status from the broker in which the order is.
Defaults to last known status if no broker is associated
- class backtrader.order.Order[source]¶
Bases:
OrderBaseOrder class for buy/sell orders.
Extends OrderBase with order type (buy/sell) and session end time handling. This is the main order class used for creating and managing trading orders.
- ordtype¶
Order type (Buy or Sell).
- dteos¶
Date/time of end of session for order validity.
- ordtype = None¶
- __init__(**kwargs)[source]¶
Initialize the order instance.
- Parameters:
**kwargs – Order parameters (owner, data, size, price, etc.).
- execute(dt, size, price, closed, closedvalue, closedcomm, opened, openedvalue, openedcomm, margin, pnl, psize, pprice)[source]¶
Execute the order with given parameters.
- Parameters:
dt – Execution datetime.
size – Executed size.
price – Execution price.
closed – Size of position closed.
closedvalue – Value of closed position.
closedcomm – Commission for closed position.
opened – Size of new position opened.
openedvalue – Value of opened position.
openedcomm – Commission for opened position.
margin – Margin required for the order.
pnl – Profit/loss from closed position.
psize – Current position size.
pprice – Current position price.
- class backtrader.order.BuyOrder[source]¶
Bases:
OrderBuy order class.
Represents a buy order with ordtype set to Order.Buy.
- ordtype = 0¶
- class backtrader.order.StopBuyOrder[source]¶
Bases:
BuyOrderStop buy order class.
Used for buy orders that trigger when price crosses a threshold.
- class backtrader.order.StopLimitBuyOrder[source]¶
Bases:
BuyOrderStop limit buy order class.
Used for buy orders that become limit orders after stop price is triggered.
- class backtrader.order.SellOrder[source]¶
Bases:
OrderSell order class.
Represents a sell order with ordtype set to Order.Sell.
- ordtype = 1¶