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
当前未平仓价格