Search code examples
interactive-brokersibpy

Getting parameters of listed options & futures in Interactive Brokers API


There are a lot of examples showing how to get particular asset's price from Interactive Brokers. However, when I want to get the whole chain of options for one asset, I don't know which particular strikes are listed. Same for futures, I don't know which expirations are available at the moment. So, i.e., for options, I just loop through all possible strikes and reqMktData for each, also making a sleep(1) every 100 messages to avoid hitting the limit for number of requests per second. Obviously, many of these messages return with error "No security definition has been found for the request".

This looks like the wrong approach as it wastes lots of time on non-existing assets. Is there any more clean way to do this, or a special function for such purpose?


Solution

  • Implementing handler for contractDetailsEnd as suggested by Donn Lee. Thanks to both shashkello and Donn Lee.

    from ib.ext.Contract import Contract
    from ib.ext.ContractDetails import ContractDetails
    from ib.opt import ibConnection, message
    import time
    
    def watcher(msg):
        print msg
    
    def contractDetailsHandler(msg):
        contracts.append(msg.contractDetails.m_summary)
    
    def contractDetailsEndHandler(msg):
        global DataWait
        DataWait =  False
    
    con = ibConnection()
    con.registerAll(watcher)
    con.register(contractDetailsHandler, 'ContractDetails')
    con.register(contractDetailsEndHandler, 'ContractDetailsEnd')
    
    con.connect()
    
    contract = Contract()
    contract.m_exchange     = "SMART"
    contract.m_secType      =  "OPT"
    contract.m_symbol       = "VTR"
    #contract.m_multiplier   = "100"
    contract.m_currency     = "USD"
    
    
    con.reqContractDetails(1, contract)
    
    contracts = [] # to store all the contracts
    
    DataWait = True  ;  i = 0
    while DataWait and i < 90:
        i += 1 ; print i,
        time.sleep(1)
    
    con.disconnect()
    con.close()
    
    print contracts