How to connect to interactive brokers with Python

Published : Feb 4, 2024

We discussed setting up your Python environment in a previous article. Now the final step to being able to place algorithmic trades is installing interactive brokers trader workstation and then connecting to it with code.

This is going to allow you to write scripts that can run whilst you sleep, whilst you walk the dog, spend time with family etc. and it is an incredibly powerful skill to learn.

Firstly, you need to create a free demo account with interactive brokers here. If you use this link you can start earning up to $1,000 when you decide to transition from a demo to a paid account.

Next you need to install trader workstation here. This is where you can place trades physically, but will also act as a connection point for our python code.

You can now open up any choice of code editor, I use VS Code which you can install here. We can now go into the terminal of the code editor and use pipenv to install the package we need to connect to the trader workstation.

Now that is installed, we can create an IB instance by creating a new python file called main.py, importing the package and creating the instance like so:

If ib_insync has a squiggly line underneath it, it means you are not in the correct environment. Simply click on the environment at the bottom of VS Code, and choose the environment which has the name of your directory. It usually starts with the version of python e.g 3.12.0

For the next step we require some configurations inside the trader workstation, so open it up and login, we recommend to your demo account to start with. Click File > Global configurations > API > Settings. Make sure you check Enable ActiveX and Socket Clients.

Then scroll down and find ‘Socket Port 7496’ - take a note of the 4 digit number. Once you have noted this, apply and ok to save the settings.

We can now head back to our python file but do not close trader workstation, make sure you keep the application open. We can now add this line to our code, where 7496 represents the socket port you found in you API settings and noted down:

You can now type this code to check if you are connected, and simply run your file by clicking the play button in the top right of VS code, which should print the word ‘True’ to verify you have connected to trader workstation API:

Summary

Open demo account on interactive brokers

Download Trader workstation

Open it up and take note of your socket port

In your code editor, type: ib.connect('127.0.0.1', 7496, clientId=1)

You can now check your connected by printing: print(ib.isConnected())