Bottom line: Interactive Brokers’ Client Portal Web API can drive a rebalancing script end to end, but the work lives in three places most people underestimate: the session lifecycle, the order-preview handshake, and the gap between what your target weights say and what the account actually holds.

The mechanics are not complicated once you have a working session. You authenticate, pull a snapshot of positions and cash, compute the drift against your target allocation, translate that drift into share quantities, then send the orders through the preview endpoint before you place them. What causes trouble is that the Client Portal API is a browser-backed gateway rather than a clean REST service, so authentication is stateful, tokens expire quietly, and the preview step is mandatory in practice because it is where IBKR surfaces margin, contract, and sizing rejections. Below is the loop I actually run, with the parts that bit me.

Why drive the API instead of the UI

If you rebalance a handful of ETFs a few times a year, the web UI is fine. Automation earns its keep when the portfolio has enough positions that manual entry becomes error-prone, or when you want a repeatable, logged process you can audit later. Three things make the Client Portal Web API a reasonable tool for this:

  • It talks to the same gateway your logged-in browser session uses, so you get account, position, and order endpoints that reflect your real permissions.
  • It exposes an order preview that returns margin impact and warnings before anything is transmitted.
  • It works across account types, including cash and margin accounts, and supports the standard US equity and ETF order types you would use for a rebalance.

The trade-off is that it is not a fire-and-forget HTTP API. The gateway must be running and authenticated, and your script inherits all the fragility of a session-based login. Plan for that up front.

The authentication model, and where the token fits

There are two layers to keep straight. The first is the Client Portal Gateway itself: a small Java process you run locally (or on a host inside your network) that proxies requests to IBKR. The second is authentication against IBKR, which yields a session cookie the gateway uses.

For third-party integrations, IBKR documents an OAuth 1.0a flow that starts with a temporary request token. The /request_token endpoint accepts an OAuth Authorization header and returns an oauth_token — a 20-character hex value — that you exchange to complete the authorization workflow. That path is aimed at applications acting on behalf of users, not at a personal script. For a single-operator rebalance script, the practical route is a direct login to the gateway and a tickle call to keep the session alive.

Two failure modes dominate. A 401 Unauthorized means your session is gone and you need to re-authenticate. A 503 Service Unavailable means the gateway is not up or is mid-restart. Treat both as normal operational events, not bugs, and build your script to detect them and stop cleanly rather than hammering the endpoint.

A minimal session check with curl looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
# Gateway assumed running on localhost:5000
# 1. Confirm the gateway is alive and authenticated
curl -s -k https://localhost:5000/v1/api/iserver/auth/status

# Expected when healthy:
# {"authenticated":true,"competing":false,"connected":true,"message":""}

# 2. Keep the session warm (run every few minutes from cron or a loop)
curl -s -k -X POST https://localhost:5000/v1/api/tickle

# 3. List accounts so you know the accountId your orders will target
curl -s -k https://localhost:5000/v1/api/portfolio/accounts

The -k flag skips certificate verification against the gateway’s self-signed cert. That is acceptable only on loopback or a trusted private network. Do not run this over an untrusted link with -k.

If authenticated is false, you need to complete login in a browser pointed at the gateway’s login URL. There is no clean headless path for a personal account, so most homelab setups run the gateway on a small always-on host and re-auth manually when the session lapses — typically daily or on restart, depending on your session settings.

Computing drift from target weights

The gateway gives you a portfolio snapshot; your target allocation lives in a config file. The job is to reconcile the two.

A position snapshot endpoint returns each holding with its position size, market price, and market value, plus the account’s cash. The calculation is straightforward:

  1. Total portfolio value = sum of position market values + cash.
  2. Target value per holding = target weight × total portfolio value.
  3. Drift per holding = target value − current market value.
  4. Convert drift to shares: round(drift ÷ current price), respecting lot sizes and avoiding dust trades below a threshold.

Two practical decisions matter more than the arithmetic. First, cash is a position. If your targets sum to 100% and you hold cash, either your targets are wrong or your cash is intentional; decide which before you compute. Second, set a rebalance band (a minimum absolute drift, say a few percentage points or a dollar floor) so you are not trading every day on rounding noise. The band is what turns a naive diff into a sane order set.

A small Python sketch of the core loop, using requests:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import requests

BASE = "https://localhost:5000/v1/api"
SESSION = requests.Session()
SESSION.verify = False # loopback only

def snapshot(account_id):
pos = SESSION.get(f"{BASE}/portfolio/{account_id}/positions").json()
summary = SESSION.get(f"{BASE}/portfolio/{account_id}/summary").json()
cash = next(float(x["amount"]) for x in summary
if x["tag"] == "totalcashvalue")
holdings = {p["contractDesc"]: {
"value": float(p["mktValue"]),
"price": float(p["mktPrice"]),
"position": float(p["position"]),
} for p in pos}
total = cash + sum(h["value"] for h in holdings.values())
return total, cash, holdings

