Trading with Interactive Brokers using Python by Dr. Hui Liu - 28 September 2016

Preview:

Citation preview

Speaker: Dr. Hui LiutradingwithIB.com | IBridgePy@gmail.com

28th September, 2016

Trading with Interactive Brokers using Python

Agenda

• Advantages of Interactive Brokers• Advantages of Python for trading• IBridgePy– Installation– Connecting to IB– PythonXY and Spider IDE– Real time quotes– Historical data– Place orders– An example code of moving average crossing

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

Advantages of Interactive Brokers

• IB API to automate trading• Low trading cost• Global markets access• Variety of products: stocks, options, futures,

forex, bonds, ETFs and CFDs

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

Advantages of Interactive Brokers

• Easy to learn• Availability of variety of modules• Open source

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

IBridgePy

Are you looking for a simple tool to trade with Interactive Brokers API using

Python, instead of using IBPy or Quantopian?• Python tool to trade with Interactive Brokers– Flexible– Easy to use– Privacy

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

Installation• Follow the link to download IBridgePy to your local

folder and unzip it. Then you will see file structures like that

• You are good to run your trading algo! Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

Connecting to IB• You need have at least a demo account at Interactive Brokers to try your

algo. • Download either TWS or IB Gateway to feed your needs

TWS will give you much more information about markets and interactive ways to communicate with IB

IB Gateway is the better choise if IB-everyday-retart is a concern for you

• Check ‘IB API’• Input your credentials and click ‘Login’

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

Connecting to IB (2)• In IB Gateway, -> Configure -> Settings

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

Connecting to IB (3)

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

PythonXY

• Python(x,y) is a free scientific and engineering development software for numerical computations, data analysis and data visualization based on Python programming language, Qt graphical user interfaces and Spyder interactive scientific development environment.

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

Prepare IDE• ‘View’-> ‘Panes’-> Check ‘Editor’ and ‘Console’• Add the folder to the Python Path by clicking ‘Tools’ -> ‘PYTHONPATH manager’

-> ‘Add path’ -> choose the folder where you unzip IBridgePy.• Then, click ‘Close’ to accept it.• It is preferred to restart the Spider IDE to make sure the Python path is

effective.

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

Run a sample code• Open RUN_ME.py in Spider IDE by clicking ‘File’-> ‘Open’• You may see Spider show up like the following

You may edit your code here

You will see results here

• To run the python code, click the green triangle or ‘F5’

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

Code structure

• "initialize()" is an built-in method to claim variables.• It will only be run once

• "handle_data()" is also an built-in method where trading decision is made• Two inputs are given here (context, data). "Context" contains the variables

claimed in initialize(). "data" is the live feed received either daily or minutely.

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

Run a sample code

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

Closer look at RUN_ME.py

• Line 16~ line 19: You may choose one algo that you want to execute by commenting out others

• Line 20: You account code at IB• Line 21: How often the function of handle_data(context, data), 60 means

to run it every minute and 1 means to run it every second. • Line 22: There are 4 levels to show results

– ERROR: only show error messages– INFO: typical users will use it to know the results of your algo– DEBUG: you may know more info when you debug your algo– NOTSET: You will see tremendous info if you really want to know what

is going onSpeaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

Three corner stones

• Real time price• Historical data• Place order

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

Ask for real time quotes

• When you need a real time price, simply call a build-in function of show_real_time_price

• For most of US stocks and ETF, you can simply put ‘AAPL’ for apple instead of ‘STK, AAPL, USD’

• For Forex, Future and Options, more info is needed to specify. For example, – 'FUT,ES,USD,201503‘– ‘OPT,AAPL,USD,20150702,133,P,100’– ‘CASH, EUR, USD’

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

Ask for historical data from IB• Request_data is used to ask all kinds of data form IB server• To ask for historical data from IB, a parameter “historyData” need to be

specified.

– Selecting the instrument for which the historical data needs to be obtained, in the above example, SPY, an ETF tracking S&P500 index

– Fixing the granularity (time gap), ‘1 day’– The period of go-back, ’50 D’ means go back 50 days from today.– The retrieved historical data are saved in a pandas dataframe that are

saved at hist, an attribute of the DataClass, saved in a dictionary called data

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

Ask for historical data from IB (2)• Of course you may request historical data from IB from other time period,

at other frequencies• The request format is defined by IB

https://www.interactivebrokers.com/en/software/api/api.htm

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

Ask for historical data from IB (3)

• Request multiple historical data at once

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

Place orders

• Place market orders: order(symbol(‘SPY’), 100)– Place an market– The target security is SPY– The action is to BUY 100 shares when n > 0– Negative number means SELL, -100 = SELL 100 shares– order_target(symbol(‘SPY’), 100) will adjust positions based on your

holding positions by either BUY or SELL until you hold 100 shares• Place Limit/Stop orders

– order(symbol(‘SPY’), 100, LimitOrder(213.42)) place a limit order to BUY 100 shares of SPY at price = $213.42 per share

– order(symbol(‘SPY’), -100, StopOrder(213.42)) place a stop order to SELL 100 shares of SPY at price = $213.42 per share

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

Place orders (2)

• It is highly recommended to follow up on the status of the order you placed by order_status_monitor()

– orderId is the unique identity of your order requests– For market orders, you should expect ‘Filled’ as the ending point of

your order request, which means the orders have been executed at IB– For limit and stop orders, the expected status is ‘Submitted’, which

means the orders have been accepted by IB and waiting for executions– For high liquidity securities, it won’t take too long ( a few seconds ) to

complete the transactions.

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

Place orders (3)

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

Moving average crossing

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

Thank You!If you need help, WE are here !

IBridgePy@gmail.comtradingwithIB.com

We have highly experienced in implementing various trading algorithms quickly

Speaker: Dr. Hui Liu (tradingwithIB.com | IBridgePy@gmail.com)

SINGAPORE30 Cecil Street, #19-08,Prudential Tower,Singapore – 049712Phone: +65-9057-8301

INDIAA-309, Boomerang,Chandivali Farm Road, Powai,Mumbai - 400 072Phone: +91-22-61691400

Learn Automated Trading

Join EPAT™The Executive Programme in

Algorithmic Trading

Enquire Now!

Recommended