Saturday, 29 October 2016

IB TWS Trading Platform in Python 7

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
        # create label for unrealized
        self.label_unrealized = Label(f1, font=('', 10), text='Unrealized').grid(row=10, column=2)

        # create label for realized
        self.label_realized = Label(f1, font=('', 10), text='Realized').grid(row=10, column=3)

        # create label for Marked
        self.label_Marked = Label(f1, font=('', 10), text='Marked').grid(row=10, column=4)

        # create entry box for unrealized
        self.tbUnrealized = Entry(f1, font=('', 10), width=12, textvariable=varUnrealized).grid(row=11, column=2)

        # create entry box for realized
        self.tbRealized = Entry(f1, font=('', 10), width=11, textvariable=varRealized).grid(row=11, column=3)

        # create entry box for Marked
        self.tbMarked = Entry(f1, font=('', 10), width=11, textvariable=varMarked).grid(row=11, column=4)

  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
        varPosition.set('0')
        varAvgPrice.set('0.00')
        self.realized_pnl = 0
        self.marked_pnl = 0
        varUnrealized.set('0.00')
        varRealized.set('0.00')
        varMarked.set('0.00')
  Add this to the monitor_position() function
        myShares = abs(self.position) # changes negative number to a position number
        varRealized.set(self.realized_pnl)
        if self.position > 0:
            self.unrealized = '%.2f' %((self.last_prices - self.average_price) * myShares)
            varUnrealized.set(self.unrealized)
            self.marked_pnl = '%.2f' %(float(self.unrealized) + float(self.realized_pnl))
            varMarked.set(self.marked_pnl)
        elif self.position < 0:
            self.unrealized = '%.2f' %((self.average_price - self.last_prices) * myShares)
            varUnrealized.set(self.unrealized)
            self.marked_pnl = '%.2f' %(float(self.unrealized) + float(self.realized_pnl))
            varMarked.set(self.marked_pnl)
        else:
            self.marked_pnl = float(self.unrealized_pnl) + float(self.realized_pnl)
            self.marked_pnl = '%.2f' % self.marked_pnl
            self.realized_pnl = '%.2f' % float(self.realized_pnl)
            varUnrealized.set('0.00')             
            varMarked.set(self.marked_pnl)
            varRealized.set(self.realized_pnl)
  add these string variables to the botton with the other textvariables for the 3 Entry boxes (text boxes)
varUnrealized = StringVar()
varRealized = StringVar()
varMarked = StringVar()

Pages: 1 2 3 4 5 6 7 8 9


Save Save Save Save Save Save

Tuesday, 11 October 2016

Python Historical Data 3

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 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



Pages: 1 2 3 4 5 6


Save Save Save Save Save Save Save Save Save Save Save Save Save Save Save

Sunday, 9 October 2016

IB TWS Historical Data in Python 2

 


from time import sleep, strftime, localtime, time
from ib.ext.Contract import Contract
from ib.ext.Order import Order
from ib.opt import Connection, message

from tkinter import *
from tkinter import ttk

class Application(Frame):
    """ a gui application"""

    def __init__(self, master):
        """ Initialize the Frame"""
        ttk.Frame.__init__(self, master)

        self.port=7496
        self.client_id = 97 # this number can be any number
        self.symbol_id, self.symbol = 5, 'MSFT'
        self.account_code = None
        self.strData = ""
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        """ create the window layout. """
        now = strftime('%Y%m%d %H:%M:%S', localtime(int(time())))
        myfont=('Arial', 12)
        myFont = ('Lucida Grande',12)
        
        # create a connect to tws button
        self.btnConnect = ttk.Button(self, text = "Connect", command=self.connect_to_tws)
        self.btnConnect.grid(row=0, column=1, sticky=W)

        # create a button to request the data
        self.btnGetData = ttk.Button(self, text = "Get Data", command=self.contract_creation)
        self.btnGetData.grid(row=0, column=2, sticky=W)

        # create a label for Symbol
        self.label_symbol = Label(root, text='Symbol').grid(row=1, column=0)
        
        # create a combobox for security symbol
        self.cbSymbol = ttk.Combobox(root, font=myfont, textvariable=varSymbol).grid(row=2, column=0)
        
        # create label for the endDateTime
        self.label_datetime = Label(root, font=myfont, text='End Date').grid(row=3, column=0)

        # create label for the duration
        self.label_duration = Label(root, font=myfont, text='Duration').grid(row=3, column=1)

        # create label for the barSizeSetting
        self.label_bar_size = Label(root, font=myfont, text='Bar Size').grid(row=3, column=2)

        # create Entry box (textbox) for the endDateTime
        self.tbDateTime = Entry(root, font=myfont, textvariable=varDateTime).grid(row=4, column=0)
        
        # create Combo box (textbox) for the duration 
        self.cbDuration = ttk.Combobox(root, font=myfont, textvariable=varDuration)
        self.cbDuration['values'] = ('1 Y', '1 M', '6 M', '1 D', '2 D')
        self.cbDuration.grid(row=4, column=1, sticky=W)

        # create Combo box (textbox) for the barSizeSetting
        self.cbBarSize = ttk.Combobox(root, font=myfont, textvariable=varBarSize)
        self.cbBarSize['values'] = ('1 day', '1 min', '2 mins', '5 mins')
        self.cbBarSize.grid(row=4, column=2, sticky=W)
        
        varDateTime.set(now)

        # create a listbox for the data make it 2 lines or the
        # listbox1.insert will not work you get an error
        # damn that is frustrating
        self.listbox1 = Listbox(root, font= ('', 12), width=75, height=30)
        self.listbox1.grid(row=6, column=0, columnspan=5, padx=5, pady=5, sticky='w')
            
    def connect_to_tws(self):
        self.tws_conn = Connection.create(port=7496, clientId=5)
        self.tws_conn.connect()

    def contract_creation(self):
        pass

root = Tk()

root.title("Historical data from IB TWS in Python please donate")
root.geometry("600x670")
root.attributes("-topmost", True)

varDateTime = StringVar()
varDuration = StringVar(root, value='1 D')
varBarSize = StringVar(root, value='5 mins')
varSymbol = StringVar(root, value='MSFT')

app = Application(root)

root.mainloop()



Pages: 1 2 3 4 5 6


Save

Saturday, 8 October 2016

IB TWS Historical Data in Python

Programs you will need to install

Python 3.4 or 3.5 but should work with others versions with small variations.  I am using version 3.5 https://www.python.org/ IBpy  I have a video on YouTube which will show you how to install it Here is a  link https://github.com/blampe/IbPy Ineractive brokers Traders Workstation https://www.interactivebrokers.com/en/index.php?f=14099#tws-software Interactive brokers API (Application Program Interface) http://interactivebrokers.github.io/# Make sure you global setting under the API menu are the same as below, although I don't think you need to check off the Enable DDE clients check box settingsAPI 2                    

Pages: 1 2 3 4 5 6

Save Save Save

Historical Data Examples Stocks Options Forex Futures

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