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

Interactive brokers - can't retrieve historical data

  • Hi,

    I took some sample code from the quickstart. The code below works perfectly fine with EURUSD CSV data that I used. I'm now trying to use historical data from IB as I'll be planning to use them to trade live.

    # Create a Stratey
    class TestStrategy(bt.Strategy):
        params = (
            ('maperiod', 15),
        def log(self, txt, dt=None):
            ''' Logging function fot this strategy'''
            dt = dt or self.datas[0]
            print('%s, %s' % (dt.isoformat(), txt))
        def __init__(self):
            # Keep a reference to the "close" line in the data[0] dataseries
            self.dataclose = self.datas[0].close
            # To keep track of pending orders and buy price/commission
            self.order = None
            self.buyprice = None
            self.buycomm = None
            # Add a MovingAverageSimple indicator
            self.sma = bt.indicators.SimpleMovingAverage(
                self.datas[0], period=self.params.maperiod)
            # Indicators for the plotting show
            bt.indicators.ExponentialMovingAverage(self.datas[0], period=25)
            bt.indicators.WeightedMovingAverage(self.datas[0], period=25,
            rsi = bt.indicators.RSI(self.datas[0])
            bt.indicators.SmoothedMovingAverage(rsi, period=10)
            bt.indicators.ATR(self.datas[0], plot=False)
        def notify_order(self, order):
            if order.status in [order.Submitted, order.Accepted]:
                # Buy/Sell order submitted/accepted to/by broker - Nothing to do
            # 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():
                        'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                    self.buyprice = order.executed.price
                    self.buycomm = order.executed.comm
                else:  # Sell
                    self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                self.bar_executed = len(self)
            elif order.status in [order.Canceled, order.Margin, order.Rejected]:
                self.log('Order Canceled/Margin/Rejected')
            # Write down: no pending order
            self.order = None
        def notify_trade(self, trade):
            if not trade.isclosed:
            self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
                     (trade.pnl, trade.pnlcomm))
        def next(self):
            # Simply log the closing price of the series from the reference
            self.log('Close, %.2f' % self.dataclose[0])
            # Check if an order is pending ... if yes, we cannot send a 2nd one
            if self.order:
            # Check if we are in the market
            if not self.position:
                # Not yet ... we MIGHT BUY if ...
                if self.dataclose[0] > self.sma[0]:
                    # BUY, BUY, BUY!!! (with all possible default parameters)
                    self.log('BUY CREATE, %.2f' % self.dataclose[0])
                    # Keep track of the created order to avoid a 2nd order
                    self.order =
                if self.dataclose[0] < self.sma[0]:
                    # SELL, SELL, SELL!!! (with all possible default parameters)
                    self.log('SELL CREATE, %.2f' % self.dataclose[0])
                    # Keep track of the created order to avoid a 2nd order
                    self.order = self.sell()
    if __name__ == '__main__':
        cerebro = bt.Cerebro()
        # Add a strategy
        cerebro.addsizer(bt.sizers.FixedSize, stake=1000)
        # Create a Data Feed
    #     data = bt.feeds.PandasData(dataname=df)
        # Connect to IB data
        ibstore = bt.stores.IBStore(host='', port=7496, clientId=35)
        # Create a Data Feed
        data = ibstore.getdata(dataname='EUR.USD-CASH-IDEALPRO',
                        fromdate=datetime.datetime(2018, 1, 1),
                        todate=datetime.datetime(2019, 12, 31),
        # Add the Data Feed to Cerebro
        # Set our desired cash start
        # Set the commission - 0.1% ... divide by 100 to remove the %
        cerebro.addanalyzer(btanalyzers.SharpeRatio, _name='mysharpe')
        print('Starting Portfolio Value: %.2f' %
        print('Final Portfolio Value: %.2f' %

    the below is only giving the portfolio starting and end value but nothing has happened in between. again, with the CSV data I used, a lot of information from the log was being printed. The default parameters like historical are set to False. I can't really see what should be changed.

    Starting Portfolio Value: 100000.00
    Final Portfolio Value: 100000.00

  • anyone please?

  • I don't think that you can easily get data for 2018 - 2019 with ib. If I remember correctly, you should have several millions on the account and spend several thousands in commissions to get that deep. Google ib historical data limitations or something like this.

  • @ab_trader

    thanks, I'll look into this. only going back 2 years, I don't see any reason why it would be a problem. I don't know their policy but it seems odd to me. How would they expect to attract people if they can't properly backtest, unless they have deep pockets of course

  • IB is the brokerage company, not data provider. This is not their business. Common approach is to get data from the data providers for backtests.

Log in to reply