Orders
Cerebro is the key control system in backtrader and Strategy (a
subclass) is the key control point of the end user. The latter needs a chaining
method to other parts of the system and that’s where orders play a key
role.
Orders translate the decisions made by the logic in a Strategy into a
message suitable for the Broker to execute an action. This is done with:
-
Creation
Through Strategy’s methods:
buy\``,sellandclose(Strategy) which return anorder` instance as a reference -
Cancellation
Through Strategy’s method:
cancel(Strategy) which takes an order instance to operate on
And the orders serve also as a communication method back to the user, to notify how things are running in the broker.
-
Notification
To Strategy method:
notify_order(Strategy) which reports anorderinstance
Order creation
When invoking the buy, sell and close the following parameters
apply for creation:
-
data(default:None)For which data the order has to be created. If
Nonethen the first data in the system,self.datas[0] or self.data0(akaself.data) will be used -
size(default:None)Size to use (positive) of units of data to use for the order.
If
Nonethesizerinstance retrieved viagetsizerwill be used to determine the size. -
price(default:None)Price to use (live brokers may place restrictions on the actual format if it does not comply to minimum tick size requirements)
Noneis valid forMarketandCloseorders (the market determines the price)For
Limit,StopandStopLimitorders this value determines the trigger point (in the case ofLimitthe trigger is obviously at which price the order should be matched) -
plimit(default:None)Only applicable to
StopLimitorders. This is the price at which to set the implicit Limit order, once the Stop has been triggered (for whichpricehas been used) -
exectype(default:None)Possible values:
-
Order.MarketorNone. A market order will be executed with the next available price. In backtesting it will be the opening price of the next bar -
Order.Limit. An order which can only be executed at the givenpriceor better -
Order.Stop. An order which is triggered atpriceand executed like anOrder.Marketorder -
Order.StopLimit. An order which is triggered atpriceand executed as an implicit Limit order with price given bypricelimit
-
-
valid(default:None)Possible values:
-
None: this generates an order that will not expire (aka Good till cancel) and remain in the market until matched or canceled. In reality brokers tend to impose a temporal limit, but this is usually so far away in time to consider it as not expiring -
datetime.datetimeordatetime.dateinstance: the date will be used to generate an order valid until the given datetime (aka good till date) -
Order.DAYor0ortimedelta(): a day valid until the End of the Session (aka day order) will be generated -
numeric value: This is assumed to be a value corresponding to a datetime inmatplotlibcoding (the one used bybacktrader) and will used to generate an order valid until that time (good till date)
-
-
tradeid(default:0)This is an internal value applied by
backtraderto keep track of overlapping trades on the same asset. Thistradeidis sent back to the strategy when notifying changes to the status of the orders. -
**kwargs: additional broker implementations may support extra parameters.backtraderwill pass the kwargs down to the created order objectsExample: if the 4 order execution types directly supported by
backtraderare not enough, in the case of for example Interactive Brokers the following could be passed as kwargs:orderType='LIT', lmtPrice=10.0, auxPrice=9.8This would override the settings created by
backtraderand generate aLIMIT IF TOUCHEDorder with a touched price of 9.8 and a limit price of 10.0.
Note
The close method will examine the current position and
correspondingly use buy or sell to effectively close the
position. size will also be automatically calculated unless the
parameter is an input from the user, in which case a partial close
or a reversal can be achieved
Order notification
To receive notifications the notify_order method has to be overriden in the
user subclassed Strategy (the default behavior is to do nothing). The
following applies to those notifications:
-
Issued before the strategy’s
nextmethod is called -
May (and will) happen several times for the same order with the same or different status during the same next cycle.
An order may be submitted to the broker and be accepted and its execution completed before
nextwill be invoked again.In this case at least 3 notifications will happen with the following
statusvalues:-
Order.Submittedbecause the order was sent to the broker -
Order.Acceptedbecause the order was taken by the broker and awaits potential execution -
Order.Completedbecause in the example it was quickly matched and completely filled (which may be the case usually forMarketorders)
-
Notifications may happen even several times for the same status in the case of
Order.Partial. This status will not be seen in the backtesting broker
(which doesn’t consider volume when matching) but it will for sure be set by
real brokers.
Real brokers may issue one or more executions before updating a position, and
this group of executions will make up for an Order.Partial notification.
Actual execution data is in the attribute: order.executed which is an
object of type OrderData (see below for the reference), with usual fields
as size and price
The values at the time of creation are stored in order.created which
remains unchanged throughout the lifecycle of an order
Order Status values
The following are defined:
-
Order.Created: set when theOrderinstance is created. Never to be seen by end-users unlessorderinstances are manually created rather than throughbuy,sellandclose -
Order.Submitted: set when theorderinstance has been transmitted to thebroker. This simply means it has been sent. In backtesting mode this will be an immediate action, but it may take actual time with a real broker, which may receive the order and only first notify when it has been forwarded to an exchange -
Order.Accepted: thebrokerhas taken the order and it is in the system (or already in a exchange) awaiting execution according to the set parameters like execution type, size, price and validity -
Order.Partial: theorderhas been partially executed.order.executedcontains the current filledsizeand average price.order.executed.exbitscontains a complete list ofExecutionBitsdetailing the partial fillings -
Order.Complete: theorderhas been completely filled average price. -
Order.Rejected: thebrokerhas rejected the order. A parameter (like for examplevalidto determine its lifetime) may not be accepted by thebrokerand theordercannot be accepted.The reason will be notified via the
notify_storemethod of thestrategy. Although this may seem awkward, the reason is that real life brokers will notify this over an event, which may or may not be direclty related to the order. But the notification from the broker can still be seen innotify_store.This status will not be seen in the backtesting broker
-
Order.Margin: the order execution would imply a margin call and the previously accepted order has been taken off the system -
Order.Cancelled(orOrder.Canceled): confirmation of the user requested cancellationIt must be taken into account that a request to cancel an order via the
cancelmethod of the strategy is no guarantee of cancellation. The order may have been already executed but such execution may not have yet notified by the broker and/or the notification may not have yet been delivered to the strategy -
Order.Expired: a previously accepted order which had a time validity has expired and been taken off the system
Reference: Order and associated classes
These objects are the generic classes in the backtrader ecosystem. They may
been extended and/or contain extra embedded information when operating with
other brokers. See the reference of the appropriate broker
class backtrader.order.Order()
Class which holds creation/execution data and type of oder.
The order may have the following status:
-
Submitted: sent to the broker and awaiting confirmation
-
Accepted: accepted by the broker
-
Partial: partially executed
-
Completed: fully exexcuted
-
Canceled/Cancelled: canceled by the user
-
Expired: expired
-
Margin: not enough cash to execute the order.
-
Rejected: Rejected by the broker
This can happen during order submission (and therefore the order will not reach the Accepted status) or before execution with each new bar price because cash has been drawn by other sources (future-like instruments may have reduced the cash or orders orders may have been executed)
Member Attributes:
-
ref: unique order identifier
-
created: OrderData holding creation data
-
executed: OrderData holding execution data
-
info: custom information passed over method
addinfo(). It is kept in the form of an OrderedDict which has been subclassed, so that keys can also be specified using ‘.’ notation
User Methods:
-
isbuy(): returns bool indicating if the order buys
-
issell(): returns bool indicating if the order sells
-
alive(): returns bool if order is in status Partial or Accepted
class backtrader.order.OrderData(dt=None, size=0, price=0.0, pricelimit=0.0, remsize=0, pclose=0.0, trailamount=0.0, trailpercent=0.0)
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
-
dt: datetime (float) creation/execution time
-
size: requested/executed size
-
price: execution price 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)
-
trailamount: absolute price distance in trailing stops
-
trailpercent: percentage price distance in trailing stops
-
value: market value for the entire bit size
-
comm: commission for the entire bit execution
-
pnl: pnl generated by this bit (if something was closed)
-
margin: margin incurred by the Order (if any)
-
psize: current open position size
-
pprice: current open position price
class backtrader.order.OrderExecutionBit(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)
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
-
size: how much was executed
-
price: execution price
-
closed: how much of the execution closed an existing postion
-
opened: how much of the execution opened a new position
-
openedvalue: market value of the “opened” part
-
closedvalue: market value of the “closed” part
-
closedcomm: commission for the “closed” part
-
openedcomm: commission for the “opened” part
-
value: market value for the entire bit size
-
comm: commission for the entire bit execution
-
pnl: pnl generated by this bit (if something was closed)
-
psize: current open position size
-
pprice: current open position price