Hello, this is Gaoraz 🙂
Today, I will help you to write simple Python code using the IBKR TWS API.
Setting up softwares on Windows
If you have not yet installed Anaconda and Microsoft VS Code, see this article to set up your development environment.
Open paper trading account (interactivebrokers.com)
In this article, we will use a paper trade account for testing purposes. If you have not made one, follow the instructions below to create a paper trade account.
- Log in to Account Management. ( https://www.interactivebrokers.com/ )
- Click Manage Account (or your name) > Settings > Paper Trading.
Download & Install IBKR TWS
Download IBKR TWS from the link below.
Install the program using the default settings.
Powershell to set up a programming environment
Open Windows PowerShell
Type ‘Powershell’ in Windows search box and open Windows PowerShell.
Update conda
Update conda to the latest.
> conda update conda
Create virtual environment
This time, we will use Python 3.10 to build a virtual environment.
The virtual environment is named “ibkr” shown as below.
> conda create -n ibkr python=3.10
[TIPS] The list of installed virtual environments can be checked with the following command.
> conda info -e
Activate the virtual environment
> conda activate ibkr
Install required packages
After adding a conda-forge channel to install packages, install required packages.
> conda config --append channels conda-forge
> conda install ib-insync
Let’s write your first Python code
Launch Microsoft VS Code
Create a new folder that you want to work on and open it in VS Code.
Use the virtual env named “ibkr”
Once VS Code has started, check the status in the bottom right-hand corner. Click the red area below.
Click ‘Python ….. (“ibkr”)’
Sample Python code
The simple code below takes data for EUR/JPY.
Save this code as ‘test.py’, and execute (Shortcut: F5) to test it.
from ib_insync import *
# util.startLoop() # uncomment this line when in a notebook
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)
contract = Forex('EURUSD')
bars = ib.reqHistoricalData(
contract, endDateTime='', durationStr='30 D',
barSizeSetting='1 hour', whatToShow='MIDPOINT', useRTH=True)
# convert to pandas dataframe:
df = util.df(bars)
print(df)
Congratulations!
Comments