ib-trades-history

$npx mdskill add staskh/trading_skills/ib-trades-history

Fetch trade executions from Interactive Brokers by account, date, or symbol.

  • Retrieves recent or full trade history for user review or analysis.
  • Requires TWS or IB Gateway running locally with API enabled.
  • Uses live API for ~7 days or FlexReport for full history.
  • Returns trade data as structured output for the agent or user.

SKILL.md

.github/skills/ib-trades-historyView on GitHub ↗
---
name: ib-trades-history
description: Fetch trade executions from Interactive Brokers filtered by account, date range, or symbol. Supports live API (~7 days history) and FlexReport (full history). Use when user asks about their trades, executions, or transaction history. Requires TWS or IB Gateway running locally.
dependencies: ["trading-skills"]
---

# IB Trades History

Fetch trade executions from Interactive Brokers.

## IB Connection

TWS or IB Gateway must be running locally with API enabled:
- **Paper trading** — port 7497
- **Live trading** — port 7496
- **`IB_PORT` env var** — default port when `--port` is omitted (e.g. `IB_PORT=4001` for a Gateway container). Precedence: `--port` flag > `IB_PORT` > built-in default. Set it in the shell or a `.env` file.

**Port fallback:** If the configured port fails, automatically retry on the other port.
If the retry succeeds, save to memory which account type worked (live/paper) and reuse it for all IB skill calls in this and future sessions — until the user explicitly asks for the other account.
If both ports fail, ask the user to verify that TWS or IB Gateway is running with API access enabled.

For full trade history beyond ~7 days, the user needs a Flex Web Service token and a pre-configured Trade query in IBKR Account Management.

## Instructions

> **Note:** If `uv` is not installed or `pyproject.toml` is not found, replace `uv run python` with `python` in all commands below.

```bash
# Recent trades (last ~7 days via API)
uv run python .claude/skills/ib-trades-history/scripts/trades.py --all-accounts

# Filter by symbol
uv run python .claude/skills/ib-trades-history/scripts/trades.py --all-accounts --symbol AAPL

# Full history via FlexReport
uv run python .claude/skills/ib-trades-history/scripts/trades.py --all-accounts --flex-token YOUR_TOKEN --flex-query-id YOUR_QUERY_ID

# Custom date range (FlexReport)
uv run python .claude/skills/ib-trades-history/scripts/trades.py --all-accounts --flex-token TOKEN --flex-query-id QID --start-date 2025-01-01 --end-date 2025-12-31

# Multiple queries (e.g., one per year to exceed 365-day limit)
uv run python .claude/skills/ib-trades-history/scripts/trades.py --all-accounts --flex-token TOKEN --flex-query-id QID_2025 --flex-query-id QID_2026 --start-date 2025-01-01 --end-date 2026-12-31

# From local FlexReport XML files (no TWS/Gateway needed)
uv run python .claude/skills/ib-trades-history/scripts/trades.py --file trades_2024.xml --file trades_2025.xml --symbol TSLA

# Mix files with date filtering
uv run python .claude/skills/ib-trades-history/scripts/trades.py --file exports/2025.xml --start-date 2025-06-01 --end-date 2025-12-31
```

## Arguments

- `--port` - IB port (default: 7497 for paper trading)
- `--account` - Specific account ID to filter
- `--all-accounts` - Fetch trades for all managed accounts
- `--symbol` - Filter trades by symbol (e.g., AAPL)
- `--start-date` - Start date in YYYY-MM-DD format (default: Jan 1 of current year)
- `--end-date` - End date in YYYY-MM-DD format (default: today)
- `--flex-token` - FlexReport token (enables extended history)
- `--flex-query-id` - FlexReport query ID (repeatable — pass multiple to merge queries spanning different periods)
- `--file` - Local FlexReport XML file path (repeatable — pass multiple to merge files). No TWS/Gateway needed

**Default behavior** (no flags): fetches trades for the first managed account from the live API (~7 days).
**Always use `--all-accounts`** unless the user asks for a specific account.

## Data Sources

| Scenario | Source | Date Range |
|---|---|---|
| No flex args | `reqExecutionsAsync` | ~last 7 days |
| `--flex-token` + `--flex-query-id` | `FlexReport` (web) | As configured in query |
| `--file` | `file` (local XML) | Full file contents |

When using the live API, a `data_limitation` warning is included in the output.

## Output

Returns JSON with:
- `connected` - Whether connection succeeded
- `source` - Data source used (`reqExecutionsAsync` or `FlexReport`)
- `filters` - Applied filters (dates, symbol, account)
- `data_limitation` - Warning about API date limits (only when using live API)
- `execution_count` - Total number of executions returned
- `executions` - List of individual trade executions
- `summary` - Aggregated stats per symbol (bought, sold, commission, realized P&L)

If not connected, explain that TWS/Gateway needs to be running.

## Dependencies

- `ib-async`

More from staskh/trading_skills

SkillDescription
earnings-calendarGet upcoming earnings dates with timing (before/after market) and EPS estimates. Use when user asks about earnings dates, earnings calendar, when a company reports, or upcoming earnings.
fundamentalsGet fundamental financial data including financials, earnings, and key metrics. Use when user asks about financials, earnings, revenue, profit, balance sheet, income statement, or company fundamentals.
greeksCalculate option Greeks (delta, gamma, theta, vega) and implied volatility for specific options. Use when user asks about Greeks, delta, gamma, theta, vega, IV, or option sensitivity analysis.
ib-accountGet account summary from Interactive Brokers including cash balance, buying power, and account value. Use when user asks about their account, balance, buying power, or available cash. Requires TWS or IB Gateway running locally.
ib-collarGenerate tactical collar strategy reports for protecting PMCC positions through earnings or high-risk events. Requires TWS or IB Gateway running locally.
ib-create-consolidated-reportConsolidate IBRK trade CSV files from a directory into a summary report. Groups trades by symbol, underlying, date, strike, buy/sell, and open/close. Outputs both markdown and CSV.
ib-find-short-rollFind roll options for existing short positions OR find best covered call/put to open against long stock. Use when user asks about rolling shorts, finding roll candidates, writing covered calls, or managing option positions. Requires TWS or IB Gateway running locally.
ib-option-chainGet option chain data from Interactive Brokers for equities, ETFs, and futures (FOP), including calls and puts with strikes, bids, asks, volume, implied volatility, and model Greeks. Use when user asks about options using IBKR data, futures options (NQ/ES/CL/GC...), or needs real-time option quotes from their broker. Requires TWS or IB Gateway running locally.
ib-pmcc-advisorAnalyze PMCC (Poor Man's Covered Call / diagonal spread) positions from IB portfolio. For each diagonal spread, reports short leg risk (delta, IV, assignment probability), daily P&L projections, top-3 roll candidates, and a side-by-side comparison table. Requires TWS or IB Gateway running locally.
ib-portfolioGet portfolio positions from Interactive Brokers. Use when user asks about their portfolio, positions, holdings, or what stocks they own. Requires TWS or IB Gateway running locally.