Interactive Brokers (IBKR) provides a Python API called **ib_insync** to interact with the TWS (Trader Workstation) or IB Gateway. This API allows Python applications to place trades, retrieve market data, manage accounts, and more.
Here’s a guide to getting started with the **IBKR API using Python**:
### 1. **Setting Up Your IBKR Account and Enable API Access**
- **Open an IBKR account** if you don’t have one.
- **Enable API access** in the TWS or IB Gateway under
Configuration > API > Settings
, and allow connections from localhost.
- **Download and install IB Gateway or Trader Workstation (TWS)** as the API requires one of these to be running.
### 2. **Installing ib_insync**
- **ib_insync** is a popular Python wrapper for the IB API, making it simpler to work with than the official
ibapi
library.
- Install
ib_insync
:
bash
pip install ib_insync
### 3. **Connecting to IBKR with ib_insync**
- Run TWS or IB Gateway and note the **port** (usually 7497 for TWS paper trading or 4001 for IB Gateway paper trading).
- Connect to the IB API by creating an instance of
IB()
.
#### Example: Establishing a Connection
python
from ib_insync import IB
# Initialize and connect to the IBKR API
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1) # clientId should be unique for each connection
# Check connection
if ib.isConnected():
print("Connected to IBKR API")
else:
print("Connection failed")