from time import sleep
from pprint import pprint
# LOAD the ib.ext and ib.opt Libraries
from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import ibConnection, Connection, message
# DEFINE a basic function to capture error messages
def error_handler(msg):
print "IB: Server Error = ", msg
# DEFINE a catch-all function to print ALL the server replies
def IB_replies_handler(msg):
# DEBUG - Print Raw Server Output
# print "IB: Server Response = ", msg.typeName, msg
# DEFINE Global Counter Output
global c
c=c+1;
# HANDLE Message Type for Contract Details
if msg.typeName.strip() == "contractDetails":
print "Reply #" + str(msg.reqId) + ":"+ str(c)
# DEBUG
#dump(msg)
#dump(a)
#pprint (vars(a))
# DEFINE Contract objects that will be assigned the values of the IB Server replies
Ticker_DESC=None
Option_DESC=None
# ASSIGN the Underlying Security Details which encapsulate details on the Option Contracts
Ticker_DESC=msg.contractDetails
# EXTRACT and ASSIGN the Option Contracts details from the Ticker_DESC objects
Option_DESC=Ticker_DESC.m_summary
# PRINT Options Contract Details
print "=> [{0} ({1})] Call/Put: {2} Strike: {3} Expiration: {4}".format(
Option_DESC.m_localSymbol,Option_DESC.m_conId, Option_DESC.m_right, Option_DESC.m_strike,Option_DESC.m_expiry)
# DEBUG - Dump object
def dump(obj):
for attr in dir(obj):
print "obj.%s = %s" % (attr, getattr(obj, attr))
# Main code
c=0
# Create the connection to IBGW with client socket id=1234
# ibConnection = Connection.create
# ibgw_conTickerChannel = ibConnection(port=7496,clientId=1234)
ibgw_conTickerChannel = Connection.create(port=4001,clientId=1234)
ibgw_conTickerChannel.connect()
# Map server replies for "Error" messages to the "error_handler" function
ibgw_conTickerChannel.register(error_handler, 'Error')
# Map all server replies to "IB_replies_handler"
ibgw_conTickerChannel.registerAll(IB_replies_handler)
# Create a contract object and update the parameters that will be sent to the ContractDetails request
order_ticker = Contract()
order_ticker.m_symbol = 'MSFT'
order_ticker.m_secType = 'OPT'
order_ticker.m_currency = 'USD'
#order_ticker.m_localSymbol = 'MSFT'
# Make the request for ContractDetails with reqID = 1
ibgw_conTickerChannel.reqContractDetails(1,order_ticker)
# Leave connection open for long replies
sleep (240)
print 'disconnected', ibgw_conTickerChannel.disconnect()