I used the code Quickstart in the documentation but with my own data (which is on a minute basis). I would like now to understand why my orders are created but not executed at the same price and days later... thanks! I am really a beginner with the platform, so any help is more than welcome. This is the code I used so far:
class TestStrategy(bt.Strategy):
params = (
('maperiod', 60),
)
def log(self, txt, dt=None):
''' Logging function for this strategy'''
dt = dt or self.datas[0].datetime.date(0)
print('%s, %s' % (dt.isoformat(), txt))
def __init__(self):
# Keep a reference to the "close" line in the data[0] dataseries
self.dataclose = self.datas[0].close
self.data_cpa = self.datas[0].high
self.data_cpb = self.datas[0].low
self.order = None
self.buyprice = None
self.buycomm = None
self.sma = bt.indicators.SimpleMovingAverage(
self.datas[0], period=self.params.maperiod)
def notify_order(self, order):
if order.status in [order.Submitted, order.Accepted]:
# Buy/Sell order submitted/accepted to/by broker - Nothing to do
return
# Check if an order has been completed
# Attention: broker could reject order if not enough cash
if order.status in [order.Completed]:
if order.isbuy():
self.log(
'BUY EXECUTED, Price: %.8f, Cost: %.8f, Comm %.8f' %
(order.executed.price,
order.executed.value,
order.executed.comm))
self.buyprice = order.executed.price
self.buycomm = order.executed.comm
else: # Sell
self.log('SELL EXECUTED, Price: %.8f, Cost: %.8f, Comm %.8f' %
(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('Order Canceled/Margin/Rejected')
self.order = None
def notify_trade(self, trade):
if not trade.isclosed:
return
self.log('OPERATION PROFIT, GROSS %.8f, NET %.f' %
(trade.pnl, trade.pnlcomm))
self.htrade = trade
def next(self):
# Simply log the closing price of the series from the reference
self.log('Close, %.8f' % self.dataclose[0])
if self.order:
return
if not self.position:
if self.dataclose[0] >= self.sma[0]:
# BUY, BUY, BUY!!! (with all possible default parameters)
self.log('BUY CREATE, %.8f' % self.dataclose[0])
# Keep track of the created order to avoid a 2nd order
self.order = self.buy(price= self.dataclose[0])
else:
if self.dataclose[0] <= self.sma[0]:
# SELL, SELL, SELL!!! (with all possible default parameters)
self.log('SELL CREATE, %.8f' % self.dataclose[0])
# Keep track of the created order to avoid a 2nd order
self.order = self.sell(price= self.dataclose[0])