In this tutorial, I will explain how to retrieve all open stock option positions in your IBKR account.
Setting up IB Gateway or TWS
The easiest way to use the IBKR API with Python is through the ib_insync [↗] library. You can do so by running the following command to install it:
$ pip install ib_insync
You need to also install IB Gateway [↗] or TWS [↗]. IB Gateway acts as an intermediary service for serving the APIs, TWS although a trading workstation also provides the same functionality.
You might want to follow my IBKR Windows WSL setup tutorial [↗] instead if thats your development environment.
Once installed, follow the steps below to configure the API gateway.
Whitelist Your WSL IP in IB Gateway/TWS
Open TWS or IB Gateway.
Go to Edit → Global Configuration → API → Settings.
Ensure connections from localhost is enabled else set your desired port.
Add your IP address to the list of Trusted IPs
Also note down the socket port value, you will need it in the next step.
Click Apply & OK.
Get a List of Your Stock Options
With TWS (Trader Workstation) or IB Gateway running and API access enabled, you can get your stock options using the script below.
test.py
01: from ib_insync import *
02:
03: ib = IB()
04: ib.connect('127.0.0.1', 4001)
05:
06: positions = ib.positions()
07: for position in positions:
08: if position.contract.secType == 'OPT':
09: print(f"Symbol: {position.contract.symbol}, Strike: {position.contract.strike}, Type: {position.contract.right}, Quantity: {position.position}")
The above script will display:
- The stock symbol
- The strike price
- Whether it is a call or put option
- The quantity of options held
Aaannnd its a wrap :)
Here is another article you might like 😊 How To Access A Windows Localhost App From WSL