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/

    Live Trading Multiple Instruments using IB Data Feeds

    General Discussion
    3
    5
    142
    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.
    • S
      shanka19 last edited by

      Hello everyone,

      I am able to run a single strategy on a single instrument and this works smoothly, however I am unable to figure out the way to run a single strategy on multiple instruments and live trade using the TWS API. I have gone through the multiple instruments example but it uses Yahoo Finance Historical Data test strategies. Here is my code for reference :

      from __future__ import (absolute_import, division, print_function,
                              unicode_literals)
      import backtrader as bt
      class St(bt.Strategy):
          def __init__(self):
              self.orderid = list()
              self.order = None
              self.inds = dict()
              for i,d in enumerate(self.data):
                  self.inds[d] = dict()
                  self.inds[d]['macd'] = bt.indicators.MACD(d, period_me1=12,period_me2=26,period_signal=9)
                  self.inds[d]['mcross_buy'] = bt.indicators.CrossOver(self.inds[d]['macd'].macd, 
                                                                       self.inds[d]['macd'].signal)
                  self.inds[d]['mcross_sell'] = bt.indicators.CrossOver(self.inds[d]['macd'].signal, 
                                                                        self.inds[d]['macd'].macd)
              
              print('--------------------------------------------------')
              print('Strategy Created')
              print('--------------------------------------------------')
              
          def logdata(self):
              txt = []
              txt.append('{}'.format(len(self)))
                 
              print(self.data)
              for i,d in enumerate(self.data):
                  txt.append('{}'.format(
                  d.datetime.datetime(0).isoformat()))
                  txt.append('{:.2f}'.format(d.open[0]))
                  txt.append('{:.2f}'.format(d.high[0]))
                  txt.append('{:.2f}'.format(d.low[0]))
                  txt.append('{:.2f}'.format(d.close[0]))
                  txt.append('{:.2f}'.format(d.volume[0]))
                  txt.append('{:.2f}'.format(self.inds[d]['mcross_buy'][0]))
                  txt.append('{:.2f}'.format(self.inds[d]['mcross_sell'][0]))
                  print(','.join(txt))
          
          bought = 0
          sold = 0
          
          def next(self):
              self.logdata()
              if not self.data_live:
                  return
              
              for i, d in enumerate(self.data):
                  if(self.inds[d]['mcross_buy'][0]>0.0):
                      self.buy(data = d)
                  elif(self.inds[d]['mcross_buy'][0]<0.0 and not self.sold):
                      self.sell(data = d)
              
          data_live = False
          def notify_data(self, data, status, *args, **kwargs):
              print('*' * 5, 'DATA NOTIF:', data._getstatusname(status),
                    *args)
              if status == data.LIVE:
                  self.data_live = True
          
          def notify_order(self, order):
              if order.status == order.Completed:
                  buysell = 'BUY ' if order.isbuy() else 'SELL'
                  txt = '{} {}@{}'.format(buysell, order.executed.size,
                                          order.executed.price)
                  print(txt)
                  
      def run(args=None):
          cerebro = bt.Cerebro(stdstats=False)
          store = bt.stores.IBStore(port=7496,clientId=100)
          data0 = store.getdata(dataname='TWTR',
                               timeframe=bt.TimeFrame.Ticks)
          data1 = store.getdata(dataname='AMD',
                               timeframe=bt.TimeFrame.Ticks)
          data2 = store.getdata(dataname='GE',
                               timeframe=bt.TimeFrame.Ticks)
          cerebro.resampledata(data0, timeframe=bt.TimeFrame.Seconds,
                               compression=10)
          cerebro.resampledata(data1, timeframe=bt.TimeFrame.Seconds,
                               compression=10)
          cerebro.resampledata(data2, timeframe=bt.TimeFrame.Seconds,
                               compression=10)
          cerebro.broker = store.getbroker()
          cerebro.addstrategy(St)
          cerebro.run()
      if __name__ == '__main__':
          run()
      

      Any help would be greatly appreciated. Thanks in advance!
      P.S : I am beginner learning to use Backtrader

      1 Reply Last reply Reply Quote 0
      • vladisld
        vladisld last edited by

        What problem do you see with your current code?

        1 Reply Last reply Reply Quote 0
        • S
          shanka19 last edited by

          Hi,
          When I run this code with TWS in the background I see the following output :

          Server Version: 76
          TWS Time at connection:20201022 10:55:39 EST
          --------------------------------------------------
          Strategy Created
          --------------------------------------------------
          ***** DATA NOTIF: DELAYED
          ***** DATA NOTIF: DISCONNECTED
          ***** DATA NOTIF: DISCONNECTED
          ***** DATA NOTIF: LIVE
          

          I cannot see the data being printed or the strategy being executed. I have tried to execute my strategy with a single instrument and it worked well! Thanks in advance!

          1 Reply Last reply Reply Quote 0
          • C
            chewbacca last edited by

            And where are you initializing the data feeds?

            S 1 Reply Last reply Reply Quote 0
            • S
              shanka19 @chewbacca last edited by

              @chewbacca The store is defined under run(args=None). The data feeds are also right below where the store is defined

              1 Reply Last reply Reply Quote 0
              • 1 / 1
              • First post
                Last post
              Copyright © 2016, 2017, 2018 NodeBB Forums | Contributors
              $(document).ready(function () { app.coldLoad(); }); }