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

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.


    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
            # enter long
            elif self.crossover < 0:  # in the market & cross to the downside
                self.close()  # close long position
    cerebro = bt.Cerebro()
    store = bt.stores.IBStore(host="", port=7497, clientId=0) = store.getbroker()
    stockkwargs = dict(
        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)
    portvalue =
    pnl = portvalue - startcash
    print('Final Portfolio Value: ${}'.format(portvalue))
    print('P/L: ${}'.format(pnl))

Log in to reply