@run-out
Hi thank you very much :)
I have another doubt where in i noticed the results are not coming as expected and i am unable to validate certain conditions.For the 15 days thing I noticed if i run the code for 1 year it is taking all the dates and if i run it for 15 days it just takes day1.
Anyways,I am doing a small code where in I am trying to enter at high of second 15 min bar(9.30-9.44) with low as stoploss.
Viceversa for sell where i enter at low of second 15 min bar with high as stoploss.
As of now I am trying with only 2 exits-
Exit at 15:00 which is time_stop or exit when stoploss hits
However I also want to get the exact exit price when it happens.As i can see the placement of orders doesn't seem to work as per expectations and i get notifications in each iteration.Also in a day i can have only 2 orders i.e a buy and a sell.If buy side stoploss hits,then no second buy will be initiated for that day and if sell side stoploss hits then no second sell will be initiated for that day.
I have tried to change the code by placing orders.Please find the attached datafile used by me along with the code:-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import backtrader as bt
import datetime as dt
[link text](link url)import pandas as pd
import csv
import numpy as np
import talib as ta
import matplotlib.pyplot as plt
from datetime import datetime,time,date,timedelta
class CommInfo(bt.CommInfoBase):
params=(
('stocklike',False),
('commtype',bt.CommInfoBase.COMM_PERC),
)
def _getcommission(self, size, price, pseudoexec):
return abs(size)*price*self.p.commission*self.p.mult
class FirstStrategy(bt.Strategy):
params=(
('exitbars',12),
)
def log(self,txt):
print(txt)
def notify_order(self, order):
if order.status in [order.Submitted,order.Accepted]:
return
if order.status in [order.Completed]:
if order.isbuy():
print(str(self.datetime.datetime(0))+" BUY TRIGGERED "+str(self.datetime.datetime())+str(" ")+str(self.buyorder.price))
self.log("Max high for {} is {}".format(self.current_date,self.ORH))
self.log("Max low for {} is {}".format(self.current_date, self.ORL))
self.log("Updated balance:" + str(cerebro.broker.getvalue()))
if order.issell():
#print("BUY EXIT possible price 1 "+str(self.datetime.datetime())+str(self.sellorder.price))
print(str(self.datetime.datetime(0))+" SELL TRIGGERED " + str(self.datetime.datetime()) +str(" ") + str(self.sellorder.price))
self.log("Max high for {} is {}".format(self.current_date, self.ORH))
self.log("Max low for {} is {}".format(self.current_date, self.ORL))
self.log("Updated balance:" + str(cerebro.broker.getvalue()))
self.bar_executed=len(self)
elif order.status in [order.Canceled, order.Margin, order.Rejected]:
pass
def __init__(self):
self.datetime = self.datas[0].datetime
self.dataclose = self.datas[0].close
self.dataopen = self.datas[0].open
self.datahigh = self.datas[0].high
self.datalow = self.datas[0].low
self.morning_start=datetime.now().replace(hour=9,minute=15,second=0,microsecond=0)
self.evening_end=datetime.now().replace(hour=14,minute=45,second=0,microsecond=0)
self.time_stop=datetime.now().replace(hour=15,minute=00,second=0,microsecond=0)
self.secondcandle_start=datetime.now().replace(hour=9,minute=30,second=0,microsecond=0)
self.secondcandle_stop=datetime.now().replace(hour=9,minute=44,second=0,microsecond=0)
self.current_date=None
self.current_time=None
self.ORH=None
self.ORL=None
self.buyorder=None
self.sellorder=None
self.buystoporder=None
self.sellstoporder=None
def next(self):
self.current_date=self.datetime.date(0)
self.current_time=self.datetime.time(0)
self.current_datetime=self.datetime.datetime(0)
#print(self.current_date)
#print(self.current_time)
if self.current_time==self.morning_start.time():
self.highlist=[]
self.lowlist=[]
#self.buy_counter=0
if self.current_time>=self.secondcandle_start.time() and self.current_time<=self.secondcandle_stop.time():
self.highlist.append(self.datahigh[0])
self.lowlist.append(self.datalow[0])
self.ORH=max(self.highlist)
self.ORL=min(self.lowlist)
if not self.position:
self.buyorder=None
self.sellorder=None
if self.current_time>self.secondcandle_stop.time() and self.current_time<=self.evening_end.time():
self.buyorder=self.buy(exectype=bt.Order.Stop,price=self.ORH,plimit=self.ORH+1)
self.buystoporder=self.sell(exectype=bt.Order.StopLimit,price=self.ORL,plimit=self.ORL-1)
self.sellorder=self.sell(exectype=bt.Order.Stop,price=self.ORL,plimit=self.ORL-1)
self.sellstoporder=self.buy(exectype=bt.Order.StopLimit,price=self.ORH,plimit=self.ORH+1)
else:
if self.buyorder is not None:
if self.current_time==self.time_stop.time():
self.cancel(self.buystoporder)
self.close()
self.log("BUY EXIT PRICE:"+str(self.close()))
if self.sellorder is not None:
if self.current_time==self.time_stop.time():
self.cancel(self.sellstoporder)
self.close()
self.log("SELL EXIT PRICE:"+str(self.close()))
'''
if self.dataclose[0]-self.maxhigh>=2*(self.maxhigh-self.minlow):
self.cancel(self.stoporder)
self.sellorder=self.close()
self.log("BUY CLOSE:"+str(self.dataclose[0]))
self.log("Updated balance:"+str(cerebro.broker.getvalue()))
if self.current_time==self.closetime.time():
self.cancel(self.stoporder)
self.sellorder=self.close()
self.log("BUY CLOSE:"+str(self.dataclose[0]))
self.log("Updated balance:" + str(cerebro.broker.getvalue()))
'''
def stop(self):
self.log("Done with processing")
if __name__=='__main__':
cerebro=bt.Cerebro()
commissions=CommInfo(
commission=0.001,
mult=25,
margin=95000
)
cerebro.broker.addcommissioninfo(commissions)
cerebro.addstrategy(FirstStrategy)
datapath="D:/Trading/Backtesting_Course/testdata/banknifty2018_1min.csv"
data=bt.feeds.GenericCSVData(
dataname=datapath,
fromdate=dt.datetime(2011, 1, 1),
todate=dt.datetime(2019, 1, 1),
datetime=0,
timeframe=bt.TimeFrame.Minutes,
compression=1,
dtformat=('%Y-%m-%d %H:%M:%S'),
open=1,
high=2,
low=3,
close=4,
volume=None,
openinterest=None,
reverse=False,
header=0
)
cerebro.adddata(data)
# cerebro.adddata(data2)
cerebro.addsizer(bt.sizers.FixedSize, stake=1)
#cerebro.broker.setcommission(commission=0.001)
cerebro.broker.set_cash(1000000.00)
print("Starting portfolio value:" + str(cerebro.broker.getvalue()))
cerebro.run()
print("Final portfolio value:" + str(cerebro.broker.getvalue()))
Please find the below link of the datafile:-
https://drive.google.com/drive/folders/1epAaDQhHZ0IYdfCJvnT3hhgOLSfwJqVF?usp=sharing