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



  • 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.datas):
                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(txt)
            
            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()
    

    The output for this script is as follows :

    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
    

    It just stays here forever. Any help would be greatly appreciated.
    P.S : I am a beginner learning to use Backtrader


Log in to reply
 

});