Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Orders

Cerebro is the key control system inbacktrader andStrategy (asubclass) is the key control point of the end user. The latter needs a chainingmethod to other parts of the system and that’s whereorders play a keyrole.

Orders translate the decisions made by the logic in aStrategy into amessage suitable for theBroker 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 anorder instance to operate on

And theorders serve also as a communication method back to the user, tonotify how things are running in the broker.

  • Notification

    To Strategy method:notify_order (Strategy) which reports anorder instance

Order creation

When invoking thebuy,sell andclose the following parametersapply for creation:

  • data (default:None)

    For which data the order has to be created. IfNone then thefirst 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.

    IfNone thesizer instance retrieved viagetsizer willbe used to determine the size.

  • price (default:None)

    Price to use (live brokers may place restrictions on the actualformat if it does not comply to minimum tick size requirements)

    None is valid forMarket andClose orders (the marketdetermines the price)

    ForLimit,Stop andStopLimit orders this valuedetermines the trigger point (in the case ofLimit the triggeris obviously at which price the order should be matched)

  • plimit (default:None)

    Only applicable toStopLimit orders. This is the price at whichto set the implicitLimit order, once theStop has beentriggered (for whichprice has been used)

  • exectype (default:None)

    Possible values:

    • Order.Market orNone. 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 givenprice or better

    • Order.Stop. An order which is triggered atprice and executed like anOrder.Market order

    • Order.StopLimit. An order which is triggered atprice and executed as an implicitLimit order with price given bypricelimit

  • valid (default:None)

    Possible values:

    • None: this generates an order that will not expire (akaGood 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.datetime ordatetime.date instance: the date will be used to generate an order valid until the given datetime (akagood till date)

    • Order.DAY or0 ortimedelta(): a day valid until theEnd of the Session (akaday order) will be generated

    • numeric value: This is assumed to be a value corresponding to a datetime inmatplotlib coding (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 bybacktrader to keep trackof overlapping trades on the same asset. Thistradeid is sentback to thestrategy when notifying changes to the status of theorders.

  • **kwargs: additional broker implementations may support extra parameters.backtrader will pass thekwargs down to the created order objects

    Example: if the 4 order execution types directly supported bybacktrader are not enough, in the case of for exampleInteractive Brokers the following could be passed askwargs:

    orderType='LIT',lmtPrice=10.0,auxPrice=9.8

    This would override the settings created bybacktrader andgenerate aLIMIT IF TOUCHED order with atouched price of 9.8and alimit price of 10.0.

Note

Theclose method will examine the current position andcorrespondingly usebuy orsell to effectivelyclose theposition.size will also be automatically calculated unless theparameter is an input from the user, in which case a partialcloseor areversal can be achieved

Order notification

To receive notifications thenotify_order method has to be overriden in theuser subclassedStrategy (the default behavior is to do nothing). Thefollowing applies to those notifications:

  • Issued before the strategy’snext method is called

  • May (and will) happen several times for the sameorder with the same or different status during the samenext cycle.

    Anorder may be submitted to thebroker and beaccepted and itsexecutioncompleted beforenext will be invoked again.

    In this case at least 3 notifications will happen with the followingstatus values:

    • Order.Submitted because the order was sent to thebroker

    • Order.Accepted because the order was taken by thebroker and awaits potential execution

    • Order.Completed because in the example it was quickly matched and completely filled (which may be the case usually forMarket orders)

Notifications may happen even several times for the same status in the case ofOrder.Partial. This status will not be seen in thebacktesting broker(which doesn’t consider volume when matching) but it will for sure be set byreal brokers.

Real brokers may issue one or more executions before updating a position, andthis group of executions will make up for anOrder.Partial notification.

Actual execution data is in the attribute:order.executed which is anobject of typeOrderData (see below for the reference), with usual fieldsassize andprice

The values at the time of creation are stored inorder.created whichremains unchanged throughout the lifecycle of anorder

Order Status values

The following are defined:

  • Order.Created: set when theOrder instance is created. Never to be seen by end-users unlessorder instances are manually created rather than throughbuy,sell andclose

  • Order.Submitted: set when theorder instance has been transmitted to thebroker. This simply means it has beensent. Inbacktesting mode this will be an immediate action, but it may take actualtime with a real broker, which may receive the order and only first notify when it has been forwarded to an exchange

  • Order.Accepted: thebroker has 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: theorder has been partially executed.order.executed contains the current filledsize and average price.

    order.executed.exbits contains a complete list ofExecutionBitsdetailing the partial fillings

  • Order.Complete: theorder has been completely filled average price.

  • Order.Rejected: thebroker has rejected the order. A parameter (like for examplevalid to determine its lifetime) may not be accepted by thebroker and theorder cannot be accepted.

    The reason will be notified via thenotify_store method of thestrategy. Although this may seem awkward, the reason is that real lifebrokers will notify this over an event, which may or may not be direcltyrelated to the order. But the notification from the broker can still beseen innotify_store.

    This status will not be seen in thebacktesting 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 cancellation

    It must be taken into account that a request tocancel an order via thecancel method of the strategy is no guarantee of cancellation. Theorder may have been already executed but such execution may not have yetnotified by the broker and/or the notification may not have yet beendelivered to the strategy

  • Order.Expired: a previously acceptedorder 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 thebacktrader ecosystem. They maybeen extended and/or contain extra embedded information when operating withother 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 willnot reach the Accepted status) or before execution with each new barprice because cash has been drawn by other sources (future-likeinstruments may have reduced the cash or orders orders may have beenexecuted)

Member Attributes:

  • ref: unique order identifier

  • created: OrderData holding creation data

  • executed: OrderData holding execution data

  • info: custom information passed over methodaddinfo(). 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 theactual 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 notdetermine if the order has been fully/partially executed, it just holdsinformation.

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


[8]ページ先頭

©2009-2025 Movatter.jp