| name | trader-cli |
| description | Use when running, testing, or automating the trader CLI tool — invoking commands, parsing output, placing orders, fetching quotes, or reading account/position data. |
Trader CLI
Overview
Agent-first trading CLI. All commands output JSON to stdout; errors output {"error": "...", "code": "..."} and exit 1. Requires IBKR Client Portal Gateway running on port 5001.
Invocation
uv run trader [--broker ibkr-rest|ibkr-tws] [--output json|table] COMMAND [ARGS]
Global options (before the command):
--broker — default ibkr-rest (Client Portal Gateway). Use ibkr-tws for local TWS.
--output — default json. Use for agent consumption.
Commands Reference
account
trader account summary
trader account balance
trader account margin
quotes
trader quotes get AAPL MSFT TSLA
trader quotes chain AAPL --expiry 2026-04-17 [--strike 200] [--right call|put]
positions
trader positions list
trader positions pnl
trader positions close AAPL
trader positions close AAPL --contract-type OPT --dry-run
trader positions close AAPL --contract-type OPT
trader positions close AAPL --contract-type OPT --strike 200 --expiry 2026-05-15
Option close error handling:
cap-price rejection → retry with orders sell ... --type limit --price <bid>
size=0 in positions list → ghost position that already expired; skip
conid mismatch → retry with explicit --contract-type option --right CALL/PUT --strike X --expiry YYYY-MM-DD
Order failure escalation (max 3 attempts, then escalate):
positions close TICKER --contract-type OPT
- If rejected:
orders sell TICKER QTY --type limit --price <bid> --contract-type option ...
- If still fails: log ORDER_FAILED event, send Telegram alert — do NOT retry further
Exit signal hierarchy (catalyst positions):
0. Native IBKR GTC stop order — placed automatically by refresh-context.py within one cycle of entry. Survives gateway/server downtime. Do NOT manually place/cancel stops on catalyst positions.
context.json catalyst_exit_signals trailing state — AUTHORITATIVE for trail stops (software layer)
trader catalyst execute --exits — AUTHORITATIVE for DTE backstop
exit_evaluations in context.json — advisory only (5-factor review)
When signals conflict: the more conservative (exit) signal wins. Native stop fires before software layer if server is down — refresh-context.py reconciles orphan on next cycle.
orders
trader orders buy AAPL 10
trader orders buy AAPL 10 --type limit --price 195
trader orders sell AAPL 10 --type market
trader orders sell AAPL 10 --type market --dry-run
trader orders bracket AAPL 10 --entry 195 --take-profit 210 --stop-loss 185
trader orders buy AAPL 10 --type bracket --price 195 --take-profit 210 --stop-loss 185
trader orders stop AAPL --price 185
trader orders stop LWLG --price 1.13 --contract-type option --right call --strike 15 --expiry 2026-05-16
trader orders take-profit AAPL --price 210
trader orders trailing-stop AAPL --trail-percent 2.5
trader orders list [--status open|filled|cancelled|all]
trader orders modify ORDER_ID [--price 198] [--qty 5]
trader orders cancel ORDER_ID
trader orders buy AAPL 1 --type limit --price 1.35 --contract-type option --expiry 2026-04-17 --strike 200 --right call
trader orders sell AAPL 1 --contract-type option --expiry 2026-04-17 --strike 200 --right call
news
trader news latest --tickers AAPL,MSFT [--limit 10]
trader news sentiment AAPL [--lookback 24h|48h|7d]
strategies
trader strategies run AAPL --strategy rsi [--interval 1d] [--lookback 90d]
trader strategies signals --tickers AAPL,MSFT --strategy rsi [--with-news]
trader strategies backtest AAPL --strategy rsi [--from 2025-01-01]
trader strategies optimize AAPL --strategy rsi [--metric sharpe|returns|win_rate]
trader strategies consensus-backtest AAPL --from 2025-10-15 [--regime bear|bull|caution]
catalyst
trader catalyst scan --type earnings --calendar [--lookahead 14] [--limit 30]
trader catalyst scan --type fda --calendar [--lookahead 60]
trader catalyst scan --type fomc --calendar [--lookahead 30]
trader catalyst scan --type opec --calendar [--lookahead 30]
trader catalyst scan --type macro --calendar [--lookahead 14]
trader catalyst scan --type earnings --watchlist all
trader catalyst proposals --type earnings [--max-iv-ratio 1.05] [--min-dte 5] [--max-dte 14]
trader catalyst proposals --type fda --max-iv-ratio 1.5
trader catalyst proposals --type fomc [--max-iv-ratio 1.05] [--regime bull|caution|bear]
trader catalyst proposals --type opec [--max-iv-ratio 1.05] [--regime bull|caution|bear]
trader catalyst proposals --type macro [--max-iv-ratio 1.05] [--regime bull|caution|bear]
trader catalyst scan --type earnings --calendar --use-ibkr
Catalyst types:
earnings — NASDAQ calendar, 280+ tickers/week. Tickers: individual stocks.
fda — RTTNews + BioPharmCatalyst PDUFA. Tickers: biotech names.
fomc — Fed rate decisions, 8/year. Tickers: SPY, QQQ, TLT, XLF, XLU, IWM.
opec — OPEC+ meetings. Tickers: XOM, CVX, SLB, OXY, HAL, COP, DVN, VLO, MPC.
macro — CPI, NFP releases, ~24/year. Tickers: SPY, QQQ, TLT, XLF, XLE, IWM.
Liquidity floor (from profile.json): min OI >= 500, min daily volume >= 200. Illiquid chains filtered at proposal stage.
Catalyst caching (automatic — no action needed):
- Event calendar cached 6h →
.trader/cache/catalysts/<type>-events.json
- IV snapshots stored daily →
.trader/history/iv-snapshots.jsonl (skip re-fetch if today's entry exists)
- Scan file TTL: 4h normally, 30min if any event <3 DTE
IV/RV fields are decimal ratios: 0.68 = 68%. iv_rv_ratio < 1.0 = IV cheap vs realised vol = good entry signal.
Quick Reference
| Goal | Command |
|---|
| Check buying power | trader account balance |
| Live price | trader quotes get AAPL |
| Open positions | trader positions list |
| Total P&L | trader positions pnl |
| Close option position | trader positions close TICKER --contract-type OPT |
| Preview close (dry-run) | trader positions close TICKER --contract-type OPT --dry-run |
| Buy market | trader orders buy AAPL 10 |
| Buy limit | trader orders buy AAPL 10 --type limit --price 195 |
| Bracket trade | trader orders bracket AAPL 10 --entry 195 --take-profit 210 --stop-loss 185 |
| Protect position | trader orders stop AAPL --price 185 |
| Latest news | trader news latest --tickers AAPL |
| Signal check | trader strategies signals --tickers AAPL --strategy rsi |
| Scan earnings catalysts | trader catalyst scan --type earnings --calendar --limit 20 |
| Scan FDA catalysts | trader catalyst scan --type fda --calendar |
| Scan FOMC catalysts | trader catalyst scan --type fomc --calendar |
| Scan OPEC catalysts | trader catalyst scan --type opec --calendar |
| Scan macro (CPI/NFP) | trader catalyst scan --type macro --calendar |
| Catalyst proposals | trader catalyst proposals --type earnings |
Gateway Session Management
The IBKR Client Portal Gateway runs locally via clientportal.gw/bin/run.sh (port 5001). Session re-authentication is handled by scripts/ibkr-reauth.py using Playwright + Telegram MFA.
Architecture
[tmux: trader] → clientportal.gw/bin/run.sh
↓
Java gateway on https://localhost:5001
Re-auth: scripts/ibkr-reauth.py (Playwright + Telegram MFA)
Session Health Check
uv run trader account summary
python scripts/ibkr-healthcheck.py
Key .env Variables
| Variable | Value | Purpose |
|---|
IB_ACCOUNT | IBKR account ID | Account for CLI commands |
IB_PORT | 5001 | Gateway HTTPS port |
Logs
tail -f clientportal.gw/root/logs/gateway.log
Troubleshooting
| Symptom | Cause | Fix |
|---|
ConnectionError from CLI | Gateway not running | Restart via clientportal.gw/bin/run.sh in tmux |
| 401 from gateway | Session expired | Run python scripts/ibkr-reauth.py |
| Persistent 401 loop | Gateway stuck | Use the ibkr-gateway-recovery agent |
Stopping the Gateway
pkill -f clientportal.gw
Error Handling
All errors produce JSON on stdout and exit code 1:
{"error": "Connection refused", "code": "ConnectionError"}
Parse with jq .error or check exit code before acting on output.
Common Mistakes
- Wrong port — Gateway runs on HTTPS
5001, not TWS 7497. Set IB_PORT=5001 in .env.
- Auth not done — Browser-auth the Client Portal Gateway before running any command.
- Bracket via
buy — Use --type bracket with --price, --take-profit, --stop-loss. Or use the dedicated bracket subcommand.
- Trailing stop qty —
trailing-stop reads qty from the open position automatically; no --qty needed.
- News tickers format —
--tickers accepts comma-separated (AAPL,MSFT) or space-separated (quote the arg: 'AAPL MSFT').
- Gateway stuck in 401 loop — Use the
ibkr-gateway-recovery agent to restart and re-authenticate.
- Stop orders show
price: null — Display bug in adapter; price is set correctly at placement, confirm in .trader/events.jsonl.
- Stop without open position —
trader orders stop TICKER --price X fails if position not yet filled. Use --qty N to pre-place: trader orders stop TICKER --price X --qty N.