def read_option_chain(client, ticker): # Define a contract for the underlying stock contract = Contract() contract.symbol = ticker contract.secType = 'STK' contract.exchange = 'SMART' contract.currency = 'USD' client.reqContractDetails(0, contract) time.sleep(2) # Get the current price of the stock client.reqTickByTickData(1, contract, "MidPoint", 1, True) time.sleep(4) # Request strike prices and expirations if client.conid: client.reqSecDefOptParams(2, ticker, '', 'STK', client.conid) time.sleep(2) else: print('Failed to obtain contract identifier.') exit() # Create contract for stock option req_id = 3 if client.strikes: for strike in client.strikes: client.chain[strike] = {} for right in ['C', 'P']: # Add to the option chain client.chain[strike][right] = {} # Define the option contract contract.secType = 'OPT' contract.right = right contract.strike = strike contract.exchange = client.exchange contract.lastTradeDateOrContractMonth = client.expiration # Request option data client.reqMktData(req_id, contract, '100', False, False, []) req_id += 1 time.sleep(1) else: print('Failed to access strike prices') exit() time.sleep(5) # Remove empty elements for strike in client.chain: if client.chain[strike]['C'] == {} or client.chain[strike]['P'] == {}: client.chain.pop(strike) return client.chain, client.atm_price
def main(): app = TestApp() app.connect("127.0.0.1", 7497, 2) # socket port is set in TWS or IB Gateway settings time.sleep(1) # short sleep to allow connection contract = Contract() contract.symbol = instrument contract.secType = securitytype contract.exchange = exchange contract.currency = "USD" contract.lastTradeDateOrContractMonth = "201903" app.reqHistoricalData(1, contract, "", length, barSize, "TRADES", 1, 1, False, []) print(instrument) app.run() wb.save('RandomRawData.xlsx')