The article “Interactive Brokers Python API (Native) – A Step-by-step Guide” first appeared on AlgoTrading101 Blog.
How to set up the IB native Python API?
There are four basic steps to setting up a connection to the IB API in Python.
- Open an account with IB – IB offers demo accounts which are great for testing. If you decide to connect to a live account, there is a read-only option for the API in TWS which is useful when testing and in the early stages of getting to know the API.
- Download the IB Python native API – These are script files written in Python that facilitate the connection and communication with IB’s client which is in turn connected to their server.
- Download your IB client (TWS or IB Gateway) – You might already be familiar with TWS, the default trading client provided by Interactive Brokers. An alternate solution is to use the Interactive Brokers Gateway client. When starting out, it’s a good idea to use TWS while testing your script as it provides a visual confirmation of any activity in your account. It’s easy to switch to the Gateway later on.
- Choose your IDE – We code our Python scripts in an IDE of our choice. However, since we require a constant open connection, not all IDEs are suitable.
- Test for connectivity – Check out code sample below
Open an account with IB
We have dedicated a separate blog post on how to do this: “How to Sign Up for an Interactive Brokers Paper Trading Account“
To learn how to navigate the IB platform, check out this video: IBKR Short Video – TWS for Beginners – Getting Started
Download the IB Python native API
You can download the Python Native API by navigating to the Interactive Brokers website and by going to Technology – Trading APIs – Get API Software, or by following this link – http://interactivebrokers.github.io/
Make sure to select API version 9.73 or higher as anything prior to that does not have the Python source files needed. Also, you should be using Python version 3.1 or higher.
Run the downloaded msi file and go through the setup wizard. This will copy the required Python source files to your hard drive. Once completed, navigate over to the directory that you specified in the installer and drill down to this directory – /TWS API/source/pythonclient. In this folder, run the
python3 setup.py install file to install the API as a package.
Congratulations! You’ve now installed the IB API. Just to make sure it is installed correctly, go into your Python terminal and type in
import ibapi. If no errors appear, the install was successful.
The IB API installer will install a few files that enable compatibility with Excel and also make a registry change in the process. If you’re looking to avoid that, check out the instructions for setting up the API in Linux or on a Mac, the method works just as well for Windows.
Install the IB API in a Mac or Linux
The process is similar to the install described above for Windows. Navigate over to the install page linked above and a ZIP file is available for download under the Mac / Linux column. Unzip the file, and navigate over to IBJts/source/pythonclient and run
python3 setup.py install.
IB has written step by step instructions which can be found here – https://ibkb.interactivebrokers.com/article/2484
Final thoughts about installing the IB API
If you choose not to install the IB API Python source as a package, simply place your scripts in the pythonclient folder and run them from there.
Alternatively, take the ibapi folder from within the pythonclient folder and place it in the directory you are creating your scripts to access the API from.
If you’d like to install the IB API Python package in a virtual environment, check out the following link for more details – https://packaging.python.org/tutorials/installing-packages/
Download your IB client (TWS or IB Gateway)
What is TWS?
TWS is the standard client that manual traders use. This client is great when you’re just starting out as it provides visual confirmation of the many commands you can send to IB via Python.
What is IB Gateway
The IB Gateway is a minimal solution that simply allows a connection to be established and requires no configuration out of the box. It’s a great solution if you’re looking to save on resources and it’s the client typically used in application developments.
If you decide to use TWS, navigate over to Trader Workstation Configuration which can be found within the TWS terminal under Edit – Global Configuration – API – Settings. You should be looking at a screen that looks like this:
Make sure to check off Enable ActiveX and Socket Clients, this is the main requirement for the API.
If you’d like to play it on the safe side, check off Read-Only API to ensure orders don’t get executed accidentally while testing out the API.
Make note of the default Socket port, or optionally change it to another available port if you desire to do so.
Lastly, make sure Allow connections from localhost only is checked for security purposes.
The IB gateway is ready to go out of the box so there’s no need to check off the box to enable a connection like in TWS. If you’d like to configure some of the other options described above, go to the configuration page in Gateway by navigating to Configure – Settings – API – Settings.
Choose your IDE
Simply put, an IDE (Integrated development environment) is the software that you code in.
The method used to connect to the IB servers is a rather unique one. There are two common approaches when it comes to communication with trading servers.
The first one involves a direct connection to a server. In such a scenario, a Python script can be coded in your favorite IDE and a connection is made to a server. This is typically done via the requests library or through a websocket.
The second common method is via an IDE provided by the broker which often involves coding in a language proprietary to the broker.
The advantage that IB brings with its API is support for multiple languages and the option to code in your favorite IDE. Supported languages currently include Python, Java, C++, and .NET. There is also support for Microsoft’s ActiveX framework as well as DDE to establish a connection within Excel.
What makes IB unique is that a connection is made to the IB client software which acts as an intermediary to the IB servers. It requires an open, and constant connection which is why we use threading in the examples provided.
This presents a challenge to those that prefer to use an interactive Python development environment such as Jupyter notebooks or Spyder. The EClient functions (outgoing calls) tend to work fine but EWrapper functions (incoming data) present issues due to the lack of an open connection.
IB-insync is a third-party library that utilizes the asyncio library to provide an asynchronous single thread to interact with the API. This might be a solution to explore for those looking to use an interactive environment.
Popular Python IDE’s include IDLE, which is pre-packaged with Python, and PyCharm. VS Code, Sublime Text, and Atom also work great with Python and can be used with other programming languages as well.
If you don’t already have a favorite IDE, Sublime Text is a good option as it offers features such as code completion and syntax highlighting. It’s also easy to customize, compatible with other programming languages, and there are a ton of third-party libraries available to extend functionality.
VS code is also a good option. It offers the same functionality as Sublime Text with the added benefit of embedded Git control. Choosing an IDE comes down to personal preference and there isn’t a clear leader within the Python community when it comes to IDE’s. For this reason it’s worth testing out some of the popular ones to see which one suits your needs best.
Test for connectivity
Here is a simple code snippet to test a connection to the IB API. Make sure you change the socket port number in the function
app.connect if needed. The number beside the socket port is a client id used to identify your script to the API. It can be any unique positive integer.
from ibapi.client import EClient from ibapi.wrapper import EWrapper class IBapi(EWrapper, EClient): def __init__(self): EClient.__init__(self, self) app = IBapi() app.connect('127.0.0.1', 7497, 123) app.run() ''' #Uncomment this section if unable to connect #and to prevent errors on a reconnect import time time.sleep(2) app.disconnect() '''
Your output should look something like this:
Didn’t get an output? If you’ve tried running the script a few times and you’re not getting an output, change the client id to something unique.
Another reason you might not be seeing an output could be because the script ended before a connection was established. In this case, try using a sleep timer at the end of the code snippet to pause the script for a few seconds.
The Importance of EClient and EWrapper
There are several source code files in the IB Python API client folder. The two most important files are EClient and EWrapper.
For the most part, the EClient handles all outgoing requests while the EWrapper handles incoming messages. True to its name, EWrapper acts like a wrapper for incoming messages and in most cases, a function from it will need to be overwritten in your script to redirect the output to where you want it to go.
It’s worthwhile going through some of the source code files to become familiar with the API. And remember, you can always type in help(EClient) or help(EWrapper) in your Python terminal to get more information about the functions contained within them.
All the examples provided here start from the basic script. In it, the EClient and Ewrapper classes are first imported. A new custom class is then created and both the EClient and Ewrapper classes are passed through into it.
At this point, we instantiate the class using the
app variable in our examples, and call the
app.connect() command to specify the parameters required to create a connection. The
app.run() command executes starts the communication while
app.disconnect() is used at the end of the script to end the session and close the connection.
We will be adding threading to the basic script. The API connection will run in its own thread to ensure that communication to and from the server is not being blocked by other commands in the main block of the script.
Visit AlgoTrading101 to read the full article: https://algotrading101.com/learn/interactive-brokers-python-api-native-guide/
Disclosure: Interactive Brokers
Information posted on IBKR Traders’ Insight that is provided by third-parties and not by Interactive Brokers does NOT constitute a recommendation by Interactive Brokers that you should contract for the services of that third party. Third-party participants who contribute to IBKR Traders’ Insight are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.
This material is from AlgoTrading101 and is being posted with permission from AlgoTrading101. The views expressed in this material are solely those of the author and/or AlgoTrading101 and IBKR is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation to buy, sell or hold such security. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.
In accordance with EU regulation: The statements in this document shall not be considered as an objective or independent explanation of the matters. Please note that this document (a) has not been prepared in accordance with legal requirements designed to promote the independence of investment research, and (b) is not subject to any prohibition on dealing ahead of the dissemination or publication of investment research.
Any trading symbols displayed are for illustrative purposes only and are not intended to portray recommendations.
Disclosure: API Examples Discussed
Throughout the lesson, please keep in mind that the examples discussed are purely for technical demonstration purposes, and do not constitute trading advice. Also, it is important to remember that placing trades in a paper account is recommended before any live trading.
Disclosure: Order Types / TWS
The order types available through Interactive Brokers LLC’s Trader Workstation are designed to help you limit your loss and/or lock in a profit. Market conditions and other factors may affect execution. In general, orders guarantee a fill or guarantee a price, but not both. In extreme market conditions, an order may either be executed at a different price than anticipated or may not be filled in the marketplace.