# make sure this is included in the connect_to_tws function
self.register_callback_functions()
Paste this code after the connect_to_tws function and make sure all your indents are correct def contract_creation(self):
self.listbox1.delete(0,END) # clears contents of the listbox
self.tws_conn.cancelHistoricalData(5) #cancels historical data
mySymbol = varSymbol.get() # get the symbol from the combobox
contract = self.create_contract(mySymbol,
'STK', # security STK = stock
'SMART', # exchange
'NASDAQ',# primary exchange
'USD') # currency
now = strftime('%Y%m%d %H:%M:%S', localtime(int(time())))
duration = varDuration.get() # get the duration ie. 1 D, 1 M, 1 Y
bar_size = varBarSize.get() # get the bar size ie. 5 mins, 2 mins, 1 day
self.tws_conn.reqHistoricalData(tickerId = 5, # contract number can be any number
contract=contract, # contract detail from above
endDateTime=now, # end date and time
durationStr=duration,
barSizeSetting=bar_size,
whatToShow='TRADES', # what to show ie. MIDPOINT, BID, ASK,
useRTH=1, # Regular trading hours 1 = RTH, 0 = all data
formatDate=1) # 1 = 20161021 09:30:00 2 = Unix time (Epoch)
def register_callback_functions(self):
# Assign server messages handling function.
self.tws_conn.registerAll(self.server_handler)
# Assign error handling function.
self.tws_conn.register(self.error_handler, 'Error')
def error_handler(self, msg):
if msg.typeName == 'error'and msg.id != -1:
print ('Server Error:', msg)
def server_handler(self, msg):
if msg.typeName == 'historicalData':
hd_date = msg.date
hd_open = msg.open
hd_high = msg.high
hd_low = msg.low
hd_close = msg.close
hd_volume = msg.volume
str_date = str(hd_date)
str_open = str(hd_open)
str_high = str(hd_high)
str_low = str(hd_low)
str_close = str(hd_close)
str_volume = str(hd_volume)
# creates a string containing date, open, high, low, close, volume
priceData2 = hd_date+","+str_open+","+str_high+","+str_low+","+str_close+","+str_volume
if 'finished' in hd_date:
pass
else:
str_data = hd_date, hd_open, hd_high, hd_low, hd_close, hd_volume
print (str_data) # prints info to the Python shell
self.listbox1.insert(END, priceData2) # adds info to the listbox
elif msg.typeName == "error" and msg.id != -1:
return
def create_contract(self, symbol, sec_type, exch, prim_exch, curr):
contract = Contract()
contract.m_symbol = symbol
contract.m_secType = sec_type
contract.m_exchange = exch
contract.m_primaryExch = prim_exch
contract.m_currency = curr
return contract
Interactive Brokers API identifies a financial instrument using an object class named contract.
The properties for contract are as follows:
Property | Description |
---|---|
conId | Contract id for the financial instrument. |
symbol | Stock symbol or symbol for Options or Futures |
secType | Type of instrument: Stock=STK, Option=OPT, Future=FUT, etc. |
expiry | used with Options or Futures: The expiration date format YYYYMMDD |
strike | Options: The Options Strike Price |
right | Options: The Options “PUT” or “CALL” |
multiplier | Contract multiplier for Futures or Options "100" |
exchange | Destination of order or requested. “SMART” = IB smart order router |
primaryExchange | Primary listing exchange where the instrument trades. NYSE, NASDAQ, AMEX, BATS, ARCA, etc. |
currency | Currency of the exchange USD or GBP or CAD or EUR, etc. |
http://interactivebrokers.github.io/tws-api/classIBApi_1_1Contract.html#gsc.tab=0 Examples, before a data request is made or before an order is submitted, an object of class contract will be created and its attributes will be populated with appropriate values used to identify the financial instrument. For example, to access market data for Netflix stock, set the properties:
conID = 5 | # Contract identifier |
symbol = "NFLX" | # Netflix stock symbol |
secType = "STK" | # Security type is a stock (STK) |
exchange = "SMART" | # Use IB’s Smart Order router to get the prices |
primary exchange = "NASDAQ" | # Use NASDAQ |
currency = "USD" | # USD Currency |
Historical data limitations Link
To access a September 2016 $40 Call option on Netflix : I believe there is a data fee for options. You need to pay for a data feed for the options in order to request data through the API
conID = 3 | # Contract ID |
symbol = "NFLX" | # Netflix’s stock symbol |
secType = "OPT" | # Security type is an Option (OPT) |
expiry = "20170120" | # January 20, 2017 Expiry YYYYMMDD |
strike = 90 | # $90.00 strike price |
right = "CALL" | # Call option |
multiplier = "100" | # multiplier 100 shares per contract for options |
exchange = "SMART" | # Use IB’s Smart Order router to get the prices |
currency = "USD" | # USD Currency |
To access a June 2017 Crude Oil Futures contract set the properties:
conID = 2 | # Contract Id |
symbol = "CL" | # Crude Oil underlying symbol (CL) |
secType = "FUT" | # Security type is an Future (FUT) |
expiry = "20170120" | # January 20, 2017 Expiry third Friday of month |
exchange = "NYMEX" | # Use IB’s Smart Order router to get the prices |
To access a foreign exchange quote such as Euro/USD:
conID = 6 | # Contract Id |
symbol = "EUR" | # Euro underlying (base currency) symbol (EUR/USD quote) |
secType = "CASH" | # Security type is Cash / FX |
exchange = "IDEALPRO" | # Use the IDEALPRO FX data source |
currency = "USD" | # Quoted currency is USD |
No comments:
Post a Comment