def drift_orders(total, holdings, targets, band_pct=1.0, min_trade=100.0):
orders = []
for symbol, weight in targets.items():
target_value = total * weight / 100.0
current_value = holdings.get(symbol, {}).get("value", 0.0)
delta = target_value - current_value
if abs(delta) < max(total * band_pct / 100.0, min_trade):
continue
price = holdings[symbol]["price"]
qty = int(delta // price) if delta > 0 else -int((-delta) // price)
if qty != 0:
orders.append({"symbol": symbol, "qty": qty,
"side": "BUY" if qty > 0 else "SELL"})
return orders

This ignores fractional shares, taxes, and wash-sale windows. All three matter; handle them before you send anything. Fractional trading is available on many IBKR accounts but not universally, and order sizing for fractions differs from whole-share orders. Wash-sale rules apply to losses in taxable accounts and are not something the API enforces for you — the preview will not warn you about them.

The order-preview step that trips people up

Every order should pass through the preview endpoint before placement. The preview validates contract resolution, order sizing, buying power, and margin impact, and returns a set of warnings. Skipping it means you discover problems as rejected or partially filled live orders.

The endpoint takes an order specification and returns either a preview with an estimated cost and margin change, or an error describing exactly why the order cannot proceed. This is where you catch:

  • Insufficient buying power in a cash account before settlement.
  • Contract ambiguities — a symbol that resolves to multiple instruments, usually because the exchange or primary listing is unspecified.
  • Orders that exceed position or margin limits for your account.

The flow is: submit the order spec to the preview endpoint, inspect the response for errors and warnings, then submit the same spec to the placement endpoint with a confirmation. The order spec format is shared between preview and placement, so build it once.

1
2
3
4
5
6
7
8
9
10
11
12
# Preview a single order (accountId and conid from your snapshot)
curl -s -k -X POST https://localhost:5000/v1/api/iserver/account/{accountId}/orders/whatif \
-H "Content-Type: application/json" \
-d '{
"orders": [{
"conid": 12345678,
"orderType": "MKT",
"side": "BUY",
"quantity": 10,
"tif": "DAY"
}]
}'

Read the response carefully. A 200 with an error field is a rejection dressed as success. Check for amount and margin fields to see the estimated impact, and treat any warning text as something to log even when the preview succeeds.

A comparison worth knowing before you script

The Client Portal Web API is one of several ways to reach IBKR programmatically. The differences matter for a rebalancing tool.

Approach Session model Order preview Best fit
Client Portal Web API (gateway) Browser-backed, stateful, needs tickle Yes, /orders/whatif Scripts and small tools against your own account
OAuth 1.0a third-party flow Token exchange via /request_token Via the same order endpoints Applications acting for other users
Manual TWS / web UI Your interactive login Interactive confirmations Occasional rebalances

The OAuth path uses a temporary oauth_token (a 20-character hex value) from /request_token to begin authorization. For a personal script, the gateway login path is simpler; for anything multi-user, the OAuth flow is the one IBKR intends you to use. Either way, the preview and placement endpoints behave the same.

Pitfalls and how to diagnose them

Session silently expires. You get 401 mid-run. Check iserver/auth/status; if authenticated is false, re-login through the gateway. Schedule a tickle every few minutes and treat the first 401 as a hard stop rather than retrying in a tight loop.

Gateway not running. 503 from every endpoint. Confirm the process is up and the port matches. A restart wipes your session, so re-auth after any restart.

Contract ambiguity. Preview rejects with an error about the instrument. Add the exchange or primary exchange to the order spec. Resolving symbols to conid once and caching the mapping avoids repeat failures.

Wrong account targeted. Positions come back for one account but orders go to another. Always pull the accountId from /portfolio/accounts at runtime rather than hardcoding it; multi-account logins are common.

Cash vs margin mismatch. A buy that looks fine against total value fails on buying power because the cash is unsettled or held as margin collateral. The preview surfaces this; the snapshot does not.

Rounding dust. Many small orders that individually clear your band but collectively churn the account. Aggregate orders per symbol before preview and drop anything below a minimum notional.

Fractional vs whole shares. Sizing math that assumes whole shares silently under-trades fractional-capable accounts, or over-trades accounts that do not support fractions. Check account capability before sizing.

Wash-sale blindness. The API will happily let you realize a loss and rebuy within the window. Track your own tax lots or keep a rebalance calendar that respects the window.

Preview treated as placement. A successful preview sends nothing. Log the preview response and confirm the placement call returned an order ID before assuming the trade exists.

FAQ

Does the Client Portal Web API require the gateway to be running?

Yes. The API is a proxy in front of IBKR’s services, and your script talks to the gateway, not directly to IBKR. If the gateway process is down or unauthenticated, every call returns an error until you restore it.

What is the difference between the request token flow and logging into the gateway?

The /request_token endpoint begins an OAuth 1.0a workflow for third-party applications acting on behalf of users, returning a temporary 20-character hex oauth_token. Logging into the gateway is a direct session for your own account. For a personal rebalance script, the gateway login is simpler; for multi-user software, use OAuth.

Why did my order preview return 200 but no order was placed?

Preview and placement are separate endpoints. A 200 from the preview means the order passed validation; it does not transmit anything. You must submit the same order specification to the placement endpoint and confirm you received an order identifier back.

How often do I need to refresh the session?

Sessions expire on their own schedule and on gateway restart. Rather than guessing, poll iserver/auth/status and send a tickle periodically to keep the session warm. Treat any 401 as a signal to re-authenticate before continuing.

Can I rebalance a cash account the same way as a margin account?

The endpoints are the same, but buying power behaves differently. In a cash account, unsettled proceeds may not be available for new purchases, and the preview will reject orders that exceed available cash. Always run the preview and read the buying-power fields before placing.

Does the API account for taxes or wash-sale rules when I rebalance?

No. The API validates orders against contract, sizing, and margin constraints. It does not model your tax situation or enforce wash-sale windows. Those are your responsibility, either in your script’s logic or in how often you rebalance in taxable accounts.