For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/

Sample Code with Interactive Broker



  • Hi everyone, I am an IB user and a newbie at coding. I tried to implement the sample SMA strategy along with IB instead of the original yahoo data source. Everything looks to be working except for the buying and selling. Please help a newbie out here.

    Figure_0.png

    from __future__ import absolute_import, division, print_function, unicode_literals
    import backtrader as bt
    import datetime
    
    
    class SmaCross(bt.Strategy):
        # list of parameters which are configurable for the strategy
        params = dict(
            pfast=10,  # period for the fast moving average
            pslow=30   # period for the slow moving average
        )
    
       
        def __init__(self):
            sma1 = bt.ind.SMA(period=self.p.pfast)  # fast moving average
            sma2 = bt.ind.SMA(period=self.p.pslow)  # slow moving average
            self.crossover = bt.ind.CrossOver(sma1, sma2)  # crossover signal
    
        def next(self):
            if not self.position:  # not in the market
                if self.crossover > 0:  # if fast crosses slow to the upside
                    self.buy()  # enter long
    
            elif self.crossover < 0:  # in the market & cross to the downside
                self.close()  # close long position
    
    
    cerebro = bt.Cerebro()
    
    startcash=100000
    cerebro.broker.set_cash(startcash)
    
    store = bt.stores.IBStore(host="127.0.0.1", port=7497, clientId=0)
    cerebro.broker = store.getbroker()
    
    stockkwargs = dict(
        timeframe=bt.TimeFrame.Days,
        rtbar=False,  # use RealTime 5 seconds bars
        historical=True,  # only historical download
        qcheck=0.5,  # timeout in seconds (float) to check for events
        fromdate=datetime.datetime(2020, 11, 2, 0, 0, 0),  # get data from..
        todate=datetime.datetime(2020, 11, 4, 0, 0, 0),  # get data from..
        latethrough=False,  # let late samples through
        tradename=None  # use a different asset as order target
        )
    
    #data = store.getdata(dataname="MSFT-STK-SMART-USD", **stockkwargs)
    data = store.getdata(dataname="MES-202012-GLOBEX-USD", **stockkwargs)
    cerebro.resampledata(data, timeframe=bt.TimeFrame.Minutes, compression=2)# 2 min candles (compression=2)
    
    
    cerebro.addstrategy(SmaCross)
    
    portvalue = cerebro.broker.getvalue()
    pnl = portvalue - startcash
    print('Final Portfolio Value: ${}'.format(portvalue))
    print('P/L: ${}'.format(pnl))
    
    cerebro.run()
    cerebro.plot(style='candlestick',iplot=False)
    

Log in to reply
 

});