# Interactive Brokers API in Python: paper to first call

Independent and unofficial. Not affiliated with or endorsed by any broker or platform named here. Educational only: nothing here is advice, and nothing here recommends a broker or a trade.

This is the markdown version of https://openbrokerapi.com/brokers/ibkr/quickstart, written from the same records as that page.

Risk warning: CFDs and spread bets are complex instruments and come with a high risk of losing money rapidly due to leverage. You can lose money on these products, and each provider publishes its own loss figure under FCA rules. You should consider whether you understand how they work and whether you can afford to take the high risk of losing your money. Automated and API trading can amplify losses through bugs, connectivity failures and runaway orders.

Connect to an IBKR paper account with ib_async or the Client Portal Web API: ports, API settings, account summary and free delayed data. Every step sourced.

- Checked: 2026-09-25

Unverified: the code on this page was written from the documentation and has not yet been run on a demo account.

Demo accounts only. Credentials are read from environment variables on your own machine. No field on this site asks for a key, a username or a password.

## Steps

### 1. Log in to paper, not live

Start TWS or IB Gateway and log in with your paper trading username. It is separate from your live one and sits in Client Portal settings. IBKR's older setup guide gives the default TWS socket ports as 7497 for a paper session and 7496 for a live one, and says they can be changed. This site also holds 4002 paper and 4001 live for IB Gateway: those two were not found on the IBKR pages read on 12 October 2026, so check the socket port shown in your own API settings. Get the port wrong and you are either not connected or connected to real money.

