Navigation

    Backtrader Community

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

    Buying and Selling at specific time (replication)

    General Code/Help
    2
    6
    112
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • H
      hangouts91 last edited by

      Hello, I found this https://community.backtrader.com/topic/3389/open-and-exit-at-specific-time post on how to buy and sell at specific time. I tried to replicate the code suggested by @rajanprabu but for some reason keep getting this error.

      '>' not supported between instances of 'NoneType' and 'int'
      

      Here is my code. I have 5 minute stock data

      class daily_strategy(bt.Strategy):
          params = (('entrytime', 10), ('exittime', 15),('printlog', True))  
                   #open trade at 10:00 UTC, exit at 15: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
              self.order = None
      
          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()
      

      The error that I get

      '>' not supported between instances of 'NoneType' and 'int'
      

      It appears that the strategy does not buy the stock at the specified time. That is why I do not have a position, which leads to the error. I cannot understand why it does not buy anything.

      Any help would be very much appreciated.

      run-out 1 Reply Last reply Reply Quote 0
      • run-out
        run-out @hangouts91 last edited by

        @hangouts91 said in Buying and Selling at specific time (replication):

        '>' not supported between instances of 'NoneType' and 'int'

        It would be most helpful if you included the few lines before that error, so we can see what it is referring to.

        RunBacktest.com

        H 2 Replies Last reply Reply Quote 0
        • H
          hangouts91 @run-out last edited by

          @run-out Sorry about that,

          Here is the full error

          File "C:\Users\OneDrive\backtrader.py", line 87, in <module>
              cerebro.run()
          
            File "C:\Users\User\anaconda3\envs\myenv\lib\site-packages\backtrader\cerebro.py", line 1127, in run
              runstrat = self.runstrategies(iterstrat)
          
            File "C:\Users\User\anaconda3\envs\myenv\lib\site-packages\backtrader\cerebro.py", line 1293, in runstrategies
              self._runonce(runstrats)
          
            File "C:\Users\User\anaconda3\envs\myenv\lib\site-packages\backtrader\cerebro.py", line 1695, in _runonce
              strat._oncepost(dt0)
          
            File "C:\Users\User\anaconda3\envs\myenv\lib\site-packages\backtrader\strategy.py", line 311, in _oncepost
              self.nextstart()  # only called for the 1st value
          
            File "C:\Users\User\anaconda3\envs\myenv\lib\site-packages\backtrader\lineiterator.py", line 347, in nextstart
              self.next()
          
            File "C:\Users\OneDrive\backtrader.py", line 76, in next
              if self.position > 0 and self.datas[0].datetime.time() == datetime.time(self.params.exittime , 0) :
          
          TypeError: '>' not supported between instances of 'Position' and 'int'
          
          run-out 1 Reply Last reply Reply Quote 0
          • H
            hangouts91 @run-out last edited by

            @run-out I figured that out, here's the code

            class daily_strategy(bt.Strategy):
                params = (('entrytime', 9), ('exittime', 15),('printlog', True))  
                         #open trade at 10:00 UTC, exit at 15: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 not self.position and self.datas[0].datetime.time() == datetime.time(self.params.entrytime , 30) :
            
                        self.log('BUY CREATE, %.2f' % self.dataclose[0])
                        self.buy()
                           
                    
                    if self.position and  self.datas[0].datetime.time() == datetime.time(self.params.exittime , 0) :
            
                        self.log('EXIT BUY CREATE, %.2f' % self.dataclose[0])
                        self.close()
            
            1 Reply Last reply Reply Quote 0
            • run-out
              run-out @hangouts91 last edited by

              @hangouts91 Thanks. Try:

              self.position.size
              

              Glad you got. Just a note for future readers, the Position object returns with the following attributes:

              --- Position Begin
              - Size: 1
              - Price: 75.288928057554
              - Price orig: 0.0
              - Closed: 0
              - Opened: 1
              - Adjbase: 85.71
              --- Position End
              

              If you make a condition of:

              if self.position
              

              You will be able to know if there's a position object. You can also use:

              if self.position.size > 0
              

              RunBacktest.com

              H 1 Reply Last reply Reply Quote 0
              • H
                hangouts91 @run-out last edited by

                @run-out Thanks, i will have a look at them

                1 Reply Last reply Reply Quote 0
                • 1 / 1
                • First post
                  Last post
                Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors