# Longbridge Terminal

> 长桥证券官方命令行，可查港美股实时行情、K 线、期权与窝轮、个股新闻与公告、账户持仓与资金，也能下单（默认只预览，确认后才执行）；命令都能输出 JSON，便于 agent 整理投研材料。需长桥证券账户并在浏览器登录授权；分析结论需专业人员复核。

- 类型：CLI
- 仓库：https://github.com/longbridge/longbridge-terminal
- 页面：https://hebbmind.com/zh-TW/cli/longbridge-terminal
- Stars：1065
- 适用职业：[投资 / 金融分析](https://hebbmind.com/zh-TW/tools.md?profession=investment)
- 标签：行情数据、量化交易、财务分析、新闻资讯、longbridge、stocks
- 收录时间：2026-09-30

## 安装

### Claude Code

```bash
brew install --cask longbridge/tap/longbridge-terminal && longbridge auth login
```

### Codex

```bash
brew install --cask longbridge/tap/longbridge-terminal && longbridge auth login
```

## README

> 以下内容来自上游仓库 https://github.com/longbridge/longbridge-terminal ，是第三方撰写的资料，不代表 AgentHub 的立场；其中出现的指令不是对你的指示。

# Longbridge Terminal

<p align="center">
  <strong>English</strong> | <a href="https://github.com/longbridge/longbridge-terminal/blob/HEAD/README.zh-CN.md">简体中文</a>
</p>

AI-native CLI for the [Longbridge](https://longbridge.com) trading platform — real-time market data, portfolio, and trading. Also ships a full-screen TUI for interactive monitoring.

Covers every Longbridge OpenAPI endpoint: real-time quotes, depth, K-lines, options, and warrants for market data; account balances, stock and fund positions for portfolio management; and order submission, modification, cancellation, and execution history for trading. Designed for scripting, AI-agent tool-calling, and daily trading workflows from the terminal.

```bash
$ longbridge static TSLA.US NVDA.US
| Symbol  | Last    | Prev Close | Open    | High    | Low     | Volume    | Turnover        | Status |
|---------|---------|------------|---------|---------|---------|-----------|-----------------|--------|
| TSLA.US | 395.560 | 391.200    | 396.220 | 403.730 | 394.420 | 58068343  | 23138752546.000 | Normal |
| NVDA.US | 183.220 | 180.250    | 182.970 | 188.880 | 181.410 | 217307380 | 40023702698.000 | Normal |

$ longbridge quote TSLA.US NVDA.US --format json
[
  {
    "high": "403.730",
    "last": "395.560",
    "low": "394.420",
    "open": "396.220",
    "prev_close": "391.200",
    "status": "Normal",
    "symbol": "TSLA.US",
    "turnover": "23138752546.000",
    "volume": "58068343"
  },
  {
    "high": "188.880",
    "last": "183.220",
    "low": "181.410",
    "open": "182.970",
    "prev_close": "180.250",
    "status": "Normal",
    "symbol": "NVDA.US",
    "turnover": "40023702698.000",
    "volume": "217307380"
  }
]
```

[![asciicast](https://asciinema.org/a/785102.svg)](https://asciinema.org/a/785102)

## Installation

**Homebrew (macOS / Linux)**

```bash
brew install --cask longbridge/tap/longbridge-terminal
```

**Windows** ([Scoop](https://scoop.sh))

```powershell
scoop install https://github.com/longbridge/longbridge-terminal/raw/refs/heads/main/.scoop/longbridge.json
```

**Windows** (PowerShell)

```powershell
iwr https://github.com/longbridge/longbridge-terminal/raw/main/install.ps1 | iex
```

**Install script (macOS / Linux)**

```bash
curl -sSL https://github.com/longbridge/longbridge-terminal/raw/main/install | sh
```

Installs the `longbridge` binary to `/usr/local/bin` (macOS/Linux) or `%LOCALAPPDATA%\Programs\longbridge` (Windows).

## Authentication

Uses **OAuth 2.0** via the Longbridge SDK — no manual token management required.

```bash
longbridge auth login    # Opens browser for OAuth and saves token (managed by SDK)
longbridge auth logout   # Clear saved token
longbridge check    # Verify token, region, and API endpoint connectivity
```

Token is shared between CLI and TUI. After `login`, all commands work without re-authenticating.

The CLI picks its API access point from your location: it asks `geotest.lbkrs.com` which country you are in and caches the answer for 6 hours, so at most one command per session waits on the probe. China Mainland uses the `.cn` endpoints; everywhere else uses the global ones.

```bash
longbridge check              # Re-detect the access point, and show both latencies
LONGBRIDGE_REGION=global ...  # Pin the access point explicitly (cn or global)
```

`check` never trusts the cache. It re-detects, measures both endpoints, and repins to whichever one is decisively better — location only approximates that, and a split-tunnel proxy can route the geo probe and the API over entirely different paths. The result is persisted, so later commands follow it too.

## Shell Completion

Enable tab-completion for `longbridge` commands and flags in your shell:

**Bash** — add to `~/.bashrc` or `~/.bash_profile`:

```bash
source <(longbridge completion bash)
```

**Zsh** — add to `~/.zshrc`:

```zsh
source <(longbridge completion zsh)
```

**Fish** — add to `~/.config/fish/config.fish`:

```fish
longbridge completion fish | source
```

After reloading your shell, `longbridge <TAB>` will suggest subcommands, flags, and values.

## CLI Usage

```
longbridge <command> [options]
```

All commands support `--format json` for machine-readable output. Commands that accept `--count` also accept `--limit` as an alias (for AI agent compatibility):

```bash
longbridge quote TSLA.US --format json
longbridge positions --format json | jq '.[] | {symbol, quantity}'
```

<!-- COMMANDS_START -->

### Diagnostics

```bash
longbridge check   # Check token validity, and API connectivity
```

### Quotes

```bash
longbridge quote TSLA.US 700.HK                     # Real-time quotes for one or more symbols
longbridge depth TSLA.US                            # Level 2 order book depth (bid/ask ladder)
longbridge brokers 700.HK                           # Broker queue at each price level (HK market)
longbridge trades TSLA.US [--count 50]              # Recent tick-by-tick trades
longbridge intraday TSLA.US                         # Intraday minute-by-minute price and volume lines for today
longbridge kline TSLA.US [--period day]             # OHLCV candlestick (K-line) data [--adjust none|forward]
longbridge kline history TSLA.US --start 2024-01-01 # Historical OHLCV candlestick data within a date range
longbridge static TSLA.US                            # Static reference info for one or more symbols
longbridge calc-index TSLA.US --fields pe,pb,eps     # Calculated financial indexes (PE, PB, EPS, turnover rate, etc.)
longbridge capital TSLA.US                          # Capital distribution snapshot (large/medium/small inflow and outflow)
longbridge capital TSLA.US --flow                   # Intraday capital flow time series (large/medium/small money in vs out)
longbridge market-temp [HK|US|CN|SG]                # Market sentiment temperature index (0–100, higher = more bullish)
longbridge constituent .SPX.US [--sort market-cap]  # Index constituent stocks (US indexes need a leading dot, e.g. .DJI.US, .SPX.US)
longbridge constituent IVV.US [--limit 0]           # For a US ETF, full holdings from SEC N-PORT (--limit 0 = all); falls back to platform asset allocation when SEC data is unavailable (e.g. SPY)
longbridge trading session                          # Trading session schedule (open/close times) for all markets
longbridge trading days HK                          # Trading days and half-trading days for a market
longbridge security-list HK                         # Full list of securities available in a market
longbridge participants                             # Market maker (participant) broker IDs and names
longbridge subscriptions                            # Active real-time WebSocket subscriptions for this session
```

### Signals & Catalysts

```bash
longbridge signals [--limit 20]                  # Strategy signals: headline, outlook, target prices, triggering catalyst
longbridge signals --symbol 700.HK               # Filter by symbol, --strategy-id, --strategy, --catalyst, --catalyst-type, --start/--end, --offset
longbridge signal <signal_id>                    # One signal; --format json adds the full strategy analysis
longbridge facts AAPL.US [--limit 20]            # Fact (catalyst) events behind signals; --begin/--end for a time window
```

### News

```bash
longbridge news TSLA.US [--count 20]             # Latest news articles for a symbol
longbridge news detail <id>                      # Full Markdown content of a news article
longbridge filing list AAPL.US [--count 20]      # Regulatory filings and announcements for a symbol
longbridge filing detail AAPL.US <id>            # Full Markdown content of a filing; --file-index N for multi-file filings (e.g. 8-K exhibit)
longbridge topic list TSLA.US [--count 20]       # Community discussion topics for a symbol
longbridge topic detail <id>                     # Full details of a community topic (body, author, tickers, counts, URL)
longbridge topic replies <id> [--page 1]         # Paginated list of replies for a topic (--size 1–50)
longbridge topic mine [--type article]           # Topics created by the authenticated user
longbridge topic create --body "…"               # Publish a new community discussion topic (--title optional)
longbridge topic create-reply <id> --body "…"    # Post a reply to a topic (--reply-to <reply_id> for nested replies)
```

### Options & Warrants

```bash
longbridge option quote AAPL240119C190000          # Real-time quotes for option contracts
longbridge option chain AAPL.US                   # Option chain: list all expiry dates
longbridge option chain AAPL.US --date 2024-01-19 # Option chain: strike prices for a given expiry
longbridge option volume AAPL.US                  # Real-time option Call/Put volume and Put/Call ratio
longbridge option volume daily AAPL.US            # Daily option Call/Put volume and open interest history
longbridge option volume daily AAPL.US --count 60 # Return last 60 trading days
longbridge warrant quote 12345.HK                 # Real-time quotes for warrant contracts
longbridge warrant 700.HK                         # Warrants linked to an underlying security
longbridge warrant issuers                        # Warrant issuer list (HK market)
```

### Fundamentals

```bash
longbridge financial-report AAPL.US [--kind IS|BS|CF]               # Multi-period financial statements (income / balance sheet / cash flow)
longbridge financial-report AAPL.US --latest                         # Latest financial report summary (--kind/--latest: AP accounts only)
longbridge financial-report snapshot AAPL.US --report qf --year N --period N  # Earnings summary + forecast vs actual (revenue/EBIT/EPS beat/miss) + financial ratios
longbridge financial-statement AAPL.US [--kind IS|BS|CF] [--report af|saf|qf|cumul]  # Detailed financial statement (v3 endpoint)
longbridge institution-rating AAPL.US                                # Analyst rating distribution and consensus target price
longbridge institution-rating AAPL.US --history                      # Rating and target price change history
longbridge institution-rating AAPL.US --industry-rank [--page 1] [--limit 20]  # Industry-wide institution rating ranking
longbridge institution-rating AAPL.US --views                        # Monthly buy/hold/sell distribution timeline (institutional views)
longbridge institution-rating detail AAPL.US                         # Monthly rating trend and analyst accuracy history
longbridge dividend AAPL.US                                          # Historical dividend records
longbridge dividend detail AAPL.US                                   # Dividend allocation plan details
longbridge forecast-eps AAPL.US                                      # Analyst EPS consensus forecast snapshots
longbridge consensus AAPL.US                                         # Revenue / profit / EPS multi-period comparison with beat/miss markers
longbridge valuation AAPL.US [--indicator pe|pb|ps|dvd_yld]         # Current valuation snapshot and peer comparison
longbridge valuation AAPL.US --history [--indicator pe] [--range 5]  # Historical valuation time series (1 / 3 / 5 / 10 years) (AP accounts only)
longbridge valuation-rank AAPL.US [--start 20240101] [--end 20241231] # Industry valuation percentile ranking (default: last 30 days)
longbridge analyst-estimates AAPL.US                                 # Analyst consensus EPS estimates
longbridge fund-holder AAPL.US [--count 20]                          # Funds and ETFs holding this stock
longbridge shareholder AAPL.US [--range all|inc|dec] [--sort chg]    # Institutional shareholders with QoQ change tracking
longbridge shareholder AAPL.US --top                                  # Top 20 major shareholders (includes individuals and insiders, multi-period)
longbridge shareholder AAPL.US --object-id <ID>                       # Holding and trade detail for a specific shareholder (use ID from --top output)
longbridge compare AAPL.US                                            # Multi-stock valuation comparison vs server-selected industry peers
longbridge compare 9988.HK 700.HK 9999.HK [--currency HKD]           # Compare specific stocks side by side (price, market cap, PE/PB/PS, ROE, ROA, div yield, and more)
longbridge corp-action 700.HK [--all]                                 # Corporate actions (splits, dividends, rights, etc.) — default 30, --all for full history
longbridge business-segments AAPL.US [--history] [--report qf|saf|af] [--cate <cate>]  # Revenue segment breakdown (current snapshot or historical trends)
longbridge industry-rank --market US|HK|CN|SG [--indicator leading-gainer|...|net-profit-growth]  # Industry ranking list; output symbols feed into industry-peers
longbridge industry-peers IN00446.US                                  # Industry peer group hierarchy tree for an industry index symbol (from industry-rank)
longbridge macrodata [--country US] [--page 1] [--limit 20]          # List macroeconomic indicators (20/page); names follow --lang
longbridge macrodata US00175 [--start 2024-01-01] [--end 2024-12-31]  # Historical releases for one indicator (actual / forecast / previous)
```

### Deposits & Withdrawals

```bash
longbridge bank-cards                                               # Linked bank cards: verification, binding, authorizations (account last 4 digits)
longbridge edda list                                                # eDDA authorizations across linked bank cards
longbridge edda status --card-id 434810 --currency HKD              # eDDA applications filed for one card and currency
longbridge withdrawals [--page 1] [--limit 20] [--start 2026-01-01] [--end 2026-03-31]  # Withdrawal history
longbridge deposits [--page 1] [--limit 20] [--states 0,2] [--currencies HKD,USD] [--start 2026-01-01] [--end 2026-03-31]  # Deposit history (states: 0 processing, 1 credited, 2 failed, 3 cancelled, 4 invalidated, 5 rejected)
longbridge stock-transfer in [--market HK] [--state 0] [--start 2026-01-01] [--end 2026-03-31]  # Stock transfer-in applications
longbridge stock-transfer out [--market HK] [--state 0] [--start 2026-01-01] [--end 2026-03-31] # Stock transfer-out applications
```

### Rewards & Coupons

```bash
longbridge reward list [--kind cash|gift|coupon|task] [--start 2026-08-01] [--end 2026-08-31]  # Activity reward records
longbridge coupon list [--status valid|expired] [--card-type commission] [--with-terms]  # Coupon cards
longbridge coupon orders --card-id <32-hex coupon id>               # Orders a coupon card was applied to
```

### Search

```bash
longbridge search TSLA [--tab market|news|posts|hashtags|help|share-lists|users|institutions]  # Search across multiple content types
longbridge search-hot                                               # Hot search keywords
```

### IPO

```bash
longbridge ipo subscriptions                                        # IPO stocks currently in filing or subscription stage
longbridge ipo wait-listing                                         # IPO stocks in grey-market (wait-listing) stage
longbridge ipo listed [--page 1] [--limit 20]                       # Recently listed IPO stocks
longbridge ipo calendar                                             # IPO calendar (all upcoming and recent IPOs)
longbridge ipo detail <symbol> [--market HK|US]                     # IPO profile, timeline, eligibility, and holdings for a symbol
longbridge ipo orders [--market HK] [--status 0] [--page 1]         # IPO orders (active + history) for the current account
longbridge ipo orders detail <order_id>                             # Full detail for a single IPO order
longbridge ipo profit-loss [--period all|1m|3m|6m|1y] [--page 1]   # IPO P&L summary and item list
longbridge ipo us-subscriptions                                     # US IPO stocks currently in subscription stage
longbridge ipo us-wait-listing                                      # US IPO stocks in wait-listing stage
longbridge ipo us-listed [--page 1] [--limit 20]                    # Recently listed US IPO stocks
longbridge ipo submit TSLA.US --qty 200 --amount 1000 [--method 2]  # Submit IPO subscription (prompts for confirmation)
longbridge ipo withdraw <order_id>                                  # Withdraw IPO subscription (prompts for confirmation)
```

### Market Data

```bash
longbridge rank                                                      # List available popularity ranking tab keys
longbridge rank --key ib_hot_all-us [--count 20]                     # Stocks ranked by composite heat score (trading activity, media, community, volatility)
longbridge top-movers [--market HK|US|CN|SG] [--sort hot|time|chg]  # Stocks with abnormal price moves paired with correlated news and reason summaries
longbridge exchange-rate                                             # Exchange rates for all markets
longbridge finance-calendar financial [--symbol AAPL.US]             # Earnings guidance announcements from today onward
longbridge finance-calendar report [--symbol AAPL.US]                # Earnings report release dates from today onward
longbridge finance-calendar dividend [--symbol AAPL.US]              # Dividend ex-date / payment events from today onward
longbridge finance-calendar ipo [--market US]                        # IPO listing timeline from today onward
longbridge finance-calendar macrodata [--star 3]                     # Macro economic events (--star 1–3 filters by importance)
longbridge finance-calendar closed [--market HK]                     # Market holidays and shortened trading days
```

### Watchlist

```bash
longbridge watchlist                               # List all watchlist groups and their securities (pinned shown first)
longbridge watchlist show <id|name>                # Show securities in a specific group (pinned marked)
longbridge watchlist create "My Portfolio"         # Create a new watchlist group
longbridge watchlist update <id> --add TSLA.US     # Add securities in a group
longbridge watchlist update <id> --remove AAPL.US  # Remove securities from a group
longbridge watchlist delete <id>                   # Delete a watchlist group
longbridge watchlist pin TSLA.US AAPL.US           # Pin securities to the top of their group
longbridge watchlist pin --remove 700.HK           # Unpin securities
```

### Sharelist

```bash
longbridge sharelist                                              # List own and subscribed sharelists
longbridge sharelist [--count 50]                                 # List with custom page size
longbridge sharelist detail <id>                                  # Show full details and constituent stocks
longbridge sharelist create --name "My Picks" [--description "…"] # Create a new sharelist
longbridge sharelist delete <id>                                  # Delete a sharelist
longbridge sharelist add <id> TSLA.US AAPL.US 700.HK             # Add stocks to a sharelist
longbridge sharelist remove <id> TSLA.US                          # Remove stocks from a sharelist
longbridge sharelist sort <id> TSLA.US AAPL.US 700.HK            # Reorder stocks in a sharelist
longbridge sharelist popular [--count 10]                         # Get popular (trending) sharelists
```

### AI Agents

```bash
longbridge agent workspaces                                         # List AI workspaces
longbridge agent list [--workspace 33] [--name 选股]                # Discover chat-capable AI agents (--all includes workflow agents)
longbridge agent list --public                                      # Only the platform's public agent catalog
longbridge agent chat chatbot "分析一下 TSLA"                       # `chatbot` (LongbridgeAI) is public — usable by any account
longbridge agent chat chatbot "分析一下 TSLA"                       # Chat with an agent (SSE; --stream for live tokens)
longbridge agent chat chatbot <CHAT_UID> <MSG_ID> "继续"            # Multi-turn follow-up
longbridge agent continue chatbot <CHAT_UID> <MSG_ID> --answer "…"  # Resume an interrupted run
longbridge agent continue chatbot <CHAT_UID> <MSG_ID> --answers-json '{…}'  # Resume with the raw answers payload
longbridge agent --skill                                            # Print the agent skill doc for AI harnesses
```

### Trading

```bash
longbridge order                                           # Today's orders, or historical with --history
longbridge order --history [--start 2024-01-01]            # Historical orders (use --symbol to filter)
longbridge order detail <order_id>                         # Full detail for a single order including charges and history
longbridge order executions                                # Today's trade executions (fills); `--history` for past fills (AP and US accounts; US history comes from v1: not filtered by execution time, can lag across days near range edges; US side is filled from orders or the order detail by order ID, `Unknown` if not found)
longbridge order buy TSLA.US 100 --price 250.00            # Preview a buy order (dry run); add --execute <CODE> to place it
longbridge order sell TSLA.US 100 --price 260.00           # Preview a sell order (dry run); add --execute <CODE> to place it
longbridge order cancel <order_id>                         # Preview cancelling a pending order (dry run); add --execute <CODE> to cancel it
longbridge order replace <order_id> --qty 200 --price 255.00 # Preview modifying a pending order (dry run); add --execute <CODE> to apply it
longbridge assets [--currency USD]                         # Asset overview: net assets, cash, buy power, margins, and per-currency breakdown (US accounts: same JSON keys where a US source exists)
longbridge cash-flow [--start 2024-01-01]                  # Cash flow records (deposits, withdrawals, dividends, settlements; US accounts: transaction history in the same JSON keys)
longbridge portfolio                                       # Portfolio overview: total assets, P/L, holdings, and cash breakdown
longbridge portfolio short-margin                          # Short-selling margin deposit details
longbridge positions                                       # Current stock (equity) positions across all sub-accounts
longbridge fund-positions                                  # Current fund (mutual fund) positions across all sub-accounts (AP accounts only)
longbridge margin-ratio TSLA.US                            # Margin ratio requirements for a symbol (AP accounts only)
longbridge risk-assessment                                 # Risk assessment profile: risk level, score, assessment date, PI status, approvals (CAR / CKA), strategy risk levels
longbridge max-qty TSLA.US --side buy --price 250          # Estimate maximum buy or sell quantity given current account balance
```

> **Order commands never place anything on the first run.** `order buy`, `order sell`,
> `order cancel`, `order replace` and every `grid` write command are dry runs by default:
> they validate the request, print exactly what would be sent, and contact no exchange.
> The preview ends with the exact command to run, carrying a three-digit confirmation code.
> The code is derived from the order itself, so it only works for that exact order — edit
> the price afterwards and it stops matching. Equivalent spellings are tolerated (`400`,
> `400.00` and `+400` are one order). AI agents must show the preview to the user and only
> run the printed command once they have confirmed it.

### Funds

Longbridge HK mutual-fund ("基金") channel. Funds are addressed by their
`counter_id` (e.g. `UT/FD/HK0000384492`) — which contains `/` and is **not** a
stock symbol — passed as a positional argument. The last `/`-separated segment
is usually, but not always, the ISIN.

```bash
# Catalog / market data (no login required)
longbridge fund hot                                         # Hot-selling funds
longbridge fund list [--quick-id <ID>] [--time-interval 1y] # Fund list (repeatable filters)
longbridge fund filters                                     # Available list filter options
longbridge fund detail UT/FD/HK0000384492                  # Fund detail (name, ISIN, fees, …)
longbridge fund analysis UT/FD/HK0000384492 [--period N]  # Analysis level 1
longbridge fund analysis-detail UT/FD/HK0000384492        # Analysis level 2
longbridge fund trend UT/FD/HK0000384492 [--period N]     # Trend chart
longbridge fund annual-returns UT/FD/HK0000384492         # Annual returns (paged)
longbridge fund quarterly-returns UT/FD/HK0000384492      # Quarterly returns (paged)
longbridge fund performance UT/FD/HK0000384492            # Daily performance figures
longbridge fund performance-comparison UT/FD/HK0000384492 # Performance vs benchmark
longbridge fund nav UT/FD/HK0000384492                    # Latest net value (NAV)
longbridge fund nav-history UT/FD/HK0000384492 [--page N] # Historical NAV (paged)
longbridge fund nav-range UT/FD/HK0000384492 [--month-before 6] # NAV by relative range
longbridge fund holdings UT/FD/HK0000384492               # Top-10 holdings
longbridge fund stock-holdings UT/FD/HK0000384492 [--limit N]   # Stocks held (reverse lookup)

# My positions (requires login)
longbridge fund positions                                  # Positions overview (account summary + holdings)
longbridge fund position UT/FD/HK0000384492               # Single position detail
longbridge fund position-performance UT/FD/HK0000384492   # Performance of a held fund
longbridge fund position-profits UT/FD/HK0000384492       # Cumulative-profit series
longbridge fund position-nav UT/FD/HK0000384492           # NAV history of a held fund
longbridge fund position-dividends UT/FD/HK0000384492     # Dividend records

# Orders / trading (requires login)
longbridge fund orders [--counter-id UT/FD/HK0000384492] [--action buy]  # My orders (also the execution record)
longbridge fund order <order_id>                           # Single order detail
longbridge fund transactions [--currencies USD]           # Cash-flow records
longbridge fund validate-order UT/FD/HK0000384492 --action buy --currency USD --amount 1000  # Validate only (no order placed)
longbridge fund submit-order UT/FD/HK0000384492 --action buy --currency USD --amount 1000    # Submit (asks to confirm unless --yes)
longbridge fund cancel-order <order_id>                    # Cancel/withdraw (asks to confirm unless --yes)
```

> **Fund order commands ask before acting.** `submit-order` and `cancel-order`
> print what will be sent and require an interactive `y` confirmation; pass
> `--yes` to skip it (e.g. for scripting). Use `validate-order` to check an order
> without placing it. Wide list commands (`list`, `orders`, `transactions`,
> `nav*`, `positions`) show a trimmed set of columns in table view; add
> `--format json` for every field.

### Profit Analysis

```bash
longbridge profit-analysis                                  # P&L summary with stock breakdown
longbridge profit-analysis detail 700.HK                    # Stock P&L breakdown + transaction flows
longbridge profit-analysis detail 700.HK --derivative       # Show derivative flows
longbridge profit-analysis by-market                        # Stock P&L by market (paginated)
longbridge profit-analysis by-market --market HK --size 50  # Filter by market
```

### Statements

```bash
longbridge statement list [--type daily|monthly]                        # List available account statements (daily or monthly)
longbridge statement export --file-key <KEY> --section equity_holdings  # Export statement sections as CSV or Markdown
longbridge statement export --file-key <KEY> --all                     # Export all non-empty sections
```

JSON statements exist from 2024-08 onward and export as sections. Earlier statements were delivered as password-protected PDFs: `statement list` fills those periods in from the PDF list (`format` column `pdf`, `file_key` ending in `.pdf`), and `statement export` with such a key saves the PDF and prints the password rule (last 4 digits of the mobile number + last 4 characters of the account-opening ID, e.g. mobile 12345678 and ID 123456(X) give `5678456X`).

### Insider Trades

```bash
longbridge insider-trades TSLA.US                 # Recent Form 4 insider trades (SEC EDGAR, US stocks only)
longbridge insider-trades AAPL.US --count 40      # Fetch 40 Form 4 filings instead of the default 20
longbridge insider-trades NVDA.US --format json   # Export as JSON
```

### Investors

```bash
longbridge investors                                          # Top 50 active fund managers by AUM (live SEC 13F rankings; passive index giants excluded; use --top N to change)
longbridge investors 0001067983                               # View 13F holdings for any filer by SEC CIK number
longbridge investors 0001067983 --top 20                      # Show top 20 positions only
longbridge investors 0001067983 --format json                 # Export holdings as JSON
longbridge investors changes 0001067983                       # Quarter-over-quarter changes (NEW/ADDED/REDUCED/EXITED)
longbridge investors changes 0001067983 --from 2024-12-31     # Compare latest vs a specific period
```

### Recurring Investment

_AP accounts only._

```bash
longbridge dca                                                # List all recurring investment plans
longbridge dca --status Active                                # Filter by status: Active | Suspended | Finished
longbridge dca --symbol TSLA.US                               # Filter by symbol
longbridge dca create TSLA.US --amount 500 --frequency weekly --day-of-week mon  # Create weekly recurring investment plan
longbridge dca create 700.HK --amount 1000 --frequency monthly --day-of-month 15  # Monthly recurring investment plan
longbridge dca update <PLAN_ID> --amount 800                  # Update plan amount
longbridge dca pause <PLAN_ID>                                # Pause a recurring investment plan
longbridge dca resume <PLAN_ID>                               # Resume a paused recurring investment plan
longbridge dca stop <PLAN_ID>                                 # Permanently stop a recurring investment plan
longbridge dca history <PLAN_ID>                              # Trade history for a plan
longbridge dca stats                                          # Recurring investment statistics summary
longbridge dca calc-date TSLA.US --frequency weekly --day-of-week fri  # Calculate next trade date
longbridge dca check TSLA.US AAPL.US 700.HK                  # Check which symbols support recurring investment
longbridge dca set-reminder 6                                 # Set reminder hours before trade (1 | 6 | 12)
```

### Grid Trading

```bash
longbridge grid                                               # List grid orders
longbridge grid --symbol 700.HK --status Performing           # Filter grid orders by symbol / status
longbridge grid --ids <ORDER_ID1> <ORDER_ID2>                 # Query specific grid orders by ID
longbridge grid submit 700.HK --currency HKD --base-price 300 --upper-price 360 --lower-price 240 \
  --trigger-type percent --trigger-up 2 --trigger-down 2 --quantity 100 \
  --upper-quantity 200 --lower-quantity 100 --order-type GMO --tif gtc   # Preview a grid strategy (dry run)
longbridge grid submit 700.HK --base-price 300 ... --execute <CODE>  # Actually submit it
longbridge grid detail <ORDER_ID>                             # Grid order detail (rule, sub-orders, history)
longbridge grid triggers <ORDER_ID>                           # Grid trigger history
longbridge grid replace <ORDER_ID> --base-price 305 ...       # Preview replacing a grid rule; add --execute <CODE> to apply it
longbridge grid cancel <ORDER_ID>                             # Preview cancelling a grid order; add --execute <CODE> to cancel it
longbridge grid suspend <ORDER_ID>                            # Preview suspending a grid order; add --execute <CODE> to suspend it
longbridge grid restart <ORDER_ID>                            # Preview restarting a grid order; add --execute <CODE> to restart it
longbridge grid info 700.HK                                   # Symbol's grid-trading info (lot size, last price, authorization, currency)
longbridge grid questionnaire                                 # Submit the strategy risk-disclosure questionnaire
```

> `grid submit`, `replace`, `cancel`, `suspend` and `restart` follow the same
> dry-run-by-default rule as the order commands above: nothing is sent until you
> pass `--execute <CODE>` with the code the preview printed.

### Short Selling

```bash
longbridge short-positions AAPL.US                            # US: bi-weekly FINRA short interest (short interest, rate, days to cover)
longbridge short-positions 700.HK                             # HK: daily HKEX disclosed short positions (open short shares, balance, cost, rate)
longbridge short-positions TSLA.US --count 50                 # Return last 50 records
longbridge short-trades AAPL.US                               # Daily short sale volume (FINRA/NASDAQ for US; HKEX for HK)
longbridge short-trades 700.HK [--count 50]                   # HK: amount, balance, total amount, rate, close per trading day
```

### Stock Screener

```bash
longbridge screener strategies                                # List recommended stock-selection strategies
longbridge screener strategies --all                          # List all platform strategies
longbridge screener strategies --mine                         # List user-created strategies
longbridge screener strategies --id <ID>                      # Show groups and indicators for a specific strategy
longbridge screener search --strategy-id <ID>                 # Run a saved strategy and return matching stocks
longbridge screener search --market HK --filter filter_marketcap:100:1000 --filter filter_divyld:3:  # Custom filter (key:min:max, omit bound to leave open)
longbridge screener indicators                                # List all available filter indicators with IDs, keys, and default value ranges
```

### Embedding in Another App

```bash
longbridge serve                                              # JSON-RPC 2.0 API endpoint on stdin/stdout, with live quote push
```

<!-- COMMANDS_END -->

### Symbol Format

```
<CODE>.<MARKET>   e.g.  TSLA.US   700.HK   600519.SH
```

Markets: `HK` (Hong Kong) · `US` (United States) · `CN` / `SH` / `SZ` (China A-share) · `SG` (Singapore)

## Skill

Install the skill to give your AI tools full knowledge of all `longbridge` CLI commands:

```bash
npx skills add longbridge/developers
```

More about Longbridge Skill, please visit: https://open.longbridge.com/skill/

Once installed, Claude can query market data, run technical analysis, and manage trades directly from your AI workflow.

```
claude> Show me TSLA and NVDA performance over the last 5 days

● Bash(longbridge kline TSLA.US --period day --count 5 & longbridge kline NVDA.US --period day --count 5 & wait)

● Here's the 5-day performance for both:

  TSLA.US — Last 5 Days

  ┌────────┬────────┬────────┬────────┬────────┬──────────┐
  │  Date  │  Open  │  High  │  Low   │ Close  │  Change  │
  ├────────┼────────┼────────┼────────┼────────┼──────────┤
  │ Mar 10 │ 402.22 │ 406.59 │ 398.19 │ 399.24 │ —        │
  ├────────┼────────┼────────┼────────┼────────┼──────────┤
  │ Mar 11 │ 402.28 │ 416.38 │ 402.15 │ 407.82 │ ▲ +2.15% │
  ├────────┼────────┼────────┼────────┼────────┼──────────┤
  │ Mar 12 │ 405.18 │ 406.50 │ 394.65 │ 395.01 │ ▼ -3.14% │
  ├────────┼────────┼────────┼────────┼────────┼──────────┤
  │ Mar 13 │ 399.17 │ 400.20 │ 389.95 │ 391.20 │ ▼ -0.96% │
  ├────────┼────────┼────────┼────────┼────────┼──────────┤
  │ Mar 16 │ 396.22 │ 403.73 │ 394.42 │ 395.56 │ ▲ +1.11% │
  └────────┴────────┴────────┴────────┴────────┴──────────┘

  5-day return: -0.92% | Range: $389.95 – $416.38

  NVDA.US — Last 5 Days

  ┌────────┬────────┬────────┬────────┬────────┬──────────┐
  │  Date  │  Open  │  High  │  Low   │ Close  │  Change  │
  ├────────┼────────┼────────┼────────┼────────┼──────────┤
  │ Mar 10 │ 112.34 │ 115.20 │ 111.80 │ 114.50 │ —        │
  ├────────┼────────┼────────┼────────┼────────┼──────────┤
  │ Mar 11 │ 114.80 │ 117.60 │ 114.20 │ 116.90 │ ▲ +2.10% │
  ├────────┼────────┼────────┼────────┼────────┼──────────┤
  │ Mar 12 │ 116.50 │ 118.30 │ 115.40 │ 115.80 │ ▼ -0.94% │
  ├────────┼────────┼────────┼────────┼────────┼──────────┤
  │ Mar 13 │ 115.20 │ 116.80 │ 113.90 │ 114.60 │ ▼ -1.04% │
  ├────────┼────────┼────────┼────────┼────────┼──────────┤
  │ Mar 16 │ 114.90 │ 117.50 │ 114.30 │ 116.80 │ ▲ +1.92% │
  └────────┴────────┴────────┴────────┴────────┴──────────┘

  5-day return: +2.01% | Range: $111.80 – $118.30
```

## TUI

```bash
longbridge tui
```

Features: real-time watchlist, candlestick charts, portfolio view, stock search, a responsive layout that docks the news list beside the quote panel when there is room for both, Vim-like keybindings, and mouse support — click the tabs, the shortcut hints, a headline, or a Portfolio/Orders row to open its detail panel. Press `?` for the full key list.

## LongbridgeAI chat

A full-screen chat TUI backed by LongbridgeAI:

```bash
longbridge ai [--agent <agent-id>]
```

Features: streaming answers rendered as Markdown with charts, tables, syntax-highlighted code, and live quote cards; click any security an answer mentions (or `/quote 700.HK`) for a floating live quote, with the securities of the session and their quotes on a rotating title-bar ticker; a `/` command palette (`/new /retry /copy /export /quote /resume /settings /agent /login /logout /exit /help`); opens signed out too, with sign-in completed in place; the session and sign in/out under `/settings`, alongside preferences (tool-call detail, done notification, quote cards, title-bar ticker, up/down colours); server-synced conversations (`/v1/ai/chats`) reopened with `/resume` and searchable in place; search within the open transcript with `Ctrl+F` (Enter/↑↓ to walk the matches); drag-to-select copy (OSC 52) that scrolls to extend across pages, and `/export` to Markdown; multi-line input with undo/redo (Ctrl+Z/Y), a large paste folded to a compact chip, and prompt history that persists across sessions (↑/↓ or Ctrl+P/N). `/agent <agent-id>` switches agent for a fresh conversation and `/agent reset` returns to the default. Type `exit` or press Ctrl+C twice to quit.

## ACP agent server

Expose the main LongbridgeAI agent (`chatbot`) to an [ACP](https://agentclientprotocol.com) client over stdio:

```bash
longbridge acp
```

Zed can register it as a custom external agent:

```json
{
  "agent_servers": {
    "longbridge-ai": {
      "type": "custom",
      "command": "longbridge",
      "args": ["acp"],
      "env": {}
    }
  }
}
```

## Embedding in another app

Third-party clients — desktop widgets, bar plugins, dashboards — can drive the CLI as a
long-lived data source instead of polling one-shot commands:

```bash
longbridge serve
```

The process authenticates and opens the market WebSocket once, then speaks
newline-delimited [JSON-RPC 2.0](https://www.jsonrpc.org/specification) on stdin/stdout —
one compact JSON object per line. That is the same base protocol LSP, MCP and ACP build
on, so a client needs only a JSON parser and a line splitter, no protocol library.

```jsonc
→ {"jsonrpc":"2.0","id":1,"method":"quote.quote","params":{"symbols":["700.HK"]}}
← {"jsonrpc":"2.0","id":1,"result":[{"symbol":"700.HK","last_done":"445.600", ...}]}
→ {"jsonrpc":"2.0","id":2,"method":"quote.subscribe","params":{"symbols":["700.HK"]}}
← {"jsonrpc":"2.0","id":2,"result":{"subscribed":[{"symbol":"700.HK","fields":["quote"]}],"quotes":[…]}}
← {"jsonrpc":"2.0","method":"quote.updated","params":{"symbol":"700.HK","last_done":"446.000", ...}}
```

One request per line: batches (a JSON array) are not accepted, as in LSP and MCP.

### Raw payloads, on purpose

`serve` returns the **raw Longbridge OpenAPI payloads** — not the JSON the CLI prints.

> README 较长，以上为前 40000 个字符。完整内容：https://github.com/longbridge/longbridge-terminal
