0

I get stuck in a sort of infinite loop when I am trying to get historical data on a contract for which there is no historical data.
In the code below I am trying to get historical data on a single stock option for 3 strikes and one expiry. The historical data exists for the 1st and 3rd strike but not for the 2nd strike.


import time
import pandas as pd
import collections
import datetime as dt

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.common import BarData

class TestApp(EClient, EWrapper):
    def __init__(self):
        EClient.__init__(self, self)
        self.data=collections.defaultdict(list)

    def error(self, reqId:int, errorCode:int, errorString:str):
        print("Error: ", reqId, "", errorCode, "", errorString)

    def historicalData(self, reqId:int, bar:BarData):
        print(bar.date, bar.close)

    def historicalDataEnd(self, reqId: int, start: str, end: str):
        print("HistoricalDataEnd. ReqId:", reqId, "from", start, "to", end)
        self.disconnect()
        print("finished")

def get_option_histo_prices(strike:str):

    app = TestApp()
    app.connect("127.0.0.1", 7496, 5)

    time.sleep(1)

    contract = Contract()

    contract.symbol = "UNH"
    contract.lastTradeDateOrContractMonth = "20200619"
    contract.secType = "OPT"   
    contract.right = "C"
    contract.exchange = "SMART"
    contract.currency = "USD"
    contract.multiplier = "100" 

    contract.strike = strike

    app.reqHistoricalData(1, contract, "","1 W", "8 hours", "TRADES", 1, 1, False, [])

    app.run()


for strike in ["280","140","240"]:
    try:
        prices = get_option_histo_prices(strike)
    except:
        print("no data for",strike)

I got the historical data for the 1st strike but then I receive the following error message

Error: 1 162 Historical Market Data Service error message:HMDS query returned no data: UNH 200619C00140000@SMART Trades

And after that the code stays stuck, it keeps running like if it was in an infinite loop. There is maybe something better to do with the exception.

Sara Mun
  • 73
  • 7
  • You'll have to show your code if it's stopping. The error message is just information and won't stop normal code. You might want to read http://interactivebrokers.github.io/tws-api/head_timestamp.html#reqHeadTimeStamp but it's unnecessary unless you want to go back in time as far as possible. – brian Jun 15 '20 at 22:57
  • @ brian, I have edited my message to show the code. I tried the reqHeadTimestamp but it does not solve the problem. If the contract does not have historical data it put me in 'an infinite loop'. – Sara Mun Jun 16 '20 at 23:43
  • It's not an exception, it's just information. There is never an exception thrown in the error callback. If an exception happens in your code, the API immediately disconnects. You problem is the code is NOT disconnecting. You never get the HistDataEnd call so the disconnect never happens and so you can't connect again. You are also connecting and disconnecting for every historical data request. This is unnecessary and might cause problems if TWS is slow to release the Client ID. – brian Jun 17 '20 at 02:01
  • @ Brian, thank you for your answer. How could I then force the code to get to the HistDataEnd call if I receive this information? – Sara Mun Jun 17 '20 at 10:51
  • @ Brian, following your message I have added a condition in the error function. If the error code is 162 it disconnects. It seems to work, thanks. Do you have some recommendation to improve the code. You mentioned that it is not good practice to connect and disconnect for every historical data request. Do you have some directions I could follow? – Sara Mun Jun 17 '20 at 12:26
  • You are not programming asynchronously. I would suggest using ib-insync, here's an example. https://github.com/erdewit/ib_insync/blob/master/notebooks/bar_data.ipynb – brian Jun 17 '20 at 17:27

1 Answers1

0

I'm pretty sure in python you can do a

try:
   #get your historical data
except HDMS query returned no data:
    #continue/break/go back to data collecting
TheUltimateGuide
  • 333
  • 3
  • 13
  • 1
    @ Ryan Yin, it does not work. I am not an expert in handling exception so I tried it as you wrote it and the syntax is incorrect. – Sara Mun Jun 16 '20 at 23:44