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.