To Build a Trading Bot with Python using Interactive Brokers API 1/3
Why build a trading bot using interactive brokers and python?
This page is a practical guide to build a sample trading strategy that can be readily implemented in live trading. It is not an academic theory on financial treatise, to make it accessible to the reader. Because practical strategies take a central place in this page, I make it sample as possible.
There are number of programming interfaces, including those provided by TD Ameritrade and E*Trade. Most of them are focusing on simplicity of development, finally, I chose Interactive Brokers (or IB) because:
- IB’s API is battle tested, it is a mature, retrieving high speed data and executing orders.
- IB’s API provided a wide-range of financial instrument for international markets. e.g. Stocks, Futures, Options, corporate bonds
- Low trading cost.
Other than broker selection, it is important to choosing the right programming language for back-testing and automated execution. Python is given that; it is easy to learn and not complicated to write any programming. It should be the most accessible programming language.
This post is focus on simplicity, With this in mind, the general operation of a trading bot can be split into five steps:
- Establish a connection to IB’s servers.
- Submit a request to IB’s server and execute the request on IB’s servers.
- Waiting for a response from IB’s servers, receive and process the response on your location desktop.
- Repeat Steps 2 and 3 until all desired requests have been executed and all response have been received.
- Terminate the connection.
Initialization
This is the initialization our application. To keep things simple, we’re just going to import a library “ib_insync” in the first step.
from ib_insync import *
Establish a connection to IB’s servers.
The application will be connect to the TWS.
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)<IB connected to 127.0.0.1:7497 clientId=1>
Submit a request to see my position.
ib.positions()[]
Submit a request to get historical data.
Suppose we want to get the EOD data of APPL, since we request 1 year or 365 days from the very beginning up until now.
There are three parameters with the class “Stock”
- Ticker
- Exchange
- Currency
contract = Stock('AAPL', 'SMART', 'USD')
ib.reqHeadTimeStamp(contract, whatToShow='TRADES', useRTH=True)
bars = ib.reqHistoricalData(
contract,
endDateTime='',
durationStr='365 D',
barSizeSetting='1 Day',
whatToShow='TRADES',
useRTH=True,
formatDate=1)
To check the beginning of the dataframe
bars[0]BarData(date=datetime.date(2019, 12, 20), open=70.56, high=70.665, low=69.64, close=69.86, volume=985390, average=70.29775, barCount=101303)
To check the end of the dataframe
bars[-1]BarData(date=datetime.date(2021, 6, 3), open=124.65, high=124.85, low=123.4, close=123.44, volume=14826, average=123.923, barCount=8507)df = util.df(bars)
display(df.head())
display(df.tail())
Plot the data
If you plot the chart in jupyter notebook, please remember include ‘inline’ on the notebook.
%matplotlib inlinedf.plot(y='close');
util.barplot(bars[-252:], title=contract.symbol);
Put it all together
from ib_insync import *
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)
ib.positions()
contract = Stock('AAPL', 'SMART', 'USD')
ib.reqHeadTimeStamp(contract, whatToShow='TRADES', useRTH=True)
bars = ib.reqHistoricalData(
contract,
endDateTime='',
durationStr='365 D',
barSizeSetting='1 Day',
whatToShow='TRADES',
useRTH=True,
formatDate=1)
bars[-1]
bars[0]
df = util.df(bars)
display(df.head())
display(df.tail())
%matplotlib inline
df.plot(y='close');
util.barplot(bars[-252:], title=contract.symbol);
Invite only, get hi now.
👉 https://hi.com/hiMorning
Twitter : twitter.com/algorimatica
Facebook : facebook.com/Algorimatica
WordPress : algorimatica.com
Patreon : patreon.com/Algorimatica