Wednesday, April 25, 2018

Using Interactive Brokers Python API

Some months ago Interactive Brokers released API software for the Python programmming language. Accessing the API with Python was already available with 3rd party software, but now it's part of the official API bundle.
I will show here a very basic example of how to get a basic application to connect with IB using the API. The example prints live quotes from stock tickers passed as parameters.

The API connects to the standard Trader Workstation (TWS) software, or it's also possible to use the specific IB Gateway software, which doesn't have the overhead of all the UX, so it might be convenient if you plan to leave the application working for a long time and want to save some PC resources.
You need to prepare your TWS or IB gateway before attempting to connect with the API, please check: http://interactivebrokers.github.io/tws-api/initial_setup.html#tws.

First of all, the MOST IMPORTANT THING TO NOTICE is that the API works in an asynchronous way, meaning that the results of your method calls are not returned right away, but your method call is queued in the system, and once the information is ready, it is returned in a callback. This is not completely clear in the API documentation, which makes it hard for someone new to start with it. After learning about this, using the API becomes trivial with the documentation in hand. The documentation can be found here: http://interactivebrokers.github.io/tws-api

There are 2 basic classes: EClient (which is in the client module) and EWrapper (which is in the wrapper module). EClient has all the necessary methods to initiate actions, like requesting market data or placing an order. EWrapper has all the callback methods that will be called by the API with the requested information, or with information regarding the outcome of your initiated actions.
The usual workflow is to override methods from EWrapper to handle the requests made with methods from EClient. Don't worry if it is not too clear now because with the attached example, this becomes more clear.
Check the client.py (which has the EClient class definition) and the wrapper.py (which has the EWrapper class definition) files from the API to see the available methods, the methods are properly documented with comments in the source code.

The example can be seen here: https://github.com/bsampietro/ib_example
If you don't use git (although I seriously recommend it), don't worry there is a link in github to download the code as a zip file.