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/

    Problem to obtain Live data from IB for US options

    General Discussion
    1
    1
    320
    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.
    • P
      Palinosk last edited by

      Hello,
      Ia m not able to obtain Live data from IB for US options. I am subscribed to OPRA Top of Book (L1) (US Option Exchanges). I have not problems to connect to other products like stocks, futures where I have also subscription to data. When I connect directly through IbPy (with this script) it works and I obtain market data:

      from time import sleep
      from ib.ext.Contract import Contract
      from ib.opt import ibConnection
      
      def price_tick_handler(msg):
          """ function to handle price ticks """
          print (msg)
      
      #--------------main script------------------
      import ib
      print ('ibpy version:' , ib.__version__)
      tws = ibConnection('127.0.0.1', 7497) # create connection object
      tws.enableLogging() # show debugging output from ibpy
      tws.register(price_tick_handler, 'tickPrice') # register handler
      tws.connect() # connect to API
      
      #-------create contract and subscribe to data
      c = Contract()
      c.m_symbol = "NOK"
      c.m_secType= "OPT"
      c.m_exchange = "BOX"
      c.m_currency = "USD"
      c.m_right = "C"
      c.m_expiry = "20200717"
      c.m_strike = 4.0
      
      tws.reqMktData(1,c,"",False) # request market data
      
      #-------print data for a couple of seconds, then close
      sleep(10)
      
      print ('All done')
      
      tws.disconnect()
      

      ... but direcly through backtrader it freezes on DATA NOTIF: DELAYED. I use this code:

      from __future__ import (absolute_import, division, print_function,
                              unicode_literals)
      import backtrader as bt
      
      
      class St(bt.Strategy):
          def logdata(self):
              txt = []
              txt.append('{}'.format(len(self)))
      
              txt.append('{}'.format(
                  self.data.datetime.datetime(0).isoformat())
              )
              txt.append('{:.2f}'.format(self.data.open[0]))
              txt.append('{:.2f}'.format(self.data.high[0]))
              txt.append('{:.2f}'.format(self.data.low[0]))
              txt.append('{:.2f}'.format(self.data.close[0]))
              txt.append('{:.2f}'.format(self.data.volume[0]))
              print(','.join(txt))
      
          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)
      
          bought = 0
          sold = 0
      
          def next(self):
              self.logdata()
              if not self.data_live:
                  return
              if not self.bought:
                  self.bought = len(self)  # keep entry bar
                  self.buy()
              elif not self.sold:
                  if len(self) == (self.bought + 3):
                      self.sell()
      
      def run(args=None):
          cerebro = bt.Cerebro(stdstats=False)
          store = bt.stores.IBStore(port=7497) 
          data = store.getdata(dataname='NOK-OPT-BOX-USD-20200717-5.0-C-100',
                               timeframe=bt.TimeFrame.Ticks, historical=False)
          cerebro.resampledata(data, timeframe=bt.TimeFrame.Seconds,
                               compression=10)
          cerebro.addstrategy(St)
          cerebro.broker = store.getbroker() #changing the backtesting broker (which defaults to a broker simulation) engine to use the Interactive Brokers facilities
          cerebro.run()
      
      
      if __name__ == '__main__':
          run()
      

      Is something I am doing wrong? Is my dataname definition right? I try both definitions from Documentation wiki but without success:
      TICKER-YYYYMMDD-EXCHANGE-CURRENCY-STRIKE-RIGHT # OPT
      TICKER-YYYYMMDD-EXCHANGE-CURRENCY-STRIKE-RIGHT-MULT # OPT
      TICKER-OPT-EXCHANGE-CURRENCY-YYYYMMDD-STRIKE-RIGHT # OPT
      TICKER-OPT-EXCHANGE-CURRENCY-YYYYMMDD-STRIKE-RIGHT-MULT # OPT

      When I change Historical= True it give me historical data, but I need Live data of course. I am not out of trading hours and have subscription to data so I do not know what is wrong. Please help me with this problem. Thank you for your help.

      1 Reply Last reply Reply Quote 3
      • 1 / 1
      • First post
        Last post
      Copyright © 2016, 2017, 2018, 2019, 2020, 2021 NodeBB Forums | Contributors