# CLI Overview

**GitHub:** https://github.com/longbridge/longbridge-terminal

AI-native CLI covering every Longbridge OpenAPI endpoint. Designed for scripting, AI-agent tool-calling, and daily trading workflows from the terminal.

## Discovering Commands

Always use the CLI's built-in help — it reflects the currently installed version:

```bash
longbridge --help                  # List all available commands
longbridge <command> --help        # Options and flags for a specific command
```

Do not rely on hardcoded documentation for command syntax or flags — use `--help` instead.

## Installation

> **Quickest:** run the installer bundled with the `longbridge` skill — `sh scripts/install-cli.sh` (macOS / Linux) or `powershell -ExecutionPolicy Bypass -File scripts\install-cli.ps1` (Windows), paths relative to the `longbridge` skill directory. Confirm with the user before installing.

```bash
# macOS (Homebrew — recommended)
brew install --cask longbridge/tap/longbridge-terminal
```

Windows (Scoop):

```powershell
scoop install https://open.longbridge.com/longbridge/longbridge-terminal/longbridge.json
```

Other platforms: download a release binary from <https://github.com/longbridge/longbridge-terminal/releases> and put `longbridge` on your `PATH`.

## Update

```bash
# Built-in updater
longbridge update
```

## Authentication

Uses OAuth 2.0 — no manual token or key management needed:

```bash
longbridge auth login    # Opens browser OAuth flow; the CLI manages the session itself
longbridge auth logout   # Sign out and clear the session
longbridge check    # Verify connectivity and token (no auth required)
```

**China Mainland:** The CLI auto-detects CN by probing `geotest.lbkrs.com` on startup (non-blocking). CN users automatically use `.cn` endpoints.

## Environment Variables

| Variable         | Value     | Description                                                                                                                 |
| ---------------- | --------- | --------------------------------------------------------------------------------------------------------------------------- |
| `LONGBRIDGE_ENV` | `staging` | Switch all endpoints to the staging environment (`openapi.longbridge.xyz`). Useful for testing against non-production data. |

```bash
# Run any command against the staging environment
LONGBRIDGE_ENV=staging longbridge auth login
LONGBRIDGE_ENV=staging longbridge statement list

# Or export for the entire shell session
export LONGBRIDGE_ENV=staging
```

When set, OAuth, HTTP API, and WebSocket endpoints are all redirected to staging. Unset the variable (or omit it) to use production.

## Output Formats

```bash
--format table   # Human-readable table (default)
--format json    # Machine-readable JSON — use for piping to jq, AI agents, scripts
```

All commands support `--format json`. Example with `jq`:

```bash
longbridge positions --format json | jq '.[] | {symbol, quantity, cost_price}'
longbridge order --format json | jq '.[] | select(.status == "New")'
```

## AI Agent Integration

### Symbols

- Pass a **ticker with a market suffix** (`TSLA.US`, `700.HK`, `600519.SH`), never a company name — `tesla.US` does not exist. US indexes take a leading dot (`.DJI.US`, `.SPX.US`); stocks do not.
- Symbols are case-insensitive on input and returned upper-case: `tsla.us` queries `TSLA.US`, and the JSON `symbol` field reads `TSLA.US`. Match results on the upper-cased symbol.
- An unknown symbol is an **error (non-zero exit)**, never an empty success. The stderr message names the symbol and, when one exists, the spelling to retry with (`Did you mean ".DJI.US"?`). For a batch, the symbols that exist are still printed on stdout before the error.
- With `--format json`, errors are JSON on stderr: `{"error": {"code", "message", "trace_id", "hints", "symbols"}}`. `symbols` lists each unresolved symbol with a stable `status` — `no_data` (exists, no data: check quote access with `longbridge auth status`), `suggest` (retry with `suggestions`), `unknown` (use a ticker), `unchecked` — so branch on `status`, never on the localised `message`. `hints` says, for `403308`, which permission to grant via `longbridge auth login`.
- A non-zero exit from `quote` / `static` / `calc-index` does not void stdout: the symbols that resolved are still there.

### Count / limit alias

All commands with a `--count` flag also accept `--limit` as an alias. Both are equivalent — use whichever feels natural in generated commands.

### Parallel execution pattern

Use `&` and `wait` to run multiple queries concurrently (faster results):

```bash
longbridge quote TSLA.US & longbridge quote AAPL.US & wait
longbridge kline TSLA.US --period day --count 30 & longbridge kline NVDA.US --period day --count 30 & wait
```

### Earnings analysis pattern

```bash
# Step 1: discover filing IDs
longbridge filing list TSLA.US
# Step 2: pull full Markdown content of a specific filing
longbridge filing detail TSLA.US 610186794100660481 --file-index 0
```

## Longbridge AI Agents

`longbridge agent` talks to Longbridge's own AI agents (research, stock analysis, screeners, custom workflow agents). This is distinct from the data commands above: the agent answers in prose, not JSON records.

```bash
longbridge agent workspaces                       # workspaces holding your agents
longbridge agent list                             # chat-capable agents (--all includes workflow agents)
longbridge agent chat chatbot "分析一下 TSLA"      # first round
longbridge agent chat chatbot <CHAT_UID> <MSG_ID> "继续"   # follow-up
longbridge agent continue chatbot <CHAT_UID> <MSG_ID> --answer "…"  # resume an interrupted run
longbridge agent --skill                          # skill document written for AI harnesses
```

Key points:

- **`chatbot` (LongbridgeAI) is public** — usable by any account, and it does not appear in `agent list` because no endpoint enumerates public agents.
- **Runs take 1–2 minutes.** Transport is SSE; `--stream` prints tokens as they arrive.
- **Follow-ups need both IDs** from the previous response: `chat_uid` and `message_id`.
- **`status: "interrupted"`** means the agent asked clarifying questions — answer them with `agent continue`, not `agent chat`.
- **`--skill`** prints a static document (no auth, no network) describing the whole flow; point a harness at it rather than duplicating the details here.

## Extended Hours (Pre/Post Market)

`quote`, `intraday`, `kline`, `kline history` all support extended-hours data. Use `longbridge <command> --help` for exact flags — key points:

- **`quote`**: always returns `pre_market_quote` / `post_market_quote` / `overnight_quote` when available (US only). Table format appends an "Extended Hours" section; JSON includes them as nested objects.
- **`intraday` / `kline` / `kline history`**: default to intraday session only; pass `--session all` to include pre/post-market data. `kline`/`kline history` add a **Session** column when `--session all` is used.

## Rate Limits

- Max **10 API calls/second**
- Token is auto-refreshed; no manual renewal needed
- WebSocket subscriptions are not available in the CLI (use SDK for real-time push)
