IB TWS Trading Platform in Python 3 part 7 - profit and loss
In this tutorial lesson you will add labels and textboxes to hold the unrealized, realized, and total profit and loss
add code to calculate the marked profit and loss for both a long position and a short position
Add these variables to your project
self.unrealized = 0 # used in monitor position
self.realized = 0 # used in monitor position
self.unrealized_pnl = 0
self.realized_pnl = 0
self.marked_pnl = 0
Add this to the bottom of the create_widgets() function
add this code to the bottom of the cbSymbol_onEnter() function
they set the text boxes for Position, average price, unrealized, realized, and marked to zero, also the 2 variables realized_pnl, and marked_pnl to zero
In this tutorial you will understand more about what goes into the code to request historical data for certain trading instruments. Check out the other properties for Options, Futures, and Forex at the end of the page. In the video example we will request data for stocks. This only works with Interactive Brokers Paste this call to a function at the end of the connect_to_tws function (The highlighted text in yellow below)
# make sure this is included in the connect_to_tws functionself.register_callback_functions()
Paste this code after the connect_to_tws function and make sure all your indents are correct
defcontract_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)defregister_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')
deferror_handler(self, msg):
if msg.typeName == 'error'and msg.id != -1:
print ('Server Error:', msg)
defserver_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:
passelse:
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 listboxelif msg.typeName == "error"and msg.id != -1:
returndef 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:
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)
This will be a demo, I created an application on what the different attributes that you will need, and what data you can show with live examples.
The data that you can show is not the same for all securities for example the list below shows you can only request what is highlighted in yellow.
for a completes list of what to show and the times for requesting historical data you can use go to the following link below:
https://www.interactivebrokers.com/en/software/api/apiguide/tables/historical_data_limitations.htm