diff --git a/skills/broker/SKILL.md b/skills/broker/SKILL.md index 49b557e..bb1683e 100644 --- a/skills/broker/SKILL.md +++ b/skills/broker/SKILL.md @@ -1,207 +1,264 @@ --- name: broker-cli -description: Expanded reference for the broker CLI command surface, including daemon, market data, orders, portfolio, risk, and audit commands. Use when translating trading operations into exact `broker` commands or checking command syntax, flags, defaults, and valid values. +description: Complete reference for the broker CLI. Use when translating trading intentions into exact `broker` commands. Covers all commands, flags, defaults, workflows, and error handling. --- -# Broker CLI Skill +# Broker CLI -Use this guide as an expanded Markdown help menu for `broker`. +`broker` is a CLI that provides programmatic access to a brokerage account (Interactive Brokers or E*Trade). The daemon is already running — use the commands below to trade. -## Basics +## Output Format -- Run help on any command with `-h` or `--help`. -- Expect JSON output from commands. -- Use command typo suggestions from the CLI if you mistype a command name. -- `broker setup` now configures provider credentials and fund observability repo wiring. +Every command returns JSON with this envelope: -## Top-Level Command Map +```json +{"ok": true, "data": {...}, "error": null, "meta": {"schema_version": "v1", "command": "...", "request_id": "...", "timestamp": "..."}} +``` + +On error, `ok` is `false`, `data` is `null`, and `error` contains: -```text -broker daemon ... # daemon lifecycle -broker setup ... # provider + fund observability setup -broker quote ... # quote snapshot -broker watch ... # streaming quote refresh -broker chain ... # option chain -broker history ... # historical bars -broker order ... # grouped order commands -broker orders ... # list orders (flat command) -broker cancel ... # cancel one/all orders (flat command) -broker fills ... # fills/executions (flat command) -broker positions ... # positions -broker pnl ... # PnL -broker balance ... # account balance/margin -broker exposure ... # grouped exposure -broker check ... # risk check -broker limits ... # risk limits -broker set ... # set mutable risk param -broker halt ... # emergency halt -broker resume ... # resume after halt -broker override ... # temporary risk override -broker audit ... # grouped audit commands +```json +{"code": "ERROR_CODE", "message": "...", "details": {...}, "suggestion": "..."} ``` -## Setup Command +The `suggestion` field, when present, tells you what to do next. The `request_id` in `meta` can be used to correlate commands in the audit log. + +## Order Types + +The order type is determined by which price flags you provide: + +| Flags | Order type | +|---|---| +| _(none)_ | market | +| `--limit` | limit | +| `--stop` | stop | +| `--limit` + `--stop` | stop-limit | +| `broker order bracket` | bracket (entry + take-profit + stop-loss) | + +## Decision Flags (Required) + +Every order submission (`buy`, `sell`, `bracket`) requires three decision flags. Orders without them are rejected. -### `broker setup` +- `--decision-name "Title Case Name"` — title-case, single-line, plain text +- `--decision-summary "Single line summary"` — single-line, plain text +- `--decision-reasoning "## Markdown reasoning"` — long-form markdown thesis -Interactive setup for broker provider + fund observability repo bootstrap. +These are stored in the fund observability repo as decision records. Write substantive reasoning — it becomes the audit trail for every trade. -- Prompts for fund directory. -- If the directory already exists, setup reuses it and skips fund bootstrap prompts. -- For new directories, setup prompts for fund name, fund slug, and git origin URL. -- Initial capital is fetched from the configured broker provider. -- Setup initializes `config.json`, `fills.json`, `cash_events.json`, `decisions/`, and a git repo with `origin`. +## Risk Limit Defaults -## Daemon Commands +These are the default risk limits. Query live values with `broker limits`. -### `broker daemon start` +| Parameter | Default | Description | +|---|---|---| +| `max_position_pct` | 10.0 | Max % of NLV in one position | +| `max_order_value` | 50000 | Max dollar value per order | +| `max_daily_loss_pct` | 2.0 | Max daily loss as % of NLV | +| `max_sector_exposure_pct` | 30.0 | Max % exposure to one sector | +| `max_single_name_pct` | 10.0 | Max % of NLV in a single name | +| `max_open_orders` | 20 | Max simultaneous open orders | +| `order_rate_limit` | 10 | Max orders per minute | +| `duplicate_window_seconds` | 60 | Window for duplicate order detection | +| `symbol_allowlist` | _(empty = all allowed)_ | Only these symbols are tradeable | +| `symbol_blocklist` | _(empty = none blocked)_ | These symbols are blocked | -Start `broker-daemon` and wait for socket readiness. +## Workflows + +### Research a trade ```bash -broker daemon start [--gateway HOST:PORT] [--client-id INT] [--paper] +broker quote AAPL +broker history AAPL --period 30d --bar 1d +broker chain AAPL --expiry 2026-03 --type call +broker snapshot --symbols AAPL +broker check --side buy --symbol AAPL --qty 50 --limit 180 ``` -- `--gateway`: Override IB gateway endpoint. -- `--client-id`: Override IB client id. -- `--paper`: Force gateway port `4002`. +### Dry-run then place an order -### `broker daemon stop` +```bash +# Test against risk limits without submitting +broker order buy AAPL 50 --limit 180 --dry-run \ + --decision-name "AAPL Accumulation" \ + --decision-summary "Adding to AAPL on pullback to 180 support" \ + --decision-reasoning "## Thesis\nAAPL pulled back to 180 support with RSI oversold." + +# If ok=true, submit for real (same command without --dry-run) +broker order buy AAPL 50 --limit 180 \ + --decision-name "AAPL Accumulation" \ + --decision-summary "Adding to AAPL on pullback to 180 support" \ + --decision-reasoning "## Thesis\nAAPL pulled back to 180 support with RSI oversold." +``` -Request graceful daemon shutdown. +### Safe retry with idempotency ```bash -broker daemon stop +broker order buy AAPL 50 --limit 180 --idempotency-key "aapl-buy-20260222" \ + --decision-name "AAPL Accumulation" \ + --decision-summary "Adding to AAPL on pullback to 180 support" \ + --decision-reasoning "## Thesis\nAAPL pulled back to 180 support with RSI oversold." +# Safe to retry — daemon deduplicates by idempotency key within the duplicate window. ``` -### `broker daemon status` - -Show daemon uptime, IB connection state, and risk halt status. +### Verify an order ```bash -broker daemon status +broker order status # check status +broker fills --symbol AAPL # confirm execution ``` -### `broker daemon restart` +### Monitor portfolio + +```bash +broker snapshot # positions + balance + exposure in one call +broker positions +broker balance +broker exposure --by sector +broker pnl --today +``` -Stop then start daemon. +### Risk management ```bash -broker daemon restart [--paper] +broker limits # view current limits +broker set max_order_value 25000 # tighten a limit +broker override --param max_order_value --value 75000 --duration 1h --reason "large block trade" +broker halt # emergency: cancel all + reject new orders +broker resume # re-enable trading after halt ``` -- `--paper`: Restart against gateway port `4002`. +--- + +## Command Reference -## Market Data Commands +### Market Data -### `broker quote` +#### `broker quote` -Snapshot quote data for one or more symbols. +Snapshot quotes for one or more symbols. ```bash -broker quote SYMBOL [SYMBOL...] +broker quote SYMBOL [SYMBOL...] [--intent best_effort|top_of_book|last_only] ``` -### `broker watch` +- `--intent`: Quote intent. Default: `best_effort`. + - `best_effort` — returns whatever data is available (delayed fallback if live unavailable) + - `top_of_book` — requires bid+ask; warns if incomplete + - `last_only` — only last trade price -Continuously refresh quote fields until interrupted. +#### `broker watch` + +Continuously refresh quote fields until interrupted (Ctrl+C). ```bash -broker watch SYMBOL [--fields CSV] [--interval DURATION] +broker watch SYMBOL [--fields CSV] [--interval DURATION] [--intent best_effort|top_of_book|last_only] ``` -- Default `--fields`: `bid,ask,last,volume` -- Allowed field values: - - `symbol`, `bid`, `ask`, `last`, `volume`, `timestamp`, `exchange`, `currency` -- `--interval` examples: `250ms`, `1s`, `2m` (must be > 0) +- `--fields`: default `bid,ask,last,volume`. Allowed: `symbol`, `bid`, `ask`, `last`, `volume`, `timestamp`, `exchange`, `currency` +- `--interval`: default `1s`. Examples: `250ms`, `1s`, `2m` -### `broker chain` +#### `broker chain` -Fetch option chain for a symbol, optionally filtered. +Fetch option chain for a symbol. ```bash -broker chain SYMBOL [--expiry YYYY-MM] [--strike-range LOW:HIGH] [--type call|put] +broker chain SYMBOL [--expiry YYYY-MM] [--strike-range LOW:HIGH] [--type call|put] \ + [--limit N] [--offset N] [--fields CSV] [--strict/--no-strict] ``` -### `broker history` +- `--strike-range`: default `0.9:1.1` (near the money) +- `--limit`: max entries to return. Default: `200` +- `--offset`: offset into filtered results. Default: `0` +- `--fields`: comma-separated. Allowed: `symbol`, `right`, `strike`, `expiry`, `bid`, `ask`, `implied_vol`, `delta`, `gamma`, `theta`, `vega` +- `--strict/--no-strict`: treat empty chain results as errors + +#### `broker history` -Fetch historical bars for a symbol. +Fetch historical bars. ```bash -broker history SYMBOL --period PERIOD --bar BAR [--rth-only] +broker history SYMBOL --period PERIOD --bar BAR [--rth-only] [--strict/--no-strict] ``` -- `--period` values: `1d`, `5d`, `30d`, `90d`, `1y` -- `--bar` values: `1m`, `5m`, `15m`, `1h`, `1d` -- `--rth-only`: Restrict to regular trading hours +- `--period` (required): `1d`, `5d`, `30d`, `90d`, `1y` +- `--bar` (required): `1m`, `5m`, `15m`, `1h`, `1d` +- `--rth-only`: restrict to regular trading hours +- `--strict/--no-strict`: treat empty history as error + +#### `broker capabilities` + +Query what market data types the connected provider supports. + +```bash +broker capabilities [SYMBOL...] [--refresh] +``` + +- Without symbols: uses daemon probe list (default: `AAPL`) +- `--refresh`: force fresh probe via provider API + +--- -## Order Commands +### Orders -### `broker order buy` +#### `broker order buy` -Place buy order. Market by default unless `--limit` and/or `--stop` is set. +Place a buy order. Market by default unless `--limit` and/or `--stop` is set. ```bash broker order buy SYMBOL QTY [--limit PRICE] [--stop PRICE] [--tif DAY|GTC|IOC] \ - --decision-name "Title Case Decision" \ - --decision-summary "One-line plain text summary" \ - --decision-reasoning "## Markdown reasoning..." + [--dry-run] [--idempotency-key KEY] \ + --decision-name "Title" --decision-summary "Summary" --decision-reasoning "Reasoning" ``` -- `QTY` must be `> 0`. -- Default `--tif`: `DAY` -- Decision flags are required for submitted orders. +- `QTY`: must be > 0 (supports fractional) +- `--tif`: default `DAY` +- `--dry-run`: evaluate against risk only, do not submit +- `--idempotency-key`: stable key for safe retries (maps to `client_order_id`) +- Decision flags are **required** for submitted orders (not required for `--dry-run`) -### `broker order sell` +#### `broker order sell` -Place sell order. Market by default unless `--limit` and/or `--stop` is set. +Place a sell order. Same flags as `buy`. ```bash broker order sell SYMBOL QTY [--limit PRICE] [--stop PRICE] [--tif DAY|GTC|IOC] \ - --decision-name "Title Case Decision" \ - --decision-summary "One-line plain text summary" \ - --decision-reasoning "## Markdown reasoning..." + [--dry-run] [--idempotency-key KEY] \ + --decision-name "Title" --decision-summary "Summary" --decision-reasoning "Reasoning" ``` -- `QTY` must be `> 0`. -- Default `--tif`: `DAY` -- Decision flags are required for submitted orders. - -### `broker order bracket` +#### `broker order bracket` -Place bracket order (entry + take-profit + stop-loss). +Place a bracket order (entry + take-profit + stop-loss). Interactive Brokers only. ```bash -broker order bracket SYMBOL QTY --entry PRICE --tp PRICE --sl PRICE [--side buy|sell] [--tif DAY|GTC|IOC] \ - --decision-name "Title Case Decision" \ - --decision-summary "One-line plain text summary" \ - --decision-reasoning "## Markdown reasoning..." +broker order bracket SYMBOL QTY --entry PRICE --tp PRICE --sl PRICE \ + [--side buy|sell] [--tif DAY|GTC|IOC] \ + --decision-name "Title" --decision-summary "Summary" --decision-reasoning "Reasoning" ``` -- Required: `--entry`, `--tp`, `--sl` -- Default `--side`: `buy` -- Default `--tif`: `DAY` -- Decision flags are required. +- `--entry`, `--tp`, `--sl`: all required +- `--side`: default `buy` +- `--tif`: default `DAY` -### `broker order status` +#### `broker order status` -Show status for one client order id. +Show status for one order. ```bash broker order status ORDER_ID ``` -### `broker orders` +#### `broker orders` -List orders (flat command at root). +List orders. ```bash broker orders [--status active|filled|cancelled|all] [--since YYYY-MM-DD] ``` -- Default `--status`: `all` +- `--status`: default `all` -### `broker cancel` +#### `broker cancel` Cancel one order or all open orders. @@ -211,10 +268,9 @@ broker cancel --all [--confirm] ``` - Do not pass `ORDER_ID` with `--all`. -- If not using `--all`, `ORDER_ID` is required. -- `--confirm` is required by daemon policy for some `--all` contexts. +- `--confirm` may be required for `--all`. -### `broker fills` +#### `broker fills` List fills / execution history. @@ -222,38 +278,42 @@ List fills / execution history. broker fills [--since YYYY-MM-DD] [--symbol SYMBOL] ``` -## Portfolio Commands +--- + +### Portfolio -### `broker positions` +#### `broker snapshot` -Show current positions. +Fetch positions, balance, and exposure in one request. ```bash -broker positions [--symbol SYMBOL] +broker snapshot [--symbols COMMA_SEPARATED] [--exposure-by symbol|sector|asset_class|currency] ``` -### `broker pnl` +- `--symbols`: comma-separated symbols for quote snapshot. Defaults to current position symbols. +- `--exposure-by`: default `symbol` -Show PnL for today, period, or since date. +#### `broker positions` ```bash -broker pnl [--today | --period 7d | --since YYYY-MM-DD] +broker positions [--symbol SYMBOL] ``` -- Choose only one of `--today`, `--period`, `--since`. -- If none is provided, defaults to `--today`. +#### `broker pnl` -### `broker balance` +```bash +broker pnl [--today | --period 7d | --since YYYY-MM-DD] +``` -Show balances and margin metrics. +- Choose only one. Defaults to `--today`. + +#### `broker balance` ```bash broker balance ``` -### `broker exposure` - -Show exposure grouped by category. +#### `broker exposure` ```bash broker exposure [--by symbol|sector|asset_class|currency] @@ -261,9 +321,11 @@ broker exposure [--by symbol|sector|asset_class|currency] - Default `--by`: `symbol` -## Risk Commands +--- + +### Risk -### `broker check` +#### `broker check` Dry-run an order against risk limits (no submission). @@ -271,11 +333,10 @@ Dry-run an order against risk limits (no submission). broker check --side buy|sell --symbol SYMBOL --qty QTY [--limit PRICE] [--stop PRICE] [--tif DAY|GTC|IOC] ``` -- Required: `--side`, `--symbol`, `--qty` -- `--qty` must be `> 0` -- Default `--tif`: `DAY` +- `--side`, `--symbol`, `--qty` are required +- `--tif`: default `DAY` -### `broker limits` +#### `broker limits` Show current runtime risk limits. @@ -283,35 +344,25 @@ Show current runtime risk limits. broker limits ``` -### `broker set` +#### `broker set` -Set mutable runtime risk parameter. +Set a risk parameter at runtime. ```bash broker set PARAM VALUE ``` -- Valid `PARAM` values: - - `duplicate_window_seconds` - - `max_daily_loss_pct` - - `max_open_orders` - - `max_order_value` - - `max_position_pct` - - `max_sector_exposure_pct` - - `max_single_name_pct` - - `order_rate_limit` - - `symbol_allowlist` - - `symbol_blocklist` +Valid params: `max_position_pct`, `max_order_value`, `max_daily_loss_pct`, `max_sector_exposure_pct`, `max_single_name_pct`, `max_open_orders`, `order_rate_limit`, `duplicate_window_seconds`, `symbol_allowlist`, `symbol_blocklist` -### `broker halt` +#### `broker halt` -Emergency halt (cancel open orders and reject new orders). +Emergency halt — cancels all open orders and rejects new orders. ```bash broker halt ``` -### `broker resume` +#### `broker resume` Resume trading after halt. @@ -319,75 +370,83 @@ Resume trading after halt. broker resume ``` -### `broker override` +#### `broker override` -Apply temporary risk override with required reason and duration. +Temporary risk override with required reason and duration. ```bash broker override --param PARAM --value VALUE --duration DURATION --reason TEXT ``` -- Required: all options above. -- `--param` uses same valid values as `broker set`. -- `--duration` accepts: - - `h` (hours) - - `m` (minutes) - - `s` (seconds) - - `` (seconds) +- All flags required. +- `--duration`: `30m`, `1h`, `1d` (or raw seconds) -## Audit Commands +--- -### `broker audit orders` +### Audit -Query order lifecycle audit rows. +#### `broker audit orders` ```bash broker audit orders [--since YYYY-MM-DD] [--status active|filled|cancelled|all] ``` -### `broker audit commands` - -Query command invocation audit rows. +#### `broker audit commands` ```bash -broker audit commands [--source cli|sdk|ts_sdk] [--since YYYY-MM-DD] +broker audit commands [--source cli|sdk|ts_sdk] [--since YYYY-MM-DD] [--request-id ID] ``` -### `broker audit risk` - -Query risk event audit rows. +#### `broker audit risk` ```bash broker audit risk [--type EVENT_TYPE] ``` -### `broker audit export` - -Export audit rows to CSV. +#### `broker audit export` ```bash -broker audit export --output PATH [--format csv] [--table orders|commands|risk] [--since YYYY-MM-DD] [--status STATUS] [--source SOURCE] [--type EVENT_TYPE] +broker audit export --output PATH [--format csv] [--table orders|commands|risk] \ + [--since YYYY-MM-DD] [--status STATUS] [--source SOURCE] [--request-id ID] [--type EVENT_TYPE] ``` -- Required: `--output` -- `--format`: currently `csv` only -- Default `--table`: `orders` -- Optional filters: - - `--status`: `active|filled|cancelled|all` (order rows) - - `--source`: `cli|sdk|ts_sdk` (command rows) - - `--type`: risk event type (risk rows) +- `--output`: required +- `--format`: `csv` only +- `--table`: default `orders` + +--- -## Quick Examples +### Utility + +#### `broker schema` + +Query daemon command schemas. Useful for discovering parameter types and valid values. ```bash -broker daemon start --paper -broker quote AAPL MSFT -broker history AAPL --period 5d --bar 15m --rth-only -broker order buy AAPL 10 --limit 180 --tif DAY -broker orders --status active -broker cancel --all --confirm -broker check --side buy --symbol AAPL --qty 25 --limit 180 -broker set max_order_value 5000 -broker override --param max_order_value --value 10000 --duration 1h --reason "earnings session" -broker audit export --output /tmp/audit.csv --table orders --since 2026-01-01 +broker schema [COMMAND] ``` + +- Without argument: list all commands +- With argument (e.g. `quote.snapshot`): return schema for that command + +--- + +## Error Handling + +| Error Code | Exit | What to do | +|---|---|---| +| `DAEMON_NOT_RUNNING` | 3 | Run `broker daemon start` | +| `IB_DISCONNECTED` | 4 | Verify IB Gateway/TWS is running, wait and retry | +| `IB_REJECTED` | 1 | Check order params (symbol, qty, price) | +| `RISK_CHECK_FAILED` | 5 | Check `broker limits`, adjust order size/price or use `broker override` | +| `RISK_HALTED` | 6 | Trading is halted — review situation, then `broker resume` | +| `RATE_LIMITED` | 1 | Wait and retry (default: 10 orders/min) | +| `DUPLICATE_ORDER` | 1 | Identical order within duplicate window — wait or use different `--idempotency-key` | +| `INVALID_SYMBOL` | 1 | Check symbol with `broker quote` | +| `INVALID_ARGS` | 2 | Check command syntax with `-h` | +| `TIMEOUT` | 10 | Retry the command | +| `INTERNAL_ERROR` | 1 | Retry; if persistent, check `broker daemon status` | + +## Fund Observability + +When configured, decisions and fills auto-sync to a git-backed fund repo. The `--decision-name`, `--decision-summary`, and `--decision-reasoning` flags on orders become markdown files in the repo's `decisions/` directory. Fills append to `fills.json`. This happens automatically — no manual management needed.