Status: verified. Source: [interactivebrokers.github.io](https://interactivebrokers.github.io/tws-api/initial_setup.html), checked 2026-09-25.

### 2. Switch the API on

In TWS open Global Configuration, then API, then Settings. Tick Enable ActiveX and Socket Clients and check the socket port. Read-Only API hides order information from the API. Leave it on for this quickstart and connect with readonly=True; IBKR's guide says to disable it for API use, so untick it when you are ready to send orders.

Status: verified. Source: [interactivebrokers.com](https://www.interactivebrokers.com/docs/tws-api/doc/tws-settings/tws-configuration-for-api-use/introduction), checked 2026-09-25.

### 3. Install ib_async

ib_async is the community successor to ib_insync and needs Python 3.10 or later. IBKR's own ibapi client needs 3.11. For the JavaScript and curl tabs, run the Java based Client Portal Gateway instead and log in at https://localhost:5000.

Python:

```python
# Python 3.10 or later
pip install ib_async
```

JavaScript:

```javascript
// Nothing to install: Node 18 or later has fetch built in.
// Start the Client Portal Gateway (needs a Java runtime), then log in at https://localhost:5000
//   macOS or Linux: bin/run.sh root/conf.yaml
//   Windows:        bin\run.bat root\conf.yaml
```

curl:

```bash
# Client Portal Gateway (needs a Java runtime), from its folder:
bin/run.sh root/conf.yaml
# Windows: bin\run.bat root\conf.yaml
# Then open https://localhost:5000 in a browser and log in with your paper username.
```

Status: verified. Source: [pypi.org](https://pypi.org/project/ib_async/), checked 2026-09-25.

### 4. Connect and check the clock

Connect to 127.0.0.1 on the paper port with a clientId unique to this script. reqCurrentTime proves the socket works. On the Web API, POST /iserver/auth/status should come back with authenticated true. It is a POST, not a GET.

Python:

```python
from ib_async import IB

ib = IB()
# TWS paper 7497, IB Gateway paper 4002
ib.connect('127.0.0.1', 7497, clientId=1, readonly=True)
print("Server time:", ib.reqCurrentTime())
print("Accounts:", ib.managedAccounts())
ib.disconnect()
```

JavaScript:

```javascript
// This tab uses the Client Portal Web API with fetch, not the TWS socket API.
// The gateway runs on your own machine with a self-signed certificate.
// For localhost only, run with: NODE_TLS_REJECT_UNAUTHORIZED=0 node step.mjs
const BASE_URL = "https://localhost:5000/v1/api";

const res = await fetch(`${BASE_URL}/iserver/auth/status`, { method: "POST" });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const status = await res.json();
console.log("authenticated:", status.authenticated, "connected:", status.connected);
```

curl:

```bash
# -k accepts the gateway's self-signed certificate. Use it against localhost only.
curl -k -s -X POST "https://localhost:5000/v1/api/iserver/auth/status"
```

Status: verified. Source: [ibkrcampus.com](https://ibkrcampus.com/campus/trading-lessons/launching-and-authenticating-the-gateway/), checked 2026-09-25.

### 5. First real call: your account

accountSummary returns balances as AccountValue rows. If you see NetLiquidation, you are in. On the Web API, call GET /portfolio/accounts first: IBKR requires it before any other /portfolio endpoint.

Python:

```python
from ib_async import IB

ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1, readonly=True)
for v in ib.accountSummary():
    if v.tag in ('NetLiquidation', 'AvailableFunds'):
        print(v.account, v.tag, v.value, v.currency)
ib.disconnect()
```

JavaScript:

```javascript
// This tab uses the Client Portal Web API with fetch, not the TWS socket API.
// The gateway runs on your own machine with a self-signed certificate.
// For localhost only, run with: NODE_TLS_REJECT_UNAUTHORIZED=0 node step.mjs
const BASE_URL = "https://localhost:5000/v1/api";

const res = await fetch(`${BASE_URL}/portfolio/accounts`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const accounts = await res.json();
console.log(accounts.map(a => a.id));
```

curl:

```bash
# Set IBKR_ACCOUNT_ID as an environment variable first (an id from the call above).
# Must be called before other /portfolio endpoints
curl -k -s "https://localhost:5000/v1/api/portfolio/accounts"

# Then, for example:
curl -k -s "https://localhost:5000/v1/api/portfolio/$IBKR_ACCOUNT_ID/summary"
```

Status: verified. Source: [interactivebrokers.com](https://www.interactivebrokers.com/campus/ibkr-api-page/webapi-doc/), checked 2026-09-25.

### 6. Prices without paying for data

Call reqMarketDataType(3) to accept delayed data when you have no live subscription. Forex needs no extra market data subscription, so EURUSD midpoint bars are the safest first request. Live data needs 500 USD in the account, the subscription cost on top and the Market Data API Acknowledgement.

Python:

```python
from ib_async import IB, Forex

ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1, readonly=True)
ib.reqMarketDataType(3)  # 1 live, 2 frozen, 3 delayed, 4 delayed frozen

contract = Forex('EURUSD')
ib.qualifyContracts(contract)  # fills in conId and exchange; skip it and the request can come back empty

bars = ib.reqHistoricalData(
    contract,
    endDateTime='',
    durationStr='1 D',
    barSizeSetting='1 hour',
    whatToShow='MIDPOINT',
    useRTH=False,  # forex has no regular trading hours, so useRTH=True often returns an empty list
)
if not bars:
    raise SystemExit('No bars returned. Check the symbol, the duration and that the gateway is connected.')
for b in bars[-3:]:
    print(b.date, b.open, b.high, b.low, b.close)
ib.disconnect()
```

JavaScript:

```javascript
// This tab uses the Client Portal Web API with fetch, not the TWS socket API.
// The gateway runs on your own machine with a self-signed certificate.
// For localhost only, run with: NODE_TLS_REJECT_UNAUTHORIZED=0 node step.mjs
// Snapshot pre-flight and field 31 are not confirmed on a page we opened.
// The first call starts the stream; repeat it to get values.
const BASE_URL = "https://localhost:5000/v1/api";
const CONID = process.env.IBKR_CONID; // the contract id, set as an environment variable
const url = `${BASE_URL}/iserver/marketdata/snapshot?conids=${CONID}&fields=31`;

await fetch(url); // pre-flight
await new Promise(r => setTimeout(r, 1000));
const res = await fetch(url);
console.log(await res.json());
```

curl:

```bash
# Snapshot pre-flight and field 31 (last price) are not confirmed on a page we opened.
# Set IBKR_CONID (the contract id) as an environment variable, call once, wait, call again.
curl -k -s "https://localhost:5000/v1/api/iserver/marketdata/snapshot?conids=$IBKR_CONID&fields=31"
sleep 1
curl -k -s "https://localhost:5000/v1/api/iserver/marketdata/snapshot?conids=$IBKR_CONID&fields=31"
```

Status: verified. Source: [interactivebrokers.com](https://www.interactivebrokers.com/campus/ibkr-api-page/market-data-subscriptions/), checked 2026-09-25.

## Sources

- Status: verified. Source: [IBKR TWS API documentation, TWS configuration for API use](https://www.interactivebrokers.com/docs/tws-api/doc/tws-settings/tws-configuration-for-api-use/introduction), checked 2026-10-12.
- Status: verified. Source: [IBKR Campus: market data subscriptions](https://www.interactivebrokers.com/campus/ibkr-api-page/market-data-subscriptions/), checked 2026-09-25.
- Status: verified. Source: [IBKR Web API documentation, using a paper account](https://www.interactivebrokers.com/docs/web-api/authentication/paper), checked 2026-10-12.
- Status: verified. Source: [IBKR Campus: Web API documentation](https://www.interactivebrokers.com/campus/ibkr-api-page/webapi-doc/), checked 2026-10-12.
- Status: verified. Source: [IBKR Campus: launching and authenticating the gateway](https://ibkrcampus.com/campus/trading-lessons/launching-and-authenticating-the-gateway/), checked 2026-09-25.
- Status: verified. Source: [ib_async documentation](https://ib-api-reloaded.github.io/ib_async/), checked 2026-09-25.
- Status: verified. Source: [PyPI: ib_async](https://pypi.org/project/ib_async/), checked 2026-09-25.
- Status: verified. Source: [ib_async source: ib.py](https://raw.githubusercontent.com/ib-api-reloaded/ib_async/main/ib_async/ib.py), checked 2026-09-25.
- Status: verified. Source: [TWS API guide: initial setup (legacy docs)](https://interactivebrokers.github.io/tws-api/initial_setup.html), checked 2026-10-12.

## Interactive Brokers limits to pace against

- Global requests a second (Web API): 10 requests per second
  - Scope: Per authenticated username, that is per Web API session
  - Status: verified. Source: [ibkrcampus.com](https://www.ibkrcampus.com/campus/ibkr-api-page/webapi-doc/), checked 2026-10-12.
  - Corroborated by [interactivebrokers.com/docs/web-api/trading/usage-and-availability/pacing-limitations](https://www.interactivebrokers.com/docs/web-api/trading/usage-and-availability/pacing-limitations)
  - Note: Client Portal Web API. Some endpoints carry their own lower limit, held in separate records. A breach returns HTTP 429, and both IBKR pages read on 12 Oct 2026 give a penalty box of 10 minutes for a violating IP address.
- Historical market data requests: Either 10 req/s or 50 req/minute, as the page words it
  - Scope: GET /iserver/marketdata/history only
  - Status: verified. Source: [interactivebrokers.com](https://www.interactivebrokers.com/docs/web-api/trading/usage-and-availability/pacing-limitations), checked 2026-10-12.
  - Corroborated by [ibkrcampus.com/campus/ibkr-api-page/webapi-doc/](https://www.ibkrcampus.com/campus/ibkr-api-page/webapi-doc/)
  - Note: The page gives two figures joined by or and does not say which applies when, so no single number is recorded. The IBKR Campus page also lists 5 concurrent requests for this endpoint.
- Market data snapshot requests a second: 10 requests per second
  - Scope: GET /iserver/marketdata/snapshot only
  - Status: verified. Source: [interactivebrokers.com](https://www.interactivebrokers.com/docs/web-api/trading/usage-and-availability/pacing-limitations), checked 2026-10-12.
  - Corroborated by [ibkrcampus.com/campus/ibkr-api-page/webapi-doc/](https://www.ibkrcampus.com/campus/ibkr-api-page/webapi-doc/)
- Order and trade list requests: 1 req/5 s
  - Scope: GET /iserver/orders and GET /iserver/trades, each counted on its own
  - Status: verified. Source: [interactivebrokers.com](https://www.interactivebrokers.com/docs/web-api/trading/usage-and-availability/pacing-limitations), checked 2026-10-12.
  - Corroborated by [ibkrcampus.com/campus/ibkr-api-page/webapi-doc/](https://www.ibkrcampus.com/campus/ibkr-api-page/webapi-doc/)
  - Note: The same figure applies to /iserver/account/pnl/partitioned, /portfolio/accounts and /portfolio/subaccounts. The window is 5 seconds, which a single unit cannot state, so the figure stays as wording.
- Session validation requests a minute: 1 requests per minute
  - Scope: GET /sso/validate only
  - Status: verified. Source: [interactivebrokers.com](https://www.interactivebrokers.com/docs/web-api/trading/usage-and-availability/pacing-limitations), checked 2026-10-12.
  - Corroborated by [ibkrcampus.com/campus/ibkr-api-page/webapi-doc/](https://www.ibkrcampus.com/campus/ibkr-api-page/webapi-doc/)
- Session keep alive requests a second: 1 requests per second
  - Scope: GET /tickle only
  - Status: verified. Source: [interactivebrokers.com](https://www.interactivebrokers.com/docs/web-api/trading/usage-and-availability/pacing-limitations), checked 2026-10-12.
  - Corroborated by [ibkrcampus.com/campus/ibkr-api-page/webapi-doc/](https://www.ibkrcampus.com/campus/ibkr-api-page/webapi-doc/)

## Next on the Interactive Brokers API

- [Interactive Brokers API error codes](https://openbrokerapi.com/errors/ibkr): 511 decoded, each with what it means, and the fix where the source gives one.
- [Interactive Brokers API endpoints](https://openbrokerapi.com/brokers/ibkr/endpoints): 23 documented, each with its method, path, parameters and source.
- [Interactive Brokers API page](https://openbrokerapi.com/brokers/ibkr): The full record: access, authentication, limits and the source for each.
- [Get your Interactive Brokers trade history into a spreadsheet](https://openbrokerapi.com/guides/ibkr-trade-history): Guide
- [IBKR API without TWS: headless IB Gateway options](https://openbrokerapi.com/guides/ibkr-headless-gateway): Guide
- [The three Interactive Brokers REST front doors compared](https://openbrokerapi.com/guides/ibkr-rest-front-doors): Guide
- [Interactive Brokers MCP servers, compared](https://openbrokerapi.com/guides/interactive-brokers-mcp-servers): Guide

## Licence and how to cite

The records behind this page are all rights reserved. This file is the page itself, at its own address, in another format. It is not part of the CC BY 4.0 downloads listed at https://openbrokerapi.com/data. Quote from it with a link to the page.

Cite as: Interactive Brokers API in Python: paper to first call. Broker API Hub, https://openbrokerapi.com/brokers/ibkr/quickstart, newest check 2026-09-25.

Where you rely on a single figure, cite the source and the checked date printed beside it as well. Where this page and a broker's own documentation differ, the documentation wins.
