INTRADAY STRATEGY
-
Hai
I need to create an intraday strategy using time
For Example:-
Morning 1000 (US TIME) I need to take a long entry and in evening 1500 I need to close the position.
-
-
@run-out thanks for your message. I need to create a sample strategy using time. I am new to python. It's possible can you send me sample strategy using time.
My requirement
If time = 1100 I will take long entry morning 1000ck open.
If time 1500 I will close my position.please help me
-
@ambrishooty Can you show us what you've tried so far?
-
@run-out data =
import datetime
import backtrader as bt
import backtrader.feeds as btfeedsbtfeeds.GenericCSVData(dataname='D:\FOREXDATE\GBPUSD5MIN.csv',
datetime=0,
fromdate=datetime.datetime(2017, 12, 28),
timeframe=btfeeds.TimeFrame.Minutes,
dtformat=('%m/%d/%Y'),
tmformat=('%H.%M'),
open=2,
high=3,
low=4,
close=5,
volume=6,
openinterest=-1,
reverse=True)class IntradayStr(bt.Strategy):
def next(self): if not self.position: # not in the market if self.data[0].datetime.datetime.hour==7: self.buy() elif self.datas[0].datetime.datetime.hour==9: self.close() # close long position
cerebro = bt.Cerebro()
cerebro.adddata(data) # Add the data feedcerebro.addstrategy(IntradayStr) # Add the trading strategy
cerebro.run() # run it all
cerebro.plot() # and plot it with a single command -
@ambrishooty said in INTRADAY STRATEGY:
D:\FOREXDATE\GBPUSD5MIN.csv',
Can you show a couple of rows from the data file, include the date and the column headers please.
-
You had some issues and typos in your code.
To get the hours you need to use something like this:
"""
hour = self.datas[0].datetime.time().hour
"""
I adjusted the start and end times to match my data. 0700 was too early.In my code I use the following to load data:
"""
data = bt.feeds.GenericCSVData(
dataname="data/dev.csv",
dtformat=("%Y-%m-%d %H:%M:%S"),
timeframe=bt.TimeFrame.Minutes,
compression=1,
)
"""
I think you have five minute data so you'll need to adjust
"""
compression=5
"""
If you are having trouble loading your data we'll have a look when you provide samples."""
import backtrader as btclass Strategy(bt.Strategy):
def log(self, txt, dt=None): """ Logging function fot this strategy""" dt = dt or self.data.datetime[0] if isinstance(dt, float): dt = bt.num2date(dt) print("%s, %s" % (dt, txt)) def print_signal(self): self.log( "o {:5.2f}\th {:5.2f}\tl {:5.2f}\tc {:5.2f}\tv {:5.0f}".format( self.datas[0].open[0], self.datas[0].high[0], self.datas[0].low[0], self.datas[0].close[0], self.datas[0].volume[0], ) ) 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 enougth cash if order.status in [order.Canceled, order.Margin]: if order.isbuy(): self.log("BUY FAILED, Cancelled or Margin") self.log if order.status in [order.Completed, order.Canceled, order.Margin]: if order.isbuy(): self.log( "BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f" % (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: %.2f, Cost: %.2f, Comm %.2f" % (order.executed.price, order.executed.value, order.executed.comm) ) self.bar_executed = len(self) # Write down: no pending order self.order = None def notify_trade(self, trade): if not trade.isclosed: return self.log("OPERATION PROFIT, GROSS %.2f, NET %.2f" % (trade.pnl, trade.pnlcomm)) def next(self): self.print_signal() hour = self.datas[0].datetime.time().hour if not self.position: # not in the market if hour == 10: self.buy() elif hour == 14: self.close() # close long position
if name == "main":
cerebro = bt.Cerebro() datapath = ("data/dev.csv") data = bt.feeds.GenericCSVData( dataname="data/dev.csv", dtformat=("%Y-%m-%d %H:%M:%S"), timeframe=bt.TimeFrame.Minutes, compression=1, ) cerebro.adddata(data) cerebro.addstrategy(Strategy) # Execute cerebro.run() cerebro.plot()
"""
-
Sorry about the formatting above. Facepalm.
You had some issues and typos in your code.
To get the hours you need to use something like this:
hour = self.datas[0].datetime.time().hour
I adjusted the start and end times to match my data. 0700 was too early.
In my code I use the following to load data:
data = bt.feeds.GenericCSVData( dataname="data/dev.csv", dtformat=("%Y-%m-%d %H:%M:%S"), timeframe=bt.TimeFrame.Minutes, compression=1, )
I think you have five minute data so you'll need to adjust
compression=5
If you are having trouble loading your data we'll have a look when you provide samples.
import backtrader as bt class Strategy(bt.Strategy): def log(self, txt, dt=None): """ Logging function fot this strategy""" dt = dt or self.data.datetime[0] if isinstance(dt, float): dt = bt.num2date(dt) print("%s, %s" % (dt, txt)) def print_signal(self): self.log( "o {:5.2f}\th {:5.2f}\tl {:5.2f}\tc {:5.2f}\tv {:5.0f}".format( self.datas[0].open[0], self.datas[0].high[0], self.datas[0].low[0], self.datas[0].close[0], self.datas[0].volume[0], ) ) 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 enougth cash if order.status in [order.Canceled, order.Margin]: if order.isbuy(): self.log("BUY FAILED, Cancelled or Margin") self.log if order.status in [order.Completed, order.Canceled, order.Margin]: if order.isbuy(): self.log( "BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f" % (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: %.2f, Cost: %.2f, Comm %.2f" % (order.executed.price, order.executed.value, order.executed.comm) ) self.bar_executed = len(self) # Write down: no pending order self.order = None def notify_trade(self, trade): if not trade.isclosed: return self.log("OPERATION PROFIT, GROSS %.2f, NET %.2f" % (trade.pnl, trade.pnlcomm)) def next(self): self.print_signal() hour = self.datas[0].datetime.time().hour if not self.position: # not in the market if hour == 10: self.buy() elif hour == 14: self.close() # close long position if name == "main": cerebro = bt.Cerebro() datapath = ("data/dev.csv") data = bt.feeds.GenericCSVData( dataname="data/dev.csv", dtformat=("%Y-%m-%d %H:%M:%S"), timeframe=bt.TimeFrame.Minutes, compression=1, ) cerebro.adddata(data) cerebro.addstrategy(Strategy) # Execute cerebro.run() cerebro.plot()
-
@run-out Thanks for your reply.
I run strategy I got an error. I have attached the error. Please look at it.Please help me to solve this error
my data formate
MM/DD/YYYY HH:MM
01/01/2021,00:05,1.3676,1.3676,1.3667,1.3668,5,4
01/01/2021,00:20,1.3672,1.3672,1.3672,1.3672,1,0
01/01/2021,00:25,1.3668,1.3673,1.3668,1.3672,1,3
01/01/2021,00:30,1.3672,1.3672,1.3671,1.3672,2,4 -
@ambrishooty
Sorry my friend. If you cannot correct an indentation error in a body of functioning code, I don't think you are ready for backtrader. An indentation error is the most basic of errors.Backtrader needs a certain level of python knowledge. You need to go learn some more python first, and then come back and try again.
Good luck.
-
@run-out Thanks for your reply.
Please correct my error. I can understand I'm new to python ...I can pay for your time I need these small strategy examples after I can develop.
Please help me.
-
@ambrishooty recommend downloading a Python IDE like PyCharm. Has useful features like auto format and they have a free community edition that works well https://www.jetbrains.com/pycharm/download/#section=linux
Most importantly though, you need to learn Python and recommend stop using backtrader until then. You don't want to end up with something that likely won't be doing what you thought it was doing.
Here's a basic interactive site to practice https://www.learnpython.org/
Python wiki has more resources https://wiki.python.org/moin/BeginnersGuide/NonProgrammers