For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
Open and exit at specific time
-
Hello community, I wanted to test opening and exiting a trade everyday at a specific hour of the day. Below is my code. There is no error msg but there is no trade being opened. Hope you can assist me on this. Many tks.
class daily_strategy(bt.Strategy): params = (('entrytime', 1), ('exittime', 12),('printlog', False)) #open trade at 1:00 UTC, exit at 12:00 UTC def log(self, txt, dt=None): ''' Logging function fot this strategy''' if self.params.printlog: dt = dt or self.datas[0].datetime.datetime(0).strftime('%Y-%m-%d %H:%M:%S') print('%s, %s' % (dt, txt)) def __init__(self): # Keep a reference to the "close" line in the data[0] dataseries self.dataclose = self.datas[0].close # BUY & SELL Signal Conditions self.buy_sig = self.datas[0].datetime.datetime(0).strftime('%H') == self.params.entrytime self.buy_exit = self.datas[0].datetime.datetime(0).strftime('%H') == self.params.exittime def next(self): self.log('Close, %.2f' % self.dataclose[0]) if self.order: return if not self.position.size and self.buy_sig : self.log('BUY CREATE, %.2f' % self.dataclose[0]) self.order = self.buy() if self.position.size > 0 and self.buy_exit: self.log('EXIT BUY CREATE, %.2f' % self.dataclose[0]) self.order = self.close()
-
You can keep the date condition is next itself..
class daily_strategy(bt.Strategy): params = (('entrytime', 1), ('exittime', 12),('printlog', False)) #open trade at 1:00 UTC, exit at 12:00 UTC def log(self, txt, dt=None): ''' Logging function fot this strategy''' if self.params.printlog: dt = dt or self.datas[0].datetime.datetime(0).strftime('%Y-%m-%d %H:%M:%S') print('%s, %s' % (dt, txt)) def __init__(self): # Keep a reference to the "close" line in the data[0] dataseries self.dataclose = self.datas[0].close def next(self): self.log('Close, %.2f' % self.dataclose[0]) if self.order: return if not self.position and self.datas[0].datetime.time() == datetime.time(self.params.entrytime , 0) : self.log('BUY CREATE, %.2f' % self.dataclose[0]) self.order = self.buy() if self.position > 0 and self.datas[0].datetime.time() == datetime.time(self.params.exittime , 0) : self.log('EXIT BUY CREATE, %.2f' % self.dataclose[0]) self.order = self.close()
-
Another alternative is to use timers: https://www.backtrader.com/docu/timers/timers/
-
@rajanprabu It works. Tks for your guidance!
-
@vladisld thank you. Will explore further.