---
name: longbridge-cli
description: LongPort OpenAPI CLI for market data, account management, orders, and trading/dividend analysis workflows.
---

# LongBridge CLI (longbridge)

A specialized skill for interacting with the LongPort OpenAPI via the `longbridge` CLI. This skill handles market data (quotes, candlesticks), account info, and order management.

## Transport Options

LongPort can be accessed three ways — choose the one that fits:

| Transport | When to use |
|-----------|-------------|
| **CLI** (`longbridge`) | Quick terminal queries, simple scripts (this skill) |
| **Python SDK** (`longport`) | Complex analysis, automated trading, batch workflows (see `longbridge-python-sdk` skill) |
| **MCP** (native Hermes) | AI-agent-first access — tools auto-discover in Hermes (see `references/longport-mcp-integration.md`) |

For the MCP transport, LongPort uses a two-endpoint architecture: an auth endpoint (`/agent`) to exchange an auth code for a Bearer token, then the main MCP service at `https://mcp.longport.cn`. Full flow documented in the reference below.

## Usage
All commands should be run with the appropriate environment variables (`LONGBRIDGE_APP_KEY`, `LONGBRIDGE_APP_SECRET`, `LONGBRIDGE_ACCESS_TOKEN`) loaded.

### Common Commands
- **Quotes**: `longbridge quote --json <SYMBOLS>` (Get real-time quotes)
- **Candlesticks**: `longbridge candlesticks --json <SYMBOLS>` (Get OHLC data)
- **Account**: `longbridge balance --json` or `longbridge positions --json`
- **Orders**: `longbridge orders --json` (Today's orders) or `longbridge buy/sell --json <SYMBOLS> <QUANTITY>`

### Order Placement (做T / Active Trading)

CLI order commands require `--price` for limit orders and `-y` to skip interactive confirmation (essential for automation):

```bash
# Limit buy
longbridge buy RGTI.US --qty 30 --price 18.50 -y

# Limit sell
longbridge sell RGTI.US --qty 30 --price 20.50 -y

# Check pending orders
longbridge orders --json

# Cancel all orders (or specific ones)
longbridge cancel <ORDER_ID>
```

**Pitfall**: `longbridge buy/sell` without `-y` hangs in interactive mode. Always use `-y` in scripts/cron.

#### T-Trading (做T) Analysis Workflow

做T = buying/selling around an existing position to lower cost basis. Requires high-volatility stocks with 10%+ daily swings.

1. **Fetch multi-timeframe data** via Python SDK (5min, 30min, daily candlesticks)
2. **Calculate technical indicators**: SMA(5/10/20), ATR(14) for volatility, recent support/resistance from highs/lows
3. **Identify key levels**: buy zone (support), sell zone (resistance), breakout/breakdown thresholds
4. **Deploy monitoring script** as cron job (every 10-15 min during market hours)
5. **Auto-place limit orders** when price hits key levels, notify user via chat

Technical analysis snippet (run via `execute_code`):
```python
from longport import openapi
cfg = openapi.Config.from_env()
ctx = openapi.QuoteContext(config=cfg)

candles = ctx.candlesticks("SYMBOL.US", openapi.Period.Day, 20, openapi.AdjustType.NoAdjust)
closes = [float(c.close) for c in candles]
highs = [float(c.high) for c in candles]
lows = [float(c.low) for c in candles]

sma5 = sum(closes[-5:]) / 5
atr = sum(max(highs[i]-lows[i], abs(highs[i]-closes[i-1]), abs(lows[i]-closes[i-1])) for i in range(-14, 0)) / 14
support = min(lows[-5:])
resistance = max(highs[-5:])
```

#### Sell Order Workflow (做T卖出)

When user wants to place a sell order for an existing position:

1. **Query actual position first** — `trade_ctx.stock_positions()`, get `quantity`, `cost_price`, `available_quantity`. NEVER guess or use memory.
2. **Fetch candlesticks** — 30-day daily for resistance levels, 5-min for intraday context.
3. **Calculate technical levels** — SMA(5/10/20), support/resistance from high/low clusters, psychological round numbers ($20, $21, etc.).
4. **Present options table** — conservative / recommended / aggressive, with projected P&L based on ACTUAL cost basis.
5. **Ask urgency** — "这周要成交吗?" determines how aggressive the price should be. Patient = closer to resistance; urgent = closer to current price.
6. **Place order** — Use `execute_code` + Python SDK, `submit_order` with `TimeInForceType.GoodTilCanceled` and `OutsideRTH.AnyTime`.
7. **Report order ID** — Always return the order_id so user can track/cancel.

**Price selection heuristic** (not in a hurry):
- Conservative: next psychological round number above current price
- Recommended: SMA10 or recent consolidation zone midpoint
- Aggressive: SMA20 or prior support-turned-resistance

For intraday margin trading with actionable entry/exit/position sizing, see `references/intraday-margin-trading.md`.\nFor token refresh automation, see `~/.hermes/scripts/update_longbridge_token.sh` — auto-updates all token locations and verifies.\nFor semi-automatic order placement with price monitoring, see `references/semi-auto-trading.md`.
For VWAP + multi-indicator T-trading panel (scoring system, cron-based auto-orders), see `references/vwap-t-trading-panel.md`.
For DCA position filtering by dividend yield threshold, see `references/dca-yield-filter.md`.

### Market Analysis Workflows

#### Watchlist Query (via Python SDK)
The CLI does not support watchlist queries directly. Use `longbridge-python-sdk` skill instead, or use the `execute_code` pattern in `references/execute-code-pattern.py` which reliably loads LONGPORT_* env vars:
```python
from longport import openapi
cfg = openapi.Config.from_env()
ctx = openapi.QuoteContext(config=cfg)
resp = ctx.watchlist()  # Returns all groups with securities
```

#### Dividend/Yield Analysis
When looking for income-generating assets:
1. **Identify Target**: Determine if the user wants monthly, quarterly, or annual payouts.
2. **Filter by Stability**: Prioritize assets with high stability scores (e.g., Dividend Aristocrats/Kings).
3. **Group and Sort**: Group by frequency (Monthly vs Quarterly) and sort by stability, then yield.
4. **Contextualize**: Provide a clear table or list with enough context (Ticker, Name, Yield, Stability).

Key dividend stocks by frequency:
- **Monthly**: O (Realty Income), MAIN (Main Street Capital)
- **Quarterly**: KO (Coca-Cola), PG (Procter & Gamble), and most S&P 500 dividend payers

### Market Trend & Professional Analysis
1. **Identify Asset Class**: Stocks or Crypto.
2. **Select Toolset**:
   - Stocks: Use `stock-analysis` or `stock-analysis-agent` (Yahoo Finance data)
   - Crypto/professional trading: Use `longbridge` CLI (this skill) or `longbridge-python-sdk`
3. **Execute Analysis**: Run the appropriate tool for real-time or historical data.
4. **Synthesize**: Summarize into actionable insights.

### Pitfalls (Analysis-Specific)
- **Yield vs. Growth**: High yield alone doesn't guarantee returns; always check stability/growth potential.
- **Frequency Confusion**: Distinguish between monthly and quarterly payouts to match user cash-flow needs.
- **Data Source Routing**: Stocks → `stock-analysis` (Yahoo Finance). Professional trading → `longbridge`.

## Pitfalls
- **NEVER fabricate trading data (critical)**: When asked about positions, costs, prices, or orders, you MUST query the actual data from LongBridge API FIRST before doing any calculations. Do NOT guess, assume, or use stale data from memory/user profile. The user will catch fabricated numbers and lose trust. **Always**: `trade_ctx.stock_positions()` → get real `quantity`, `cost_price`, `available_quantity` → then calculate. This applies to cost basis calculations, P&L projections, and sell order sizing. One extra API call is infinitely better than a wrong number.
- **Missing Symbols**: Most quote/candlestick commands require one or more symbols.
- **JSON Output**: Always use the `--json` flag for machine-readable data.
- **Environment Variables**: Ensure `.env` or shell exports are active before running commands.
- **Command Syntax**: Note that `longbridge` uses a sub-command structure (e.g., `longbridge <command> [OPTIONS] <args>`).
- **Token Expiration (401004)**: `LONGBRIDGE_ACCESS_TOKEN` is a **dynamic, time-sensitive token** stored in bashrc (or `.env`). It expires and causes `401004: token invalid` errors. Fix (preferred): run `bash ~/.hermes/scripts/update_longbridge_token.sh NEW_TOKEN` — it auto-updates all locations (bashrc, .env, hermes envs) and verifies both CLI and Python SDK. See `references/token-refresh.md` for full workflow. Never rely on a stale cached token.
- **Freshly-generated token still gets 401004**: If a new token (just copied from App) gets 401004, first decode the JWT to verify `exp` is in the future and `ak` matches the configured APP_KEY (see `references/token-refresh.md` → "JWT Verification"). If the JWT is valid but API rejects it, either: (a) wait 30s and retry (propagation delay), (b) re-generate from App (first generation sometimes doesn't register), or (c) try from Web console at https://open.longportapp.com/ (different token type). Do NOT assume the token is wrong — the JWT structure is verifiable independently of the API.
- **Command Name**: The npm-installed CLI is `longbridge` (not `lonbh`, `longport`, etc.). Verify with `npm list -g | grep longbridge`.
- **Env Var Loading**: Variables in bashrc are not visible to child processes via `env | grep`. Always `source ~/.bashrc` in the same shell session before running commands.
- **Validate Token Before Batch**: Before running multi-ticker queries (especially dividend/quote batch calls), run a single-ticker sanity check first: `longbridge quote --json AAPL`. A 401004 on a 15-ticker batch wastes time diagnosing which tickers are the problem vs. the token being expired.
- **401004 Diagnostic Protocol**: When hitting 401004, first distinguish between these scenarios:
  - **Terminal output shows `...`** → That's the tool's secret masking. Verify with `python3 -c "open('/home/openclaw/.bashrc').read().split('LONGBRIDGE_ACCESS_TOKEN=')[1].split()[0]" | wc -c`. If length ~1053, the token is intact.
  - **Token was never saved** → All files have literal `...` placeholders. Ask user to re-generate.
  - **Token expired** → error 401003. Run `bash ~/.hermes/scripts/update_longbridge_token.sh NEW_TOKEN`.
  - **Fresh token gets 401004** → See pitfall "Freshly-generated token still gets 401004" above.
  Do NOT iterate through config files one by one — run the script which handles all locations in one call.
- **CLI Installation Path**: The `longbridge` CLI is installed via `uv tool install` at `~/.local/bin/longbridge`. It is NOT in `$PATH` by default in all sessions. Use the full path `~/.local/bin/longbridge` or add `export PATH="$HOME/.local/bin:$PATH"` to bashrc. Verify with `which longbridge || ls ~/.local/bin/longbridge`.
- **CLI Token Masking (Critical - Use Python SDK Instead)**: The terminal tool's secret-redaction layer masks/truncates environment variable values containing tokens. This causes the `longbridge` CLI to get corrupted tokens → 401004 (token invalid) or 403201 (signature invalid) errors. **The Python SDK always works** because `execute_code` scripts read bashrc via `open()` and set `os.environ` programmatically, bypassing the terminal layer. **Rule**: For any order/trade/position operation, always use `execute_code` + Python SDK, never `terminal` + CLI. Quote commands may work via CLI but orders will fail.
- **"..." in terminal output ≠ placeholder (critical trap)**: The terminal tool **masks** secrets in both display AND environment variables. When you run `grep LONGBRIDGE_ACCESS_TOKEN ~/.bashrc`, the output shows `m_eyJh...jb-k` even when the actual file has a **complete 1053-char JWT**. This is the tool's secret-redaction layer, NOT file corruption. Never conclude a token is truncated from terminal grep output alone. To verify the file truly has a complete token:
  ```bash
  python3 -c "
  with open('/home/openclaw/.bashrc') as f:
      for line in f:
          if 'LONGBRIDGE_ACCESS_TOKEN' in line and 'export' in line:
              tk = line.strip().split('=', 1)[1]
              print(f'Token length: {len(tk)}')  # Should be ~1053
  "
  ```
  **Trust the user** when they say "变量没有占位符" — they can see the file without masking.
- **Signature Invalid (403201)**: Distinct from 401004 (token expired). Error `403201: signature invalid` means the `LONGBRIDGE_APP_SECRET` (or `LONGPORT_APP_SECRET`) value is wrong, corrupted, or truncated — NOT that the token expired. This commonly happens because of the terminal secret masking above. Fix: use Python SDK instead.
- **HK stock symbols**: Use `.HK` suffix (e.g., `0823.HK`, `0778.HK`). The CLI accepts both `0823.HK` and `HK.0823` formats.
- **Python SDK Env Var Prefix Mismatch**: The CLI uses `LONGBRIDGE_*` env vars, but the Python SDK (`longport`) reads `LONGPORT_*`. When using Python, you must **manually map** the bashrc vars: `os.environ["LONGPORT_APP_KEY"] = config.get("LONGBRIDGE_APP_KEY", "")` etc. See `references/python-sdk.md`.
- **`buy/sell` requires `-y` flag**: Without `-y`, the CLI prompts for confirmation interactively and hangs in scripts/cron. Always `longbridge buy SYM --qty N --price P -y`.
- **Read-only mode by default (LONGBRIDGE_TRADE_ENABLED)**: The CLI defaults to read-only mode. `buy`, `sell`, and `cancel` commands fail with `当前为只读模式，下单/撤单操作已禁用` unless `LONGBRIDGE_TRADE_ENABLED=true` is set. This env var must be exported in `~/.bashrc` alongside the other `LONGBRIDGE_*` vars. Without it, even valid tokens reject order commands. **Fix**: `echo 'export LONGBRIDGE_TRADE_ENABLED=true' >> ~/.bashrc` then `source ~/.bashrc`.
- **Python SDK `submit_order` API quirks**: The enum is `openapi.TimeInForceType` (NOT `TimeInForce`). The function signature is `submit_order(symbol, order_type, side, submitted_quantity, time_in_force, submitted_price=None, ...)` — note `time_in_force` is a **required positional arg** before the optional `submitted_price`. Correct call:
```python
# Enums reference:
# openapi.OutsideRTH: .AnyTime (pre+regular+post), .Overnight, .RTHOnly, .Unknown
# openapi.TimeInForceType: .Day, .GoodTilCanceled, .GoodTilDate, .Unknown
# openapi.OrderType: .LO (limit), .MO (market), .ELO (enhanced limit), .ALO, .AO, .SLO, etc.
# openapi.OrderSide: .Buy, .Sell, .Unknown

resp = trade_ctx.submit_order(
    symbol="RGTI.US",
    order_type=openapi.OrderType.LO,
    side=openapi.OrderSide.Sell,
    submitted_quantity=15,
    time_in_force=openapi.TimeInForceType.GoodTilCanceled,  # GTC = persists until filled/canceled
    submitted_price=21.00,
    outside_rth=openapi.OutsideRTH.AnyTime,  # pre-market + regular + after-hours
)
```
- **`SecurityQuote` attributes vary**: US quotes from `Nasdaq Basic` may lack `turnover_rate`, `amplitude` etc. that HK LV1 provides. Wrap attribute access in try/except or hasattr. **No `change_rate` attribute**: Calculate change manually: `(float(q.last_done) - float(q.prev_close)) / float(q.prev_close) * 100`. Available attributes: `symbol`, `last_done`, `prev_close`, `open`, `high`, `low`, `timestamp`.
- **Period enum uses underscores**: `Period.Min_5` not `Period.Min5`. Full list: `Min_1`, `Min_2`, `Min_3`, `Min_5`, `Min_10`, `Min_15`, `Min_20`, `Min_30`, `Min_45`, `Min_60`, `Min_120`, `Min_180`, `Min_240`, `Day`, `Week`, `Month`, `Quarter`, `Year`.
- **AccountBalance attributes**: Has `buy_power`, `total_cash`, `net_assets`, `max_finance_amount`, `remaining_finance_amount`, `risk_level`, `margin_call`. NO `available_cash` or `free` — use `buy_power` for available buying power. **Confirmed HK LV1 attributes** (2026-06-25): `high`, `last_done`, `low`, `open`, `overnight_quote`, `post_market_quote`, `pre_market_quote`, `prev_close`, `symbol`, `timestamp`. **NO `change_rate`** — compute manually: `(last_done - prev_close) / prev_close * 100`.
- **`Period` enum format**: Use `Period.Min_5` (underscore), NOT `Period.Min5`. Full list: `Min_1`, `Min_2`, `Min_3`, `Min_5`, `Min_10`, `Min_15`, `Min_20`, `Min_30`, `Min_45`, `Min_60`, `Min_120`, `Min_180`, `Min_240`, `Day`, `Week`, `Month`, `Quarter`, `Year`.
- **`SecurityQuote` attributes vary**: US quotes from `Nasdaq Basic` may lack `turnover_rate`, `amplitude` etc. that HK LV1 provides. Wrap attribute access in try/except or hasattr.
- **Position fields**: `available_quantity` (settled, sellable) vs `quantity` (total incl unsettled). For T-trading sell, check `available_quantity` first.
- **Prefer `execute_code` over `terminal` for Python SDK**: The `execute_code` sandbox can access `LONGPORT_*` vars from the host environment, making `Config.from_env()` work reliably. In contrast, `terminal` + `source ~/.bashrc` frequently fails because env vars get masked/truncated by the terminal tool's secret-redaction layer, producing 403201 or 401004 errors. **Workflow**: for single-call quick data, use `execute_code` with inline Python + `Config.from_env()`. For CLI commands, use `terminal` with `source ~/.bashrc && longbridge ...`.
- **China Mainland Geo-Block (Error 602315)**: LongPort API blocks trading from mainland China IPs. Error: `"Due to Mainland China regulatory requirements, you are currently located in Mainland China and cannot perform this action."` (code 602315). Read-only operations (quotes, positions) may still work. **Fix**: Use WireGuard VPN via overseas VPS. On-demand scripts (`wg-trade`, `wg-on/off/status`) route only trading traffic through VPN. Full setup in `longbridge-python-sdk` skill's `references/wireguard-proxy-setup.md`.
- **Period enum names**: LongPort Python SDK uses `Period.Min_5` (not `Period.Min5`), `Period.Min_10`, `Period.Min_15`, etc. Always use underscore format.
- **ONLY CLOSE YOUR OWN POSITIONS (critical)**: Automated trading systems MUST only close positions that were opened by the same system. Track opened positions in a JSON file (e.g., `entries.json`) with `order_id`, `shares`, `entry_price`. On close, verify `order_id` exists before executing. Never close user's manual positions. User explicitly stated: "只有你开仓的的你才能平，不是你开的你不能操作".
