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/

    Sample Code with Interactive Broker

    General Code/Help
    1
    1
    39
    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.
    • Jeffrey C F Wong
      Jeffrey C F Wong last edited by

      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)
      
      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(); }); }