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/

    Getting errors one after another

    General Code/Help
    2
    4
    80
    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.
    • Abhishek Agrawal
      Abhishek Agrawal last edited by

      I wanted to make a range breakout strategy. Mkt opens at 9:15 IST. I want the algo to calculate the range of 1st 15min bar and buy or sell if the price is above high or low. I have a 1 min data.
      in this code i am getting an IndexError.
      Please help
      @backtrader @ab_trader @run-out

      from __future__ import (absolute_import, division, print_function,
                              unicode_literals)
      import backtrader as bt
      import datetime
      # from datetime import datetime
      import os
      import sys
      import backtrader.feeds as btfeed
      
      import pandas as pd
      
      
      class TestStrategy(bt.Strategy):
          def log(self, txt, dt=None):
              dt = dt or self.data.datetime.datetime(0)
              print('%s, %s' % (dt.isoformat(), txt))
      
          def __init__(self):
              self.datahigh = self.datas[0].high
              self.datalow = self.datas[0].low
              self.dataclose = self.datas[0].close
              self.order = None
              self.buyprice = None
              self.buycomm = None
              # self.starttime = datetime.replace(hour=9, minute=30, second=0)
              # self.t = self.datas[0].datetime.time(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 enough cash
              if order.status in [order.Completed]:
                  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))
      
              elif order.status in [order.Canceled, order.Margin, order.Rejected]:
                  self.log('Order Canceled/Margin/Rejected')
      
              self.order = None
      
          def next(self):
      
              if self.order:
                  return
              if not self.position:
      
                  if self.dataclose[0] > self.datahigh[-1]:
                      self.log('BUY CREATED, %.2f' % self.dataclose[0])
      
                      # Keep track of the created order to avoid a 2nd order
                      self.order = self.buy()
      
                  else:
                      if self.dataclose[0] < self.datalow[-1]:
                          self.log('SELL CREATED, %.2f' % self.dataclose[0])
      
                          # Keep track of the created order to avoid a 2nd order
                          self.order = self.sell()
      
          def stop(self):
              self.log(' Ending Value %.2f' % (self.broker.getvalue()))
      
      
      if __name__ == '__main__':
          cerebro = bt.Cerebro()
      
      
          class DataFeed(btfeed.GenericCSVData):
              params = (
      
                  ('dtformat', '%Y%m%d'),
                  ('tmformat', '%H:%M:%S'),
                  ('datetime', 0),
                  ('time', 1),
                  ('open', 2),
                  ('high', 3),
                  ('low', 4),
                  ('close', 5),
                  ('volume', 6),
                  ('openinterest', 7)
              )
      
      
          data = DataFeed(dataname='BANKNIFTYFEB18.csv', timeframe=bt.TimeFrame.Minutes, compression=15,
                          fromdate=datetime.datetime(2017, 2, 1),
                          todate=datetime.datetime(2017, 2, 28))
      
          cerebro.adddata(data)
          cerebro.addstrategy(TestStrategy)
      
          cerebro.run()
      ext
      
      run-out 1 Reply Last reply Reply Quote 0
      • run-out
        run-out @Abhishek Agrawal last edited by

        @Abhishek-Agrawal said in Getting errors one after another:

        if self.dataclose[0] > self.datahigh[-1]:

        Although I can't see your error since you didn't include it, I suspect the above line is the problem. You are trying to find currnet and previous bar. On the first bar there is no previous bar. This will throw an error.

        You need to manually skip the first bar in next with a self.counter of some sort.

        def __init__(self):
            self.counter = 0
        
        def next(self):
            if self.counter == 0:
                self.counter += 1
                return
        

        RunBacktest.com

        1 Reply Last reply Reply Quote 1
        • Abhishek Agrawal
          Abhishek Agrawal last edited by

          It still doesn't work. Can u connect over teamviewer for some help.

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

            Can you include the errors you are getting here so that I or others can help you? Thanks.

            RunBacktest.com

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