天天看點

Backtrader Orders 訂單建立訂單Order notification 訂單通知

https://www.backtrader.com/docu/order/#order-notification

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.

當調用 buy\sell\close時會建立order

建立訂單

這三個函數可用的參數:

data (default: None)

使用的資料

預設為self.datas[0] or self.data0,如果建立時傳入了多個data可以指定

self.sell(data=self.data1)

size (default: None)

要買入\賣出\平倉的數量

如果沒有,則通過 getsizer 檢索的 sizer 執行個體将用于确定大小。

price (default: None)

價格 對于 Market 和 Close 訂單無效

For Limit, Stop and StopLimit orders this value determines the trigger point (in the case of Limit the trigger is obviously at which price the order should be matched)

對于“限制”、“停止”和“停止限制”訂單,這個值決定了觸發點(在“限制”的情況下,觸發器顯然應該與訂單的價格相比對)

plimit (default: None)

Only applicable to StopLimit orders. This is the price at which to set the implicit Limit order, once the Stop has been triggered (for which price has been used)

隻适用于停止限制指令。這是設定隐式限價指令的價格,一旦止損被觸發(已經使用了這個價格)

exectype (default: None)

有以下參數:

Order.Market or None 一個市場訂單将以下一個可用價格執行。在回測中,它将是下一個Bar的開盤價

Order.Limit 指令隻能以給定的價格或更高的價格執行

Order.Stop

Order.StopLimit

valid (default: None)

有以下選項:

None 這産生的訂單将不會到期,并保留在市場上,直到比對或取消。

datetime.datetime or datetime.date

Order.DAY or 0 or timedelta()

numeric value

tradeid (default: 0)

This is an internal value applied by backtrader to keep track of overlapping trades on the same asset. This tradeid is sent back to the strategy when notifying changes to the status of the orders.

用于追蹤同一資産上的重疊交易,當将訂單狀态的更改通知給政策時,這個貿易辨別被發送回來。

**kwargs

BUY

https://www.backtrader.com/docu/order-creation-execution/order-creation-execution/
# buy the main date, with sizer default stake, Market order
order = self.buy()

# Market order - valid will be "IGNORED"
order = self.buy(valid=datetime.datetime.now() + datetime.timedelta(days=3))

# Market order - price will be IGNORED
order = self.buy(price=self.data.close[0] * 1.02)

# Market order - manual stake
order = self.buy(size=25)

# Limit order - want to set the price and can set a validity
order = self.buy(exectype=Order.Limit,
                 price=self.data.close[0] * 1.02,
                 valid=datetime.datetime.now() + datetime.timedelta(days=3)))

# StopLimit order - want to set the price, price limit
order = self.buy(exectype=Order.StopLimit,
                 price=self.data.close[0] * 1.02,
                 plimit=self.data.close[0] * 1.07)

# Canceling an existing order
self.broker.cancel(order)
           

Order notification 訂單通知

要接收通知,需要在政策裡寫上notify_order

class MaCrossStrategy(bt.Strategy):
    params=(('maperiod',15),
            ('printlog',False),)
    
    def __init__(self):
        pass

    def next(self):
        pass
            
    #交易記錄日志
    def log(self, txt, dt=None):
        dt = dt or self.datas[0].datetime.date(0)
        print(f'{dt.isoformat()},{txt}')
    #記錄交易執行情況(可省略,預設不輸出結果)
    def notify_order(self, order):
        # 如果order為submitted/accepted,傳回空
        if order.status in [order.Submitted, order.Accepted]:
            return
        # 如果order為buy/sell executed,報告價格結果
        if order.status in [order.Completed]: 
            if order.isbuy():
                self.log(f'買入:\n價格:{order.executed.price},\
                成本:{order.executed.value},\
                手續費:{order.executed.comm}')
                self.buyprice = order.executed.price
                self.buycomm = order.executed.comm
            else:
                self.log(f'賣出:\n價格:{order.executed.price},\
                成本: {order.executed.value},\
                手續費{order.executed.comm}')
            self.bar_executed = len(self) 

        # 如果指令取消/交易失敗, 報告結果
        elif order.status in [order.Canceled, order.Margin, order.Rejected]:
            self.log('交易失敗')
            print(order.status,order.Margin)
        self.order = None
           

通知産生的情況:

  • Issued before the strategy’s next method 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 next will be invoked again.
  • In this case at least 3 notifications will happen with the following status values:

    – Order.Submitted because the order was sent to the broker

    – Order.Accepted because the order was taken by the broker and awaits potential execution

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

訂單狀态值

  • Order.Created 建立
  • Order.Submitted 送出給broker
  • Order.Accepted broker已接收
  • Order.Partial 訂單部分被執行 order.executed檢視訂單
  • Order.Complete 訂單已完成平均價格
  • Order.Rejected 被broker拒絕
  • Order.Margin 保證金不足\沒有足夠的現金執行訂單。
  • Order.Cancelled 使用者取消
  • Order.Expired 過期

源碼裡是:

Created, Submitted, Accepted, Partial, Completed, \
        Canceled, Expired, Margin, Rejected = range(9)
           

訂單方法

類 backtrader.Order. Order ()

類的新執行個體,該執行個體儲存建立/執行資料和 oder 類型。

isbuy(): returns bool indicating if the order buys

Isbuy () : 傳回 bool 表示訂單是否購買

issell(): returns bool indicating if the order sells

Issell () : 傳回 bool,訓示訂單是否賣出

alive(): returns bool if order is in status Partial or Accepted

如果訂單處于狀态,則傳回 bool

成員屬性:

ref: unique order identifier

唯一的指令辨別符

created: OrderData holding creation data

儲存建立資料的 OrderData

executed: OrderData holding execution data

Executed: OrderData 儲存執行資料

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

Info: 自定義資訊傳遞方法 addinfo ()。它以已經被子類化的 OrderedDict

的形式儲存,是以也可以使用‘來指定鍵。’符号

訂單類

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)

0,price = 0.0,pricelimit = 0.0,remsize = 0,pclose = 0.0,trailamount = 0.0,trailpercent = 0.0)

儲存建立和執行的實際訂單資料。

exbits : iterable of OrderExecutionBits for this OrderData

Exbits: 這個 OrderExecutionBits 的疊代

dt: datetime (float) creation/execution time

Dt: datetime (float)建立/執行時間

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

Value: 整個位大小的市場價值

comm: commission for the entire bit execution

整個比特執行的傭金

pnl: pnl generated by this bit (if something was closed)

Pnl: 由這個位生成的 pnl (如果什麼東西是關閉的)

margin: margin incurred by the Order (if any)

保證金: 指令産生的保證金(如果有的話)

psize: current open position size

Psize: 目前打開位置大小

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)

用于儲存有關訂單執行的資訊。

“Bit”不能确定訂單是否已經完全/部分執行,它隻能儲存資訊。

dt: datetime (float) execution time

Dt: datetime (float)執行時間

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

Openedvalue: “打開”部分的市場價值

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

Value: 整個位大小的市場價值

comm: commission for the entire bit execution

整個比特執行的傭金

pnl: pnl generated by this bit (if something was closed)

Pnl: 由這個位生成的 pnl (如果什麼東西是關閉的)

psize: current open position size

Psize: 目前打開位置大小

pprice: current open position price

目前未平倉價格