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[源代码]

基类:object

Intended 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)[源代码]

Initialize order execution bit information.

参数:
  • 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[源代码]

基类:object

Holds 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)[源代码]

Initialize order data.

参数:
  • 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)[源代码]

Add execution information to this order.

参数:
  • 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)[源代码]

Store an execution bit and recalculate order values.

参数:

exbit -- OrderExecutionBit to add.

getpending()[源代码]

Get list of pending execution bits.

返回:

List of pending OrderExecutionBit objects.

返回类型:

list

iterpending()[源代码]

Iterate over pending execution bits.

返回:

Iterator over pending OrderExecutionBit objects.

返回类型:

iterator

markpending()[源代码]

Mark current execution bits as pending.

Rebuilds the indices to mark which exbits are pending in clone.

clone()[源代码]

Clone the OrderData object.

返回:

A cloned copy with marked pending bits.

返回类型:

OrderData

class backtrader.order.OrderParams[源代码]

基类:object

Simple parameter container for Order classes.

Stores order parameters like owner, data, size, price, execution type, etc.

__init__(**kwargs)[源代码]

Initialize order parameters with defaults.

参数:

**kwargs -- Keyword arguments to override default parameters.

抛出:

AttributeError -- If an invalid parameter is provided.

class backtrader.order.OrderBase[源代码]

基类:object

Base 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)[源代码]

Initialize the order base instance.

参数:

**kwargs -- Order parameters (owner, data, size, price, etc.).

property plimit
clone()[源代码]

Clone the order.

返回:

A cloned copy with cloned executed OrderData.

返回类型:

OrderBase

getstatusname(status=None)[源代码]

Returns the name for a given status or the one of the order

getordername(exectype=None)[源代码]

Returns the name for a given exectype or the one of the order

classmethod ExecType(exectype)[源代码]

Get the execution type constant from the class.

参数:

exectype -- String name of the execution type.

返回:

The execution type constant.

返回类型:

int

ordtypename(ordtype=None)[源代码]

Returns the name for a given ordtype or the one of the order

active()[源代码]

Check if the order is active.

返回:

True if order is active, False otherwise.

返回类型:

bool

activate()[源代码]

Activate the order.

alive()[源代码]

Returns True if the order is in a status in which it can still be executed

addcomminfo(comminfo)[源代码]

Stores a CommInfo scheme associated with the asset

addinfo(**kwargs)[源代码]

Add the keys, values of kwargs to the internal info dictionary to hold custom information in the order

isbuy()[源代码]

Returns True if the order is a Buy order

issell()[源代码]

Returns True if the order is a Sell order

setposition(position)[源代码]

Receives the current position for the asset and stores it

submit(broker=None)[源代码]

Marks an order as submitted and stores the broker to which it was submitted

accept(broker=None)[源代码]

Marks an order as accepted

brokerstatus()[源代码]

Tries to retrieve the status from the broker in which the order is.

Defaults to last known status if no broker is associated

reject(broker=None)[源代码]

Marks an order as rejected

cancel()[源代码]

Marks an order as cancelled

margin()[源代码]

Marks an order as having met a margin call

completed()[源代码]

Marks an order as completely filled

partial()[源代码]

Marks an order as partially filled

execute(dt, size, price, closed, closedvalue, closedcomm, opened, openedvalue, openedcomm, margin, pnl, psize, pprice)[源代码]

Receives data execution input and stores it

expire()[源代码]

Marks an order as expired. Returns True if it worked

trailadjust(price)[源代码]

Adjust trailing stop price.

参数:

price -- Current price for trailing calculation.

备注

Generic interface - override in subclasses for specific behavior.

class backtrader.order.Order[源代码]

基类:OrderBase

Order 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)[源代码]

Initialize the order instance.

参数:

**kwargs -- Order parameters (owner, data, size, price, etc.).

execute(dt, size, price, closed, closedvalue, closedcomm, opened, openedvalue, openedcomm, margin, pnl, psize, pprice)[源代码]

Execute the order with given 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.

expire()[源代码]

Check if order should be expired

返回:

If order has expired False: If order has not expired

返回类型:

True

trailadjust(price)[源代码]

Adjust trailing stop order price.

参数:

price -- Current market price for trailing calculation.

For buy orders: stop price moves up as price increases. For sell orders: stop price moves down as price decreases.

class backtrader.order.BuyOrder[源代码]

基类:Order

Buy order class.

Represents a buy order with ordtype set to Order.Buy.

ordtype = 0
class backtrader.order.StopBuyOrder[源代码]

基类:BuyOrder

Stop buy order class.

Used for buy orders that trigger when price crosses a threshold.

class backtrader.order.StopLimitBuyOrder[源代码]

基类:BuyOrder

Stop limit buy order class.

Used for buy orders that become limit orders after stop price is triggered.

class backtrader.order.SellOrder[源代码]

基类:Order

Sell order class.

Represents a sell order with ordtype set to Order.Sell.

ordtype = 1
class backtrader.order.StopSellOrder[源代码]

基类:SellOrder

Stop sell order class.

Used for sell orders that trigger when price crosses a threshold.

class backtrader.order.StopLimitSellOrder[源代码]

基类:SellOrder

Stop limit sell order class.

Used for sell orders that become limit orders after stop price is triggered.