| HTTP Method | GET |
| HTTP URL | /v1/ai/agents |
| HTTP Method | POST |
| HTTP URL | /v1/ai/agents/:id/conversations/:chat_uid/messages/:message_id/continue |
| HTTP Method | POST |
| HTTP URL | /v1/ai/agents/:id/conversations |
| HTTP Method | GET |
| HTTP URL | /v1/ai/workspaces/:id/agents |
| HTTP Method | GET |
| HTTP URL | /v1/ai/workspaces |
Square icon for avatar-style placements, such as GitHub Avatar or Twitter Avatar.
Square icon for avatar-style placements on dark backgrounds, such as GitHub Avatar or Twitter Avatar.
Longbridge Developers logo, dark variant.
Longbridge Developers logo, light variant.
Longbridge logo, light variant.
Longbridge logo, dark variant.
## Before you start
Sign in once — every CLI command shares the same session:
```bash
longbridge auth login
```
You can also start `longbridge ai` while signed out and run `/login` from inside the chat: it opens
your browser to authorize the terminal (the URL is copied to the clipboard too, in case the browser
does not open).
## The screen
| Area | What it shows |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Title bar | The brand badge, a **Sessions** button, the conversation title, and a **ticker** of every security this chat has mentioned with its live quote |
| Transcript | Your questions and the streamed answers, plus tool activity and references |
| Prompt | A multi-line editor; `/` opens the command palette, which hangs off the prompt box |
| Status row | Streaming spinner while a turn runs, `▲ Scrolled up` when you have scrolled back, and one-line confirmations (`Copied to clipboard.`, `Exported to …`) |
Click a security — in the ticker, or where an answer mentions it — to open its **quote card**:
last price and change with an intraday sparkline, O/H/L, previous close, volume and turnover,
average price, amplitude, turnover rate, volume ratio, PE (TTM), PB, market cap, EPS, and net assets
per share. `←`/`→` (or the `[<]` / `[>]` buttons) step through the other securities in the
conversation, and **More ↗** opens the security on longbridge.com.

## Asking questions
Type a question and press `Enter`. `Shift+Enter` inserts a newline, and pasted multi-line text is
inserted whole rather than submitted line by line.
```text
How is TQQQ doing this year?
How did my portfolio do today?
What is the outlook for the Hang Seng Index?
Compare NVDA.US and AMD.US on revenue growth and margins
Summarize Tesla's latest quarterly filing
```
While an answer is streaming, `Esc` cancels it. `Esc` on an idle screen clears the input — it never
quits.
### Suggested follow-ups and references
An answer can come back with source references and suggested follow-up questions. Click a follow-up,
or press `Alt+1` … `Alt+9`, to send it as your next question. References list where the answer's
facts came from.
### Questions the agent asks you
Some tasks need your input before the agent can continue. LongbridgeAI can raise three kinds of
prompt in the transcript:
- **A question with options** — click an option to answer. `X` skips the question; `Esc` lets you
type a free-text answer instead.
- **A multi-select question** — toggle several options, then **Confirm selection**.
- **An authorization request** — `Allow` or `Decline` before the agent runs the action.
Cancelling the turn drops the pending question; starting a new conversation clears it.
## Slash commands
Press `/` for the command palette — `↑`/`↓` to move, `Enter`, `Tab`, or a click to run. Typing a
prefix filters the list.
| Command | What it does |
| ------------------------------------ | ------------------------------------------------------------------- |
| `/new` (`/clear`) | Start a new chat |
| `/retry` (`/regenerate`) | Regenerate the last answer |
| `/copy` | Copy the last answer to the clipboard |
| `/export` | Export the conversation to a Markdown file |
| `/quote [SYMBOL]` | Open a live quote — for the given symbol, or the last one mentioned |
| `/resume` | Open saved conversations and resume one |
| `/settings` | Open Settings |
| `/agent ` | Historical releases for one indicator |
## Examples
### List all indicators
```bash
longbridge macrodata
```
```
Total: 441
Code Name Category Country Frequency Source
61744 Non-Farm Payroll Employment US Monthly Bureau of Labor Statistics
...
```
### Filter by country
```bash
longbridge macrodata --country US
longbridge macrodata --country HK
longbridge macrodata --country CN
```
Supported country codes: `HK`, `CN`, `US`, `EU`, `JP`, `SG`.
### Search by keyword
```bash
longbridge macrodata --keyword CPI
longbridge macrodata --keyword CPI --country US
```
### Paginate the list
```bash
longbridge macrodata --country US --limit 50 --page 2
```
### Historical releases for a specific indicator
```bash
longbridge macrodata 61744
```
```
Non-Farm Payroll [Employment | Bureau of Labor Statistics · Monthly]
Period Actual Forecast Previous Revised Unit
2026-05-01 272000 250000 265000 263500 Thousand
2026-04-01 228000 137000 228000 228000 Thousand
...
```
### Filter history by date range
```bash
longbridge macrodata 61744 --start 2024-01-01 --end 2024-12-31
```
### JSON output for AI / scripting
```bash
# List as JSON
longbridge macrodata --format json
# History as JSON
longbridge macrodata 61744 --format json
```
**List JSON structure:**
```json
{
"count": 619,
"page": 1,
"limit": 20,
"has_more": true,
"list": [
{
"indicator_code": "61744",
"country": "US",
"name": "Non-Farm Payroll",
"periodicity": "Monthly",
"importance": 3
}
]
}
```
**History JSON structure:**
```json
{
"count": 24,
"page": 1,
"limit": 20,
"has_more": true,
"info": {
"indicator_code": "61744",
"country": "US",
"name": "Non-Farm Payroll",
"periodicity": "Monthly",
"importance": 3
},
"data": [
{
"period": "2026-05-01",
"release_at": 1781094600,
"actual_value": "272000",
"previous_value": "265000",
"forecast_value": "250000",
"unit": "Thousand"
}
]
}
```
:::tip
`actual_value` is empty when the data has not yet been released (only `forecast_value` is available). `has_more: true` means additional pages exist — use `--page` to paginate.
:::
## Options
| Option | Description | Default |
| ------ | ----------- | ------- |
| `--country` | Filter list: `HK` \| `CN` \| `US` \| `EU` \| `JP` \| `SG` | All |
| `--keyword` | Server-side keyword search on indicator name (list mode only) | — |
| `--start` | History start date `YYYY-MM-DD` | — |
| `--end` | History end date `YYYY-MM-DD` | — |
| `--lang` | Language for names/descriptions: `zh-CN` \| `en` | — |
| `--limit` | Max records per page (list: max 1000, history: max 100) | 20 |
| `--page` | Page number, 1-based | 1 |
| `--format` | `table` or `json` | `table` |
---
# operating
URL: https://open.longbridge.com/docs/cli/fundamentals/operating.md
# longbridge operating
View a company's operating reviews — key financial indicators and management commentary by report period.
:::info
This command only supports Hong Kong stocks.
:::
## Basic Usage
```bash
longbridge operating 700.HK
```
```
Currency: HKD
| period | revenue | revenue_yoy | net_income | net_income_yoy | eps | eps_yoy |
|--------|----------|-------------|------------|----------------|-------|---------|
| af * | 821.7B | 14.96% | 245.7B | 16.98% | 26.4 | 19.04% |
| q3 | 605.6B | 13.98% | 181.1B | 16.41% | 19.47 | 18.88% |
| saf | 394.7B | 14.07% | 112.0B | 15.95% | 12.05 | 19.04% |
| q1 | 192.8B | 11.53% | 51.2B | 12.81% | 5.49 | 15.55% |
...
```
## Examples
### View operating review
```bash
longbridge operating 700.HK
longbridge operating 9988.HK
```
Displays financial indicator tables and management review summaries.
### Filter by report period
```bash
# Annual report
longbridge operating 700.HK --report af
# Q1 report
longbridge operating 700.HK --report q1
```
Supported report types: `af` (annual), `saf` (semi-annual), `q1` (Q1), `q3` (Q3). Multiple types can be comma-separated.
### JSON output
```bash
longbridge operating 700.HK --format json
```
---
# valuation
URL: https://open.longbridge.com/docs/cli/fundamentals/valuation.md
# longbridge valuation
Analyze a stock's current valuation (P/E, P/B, P/S, dividend yield) with 5-year historical context and industry peer comparison, or track how valuation has changed over time.
## Basic Usage
```bash
longbridge valuation TSLA.US --indicator pe
```
```
Overview:
| indicator | current | high | low | median | industry_median | date |
|-----------|---------|--------|-------|--------|-----------------|------------|
| PE | 341.83x | 284.01 | 51.31 | 96.85 | -0.11 | 2026-04-09 |
Current P/E 341.83, above fair range, cheaper than 8.85% of last 5 years, industry rank 19/49
Peers (5):
| name | pe |
|-------|--------|
| TSLA | 341.83 |
...
```
## Examples
### Current valuation snapshot
```bash
longbridge valuation TSLA.US
```
Shows current P/E, P/B, P/S, and dividend yield alongside the 5-year historical range and where the current value sits within that range. Includes industry peer rank.
### Historical P/E chart
```bash
longbridge valuation TSLA.US --history --indicator pe --range 5
```
Returns a 5-year time series of Tesla's P/E ratio. Use `--range` to set the lookback window: `1`, `3`, `5`, or `10` years.
### Compare P/B over time
```bash
longbridge valuation 700.HK --history --indicator pb
```
Tracks Tencent's price-to-book ratio over time. Supported indicators for `--history` mode: `pe`, `pb`, `ps`, `dvd_yld`.
### JSON for monitoring
```bash
# Export historical P/B data as JSON for scripting or monitoring pipelines
longbridge valuation TSLA.US --history --indicator pb --format json
```
```json
{
"metrics": {
"pb": {
"desc": "current P/B 15.79, in reasonable range, cheaper than 50.31% of last 5 years, industry rank 35/49",
"high": "24.35",
"list": [
{ "timestamp": "1619841600", "value": "26.87" },
{ "timestamp": "1622520000", "value": "24.53" }
]
}
}
}
```
The `desc` field provides a human-readable summary of how the current valuation compares to historical range and industry peers. The `list` array contains the time series data points.
---
# valuation-rank
URL: https://open.longbridge.com/docs/cli/fundamentals/valuation-rank.md
# longbridge valuation-rank
Track a stock's daily PE/PB/PS valuation percentile rank within its industry over a date range.
## Basic Usage
```bash
longbridge valuation-rank TSLA.US
```
```
(day)
Date PE PB PS Div
────────────────────────────────────────────────────
2026-04-08 19/49 35/49 37/49 -
2026-04-09 19/49 35/49 37/49 -
2026-04-10 19/49 35/49 36/49 -
...
```
Each column shows `rank/total` — for example `19/49` means the stock ranks 19th out of 49 peers for that metric on that day.
## Examples
### Default (1 year)
```bash
longbridge valuation-rank TSLA.US
longbridge valuation-rank AAPL.US
```
Returns daily valuation ranks for the past year (PE, PB, PS, dividend yield).
### Custom date range
```bash
longbridge valuation-rank TSLA.US --start 20250101 --end 20251231
longbridge valuation-rank 700.HK --start 20240101 --end 20241231
```
Date format is `YYYYMMDD`.
### JSON output
```bash
longbridge valuation-rank TSLA.US --format json
```
Returns the same rank data as a JSON array, suitable for scripting or further analysis.
---
# Longbridge CLI
URL: https://open.longbridge.com/docs/cli.md
# Longbridge CLI
Longbridge CLI (`longbridge`) is an AI-native command-line tool with 130+ commands covering every
Longbridge OpenAPI endpoint — [real-time market data](https://longbridge.com/markets), fundamentals, account management, and trading.
Designed for scripting, [AI-agent tool](https://longbridge.com/hk/longbridge-ai)-calling, and daily workflows from the terminal.
**GitHub:** [longbridge/longbridge-terminal](https://github.com/longbridge/longbridge-terminal)
## Quick Start
See [Installation](/docs/cli/install) for platform-specific install instructions and authentication setup. After installing, try any command:
```bash
# Check real-time price
longbridge quote TSLA.US NVDA.US
# View your portfolio
longbridge portfolio
# Get JSON output for scripting or AI agents
longbridge quote AAPL.US --format json
# Chat with LongbridgeAI in a full-screen TUI
longbridge ai
```
## JSON Output
Every command supports `--format json` for machine-readable output. Use it for scripting,
piping into `jq`, or feeding data to [AI agents](https://longbridge.com/en/ai):
```bash
longbridge positions --format json
longbridge quote TSLA.US NVDA.US --format json
```
## Symbol Format
Symbols use `CODE.MARKET` format:
| Example | Market |
| ------------ | ---------------------------- |
| `TSLA.US` | US stocks |
| `700.HK` | Hong Kong |
| `600519.SH` | China A-share (Shanghai) |
| `000568.SZ` | China A-share (Shenzhen) |
| `D05.SG` | Singapore |
| `BTCUSD.HAS` | Crypto (Longbridge-specific) |
---
# Installation
URL: https://open.longbridge.com/docs/cli/install.md
# Installation
Install the CLI and authenticate with your [Longbridge account](https://longbridge.com/hk/download).
Source code and release binaries: [longbridge/longbridge-terminal](https://github.com/longbridge/longbridge-terminal){target="_blank"}
## Install
```bash
brew install --cask longbridge/tap/longbridge-terminal
```
```bash
curl -sSL https://open.longbridge.com/longbridge/longbridge-terminal/install | sh
```
```powershell
scoop install https://open.longbridge.com/longbridge/longbridge-terminal/longbridge.json
```
```powershell
iwr https://open.longbridge.com/longbridge/longbridge-terminal/install.ps1 | iex
```
## auth
Manage authentication — login, logout, and check token status.
### auth login
Authenticate via OAuth 2.0 device authorization flow — works in any environment including SSH
and headless servers.
```bash
longbridge auth login
```
Running `auth login` prints a URL and a short code. Open the URL in any browser, enter the code,
and authorize. The token is saved to `~/.longbridge/openapi/tokens/` and reused
automatically by all subsequent commands.
If no browser is available, generate an [Agent Auth Code](/docs/agent-auth) at
[https://open.longbridge.com/connect](https://open.longbridge.com/connect) and redeem it directly:
```bash
longbridge auth login --auth-code 6vYzXq3WbKp9TmHd
```
### auth logout
Clears the stored OAuth token. The next command or TUI launch will trigger re-authentication.
```bash
longbridge auth logout
```
### auth status
Shows token validity locally — no network required. Displays expiry time, login time, account
info, and current quote level.
```bash
longbridge auth status
longbridge auth status --format json
```
## check
Verifies token validity and API connectivity. Shows token status, cached region, and latency
to both Global and CN API endpoints. Does not require an active market session.
```bash
longbridge check
longbridge check --format json
```
## update
Downloads and runs the official install script to replace the current binary with the latest
release.
```bash
longbridge update
```
---
# ipo
URL: https://open.longbridge.com/docs/cli/ipo.md
# longbridge ipo
Track IPO listings, manage subscriptions, and review your IPO order history and profit/loss.
## Subcommands
| Subcommand | Description |
|---|---|
| `subscriptions` | HK IPOs currently in filing or subscription stage |
| `wait-listing` | HK IPOs in wait-listing (grey market) stage |
| `listed` | Recently listed HK IPOs |
| `calendar` | Full IPO calendar (HK + US) |
| `detail` | Profile and timeline for a specific IPO symbol |
| `orders` | Your IPO order history |
| `profit-loss` | Your IPO profit/loss summary |
| `us-subscriptions` | US IPOs currently in subscription stage |
| `us-wait-listing` | US IPOs in wait-listing stage |
| `us-listed` | Recently listed US IPOs |
## Examples
### IPO calendar
```bash
longbridge ipo calendar
```
```
── HK ──
| name | symbol | state | sub_date | sub_end_date | ipo_date |
|-----------------|---------|---------|------------|--------------|------------|
| ROBOTPHOENIX | 6871.HK | pending | 2026-05-07 | 2026-05-13 | 2026-05-17 |
| IMPACT THERAP-B | 7630.HK | pending | 2026-05-04 | 2026-05-08 | 2026-05-12 |
── US ──
| name | symbol | state | ipo_date |
|----------------------------|---------|---------|------------|
| Odyssey Therapeutics, Inc. | ODTX.US | pending | 2026-05-08 |
```
Shows the upcoming IPO schedule across HK and US markets.
### Active subscriptions
```bash
longbridge ipo subscriptions
```
Lists HK IPOs currently open for subscription, including entrance fee, estimated subscription amount, financing rate, and max leverage.
### Wait-listing (grey market)
```bash
longbridge ipo wait-listing
```
Lists HK IPOs that have closed subscription and are waiting for listing, with the indicative issue price range.
### Recently listed
```bash
longbridge ipo listed
```
Shows recently listed IPOs with issue price, last price, and performance since IPO.
### IPO detail
```bash
longbridge ipo detail 6871.HK
```
Shows the full IPO profile and listing timeline for a specific symbol.
### Your IPO orders
```bash
longbridge ipo orders
# Filter by status: 0=all, 1=subscribed, 2=debit-failed, 3=not-won, 4=won, 5=cancelled
longbridge ipo orders --status 4
# View detail for a specific order
longbridge ipo orders detail 2452504
```
Lists your active and historical IPO subscription orders. Use `orders detail ` for full order details.
### Profit/loss summary
```bash
longbridge ipo profit-loss
# Filter by period: 1m | 3m | 6m | 1y | all
longbridge ipo profit-loss --period 1y
```
Shows your IPO subscription profit/loss summary and per-stock breakdown for a given period.
## Requirements
OAuth account permission required for `orders` and `profit-loss`. See the [account permission setup](/docs/trade/trade-overview) guide.
---
# ah-premium
URL: https://open.longbridge.com/docs/cli/market-data/ah-premium.md
# longbridge ah-premium
View the A/H premium ratio for dual-listed stocks — K-line history or intraday timeshare data.
## Basic Usage
```bash
longbridge ah-premium 939.HK
```
```
| date | A-share(CNY) | H-share(HKD) | premium | fx_rate |
|------------|--------------|--------------|---------|----------|
| 2025-11-18 | 9.520 | 8.130 | -21.92% | 0.914300 |
| 2025-11-19 | 9.820 | 8.220 | -23.58% | 0.913000 |
| 2025-11-20 | 9.790 | 8.090 | -24.57% | 0.912800 |
...
```
## Examples
### A/H premium K-line
```bash
longbridge ah-premium 939.HK
longbridge ah-premium 1398.HK --kline-type day --count 100
```
Shows daily A/H premium ratio data. Kline types: `1m`, `5m`, `15m`, `30m`, `60m`, `day`, `week`, `month`, `year`.
### Intraday premium data
```bash
longbridge ah-premium intraday 939.HK
longbridge ah-premium intraday 1398.HK
```
Shows intraday timeshare A/H premium ratio data.
### JSON output
```bash
longbridge ah-premium 939.HK --format json
```
## Notes
Only works for HK stocks that are dual-listed on A-share markets (e.g. 939.HK, 1398.HK). If no data is returned, the stock is not dual-listed.
---
# anomaly
URL: https://open.longbridge.com/docs/cli/market-data/anomaly.md
# longbridge anomaly
Detect unusual market movements and quote anomalies — price spikes, volume surges, and other abnormal activity.
## Basic Usage
```bash
longbridge anomaly --market US
```
```
| time | symbol | name | alert | emotion |
|------------|----------|-------------------|---------------|---------|
| 1775850599 | LRCX.US | Lam Research | Large Sell | Bear |
| 1775850599 | VST.US | Vistra | Large Buy | Bull |
| 1775850599 | LPCN.US | Lipocine | Rapid Rise | Bull |
| 1775850598 | C.US | Citigroup | Large Sell | Bear |
...
```
## Examples
### View HK market anomalies
```bash
longbridge anomaly
longbridge anomaly --market HK
```
Default market is HK. Lists recent unusual price and volume movements.
### View US market anomalies
```bash
longbridge anomaly --market US
longbridge anomaly --market US --count 20
```
### Filter by symbol
```bash
longbridge anomaly --market US --symbol TSLA.US
```
### JSON output
```bash
longbridge anomaly --market HK --format json
```
## Notes
Supported markets: `HK`, `US`, `CN`, `SG`. Maximum 100 results per request.
---
# broker-holding
URL: https://open.longbridge.com/docs/cli/market-data/broker-holding.md
:::warning Longbridge HK / SG accounts only
This command is available to Longbridge HK / SG accounts only. It works with any supported symbol, including US stocks.
:::
# longbridge broker-holding
View broker holding positions for HK-listed stocks — top buyers/sellers, full detail list, and daily history per broker.
## Basic Usage
```bash
longbridge broker-holding 700.HK
```
```
Broker Holding Top (updated: 2026.04.10)
Buy:
| broker | parti_no | change(shares) |
|-------------------------------------|----------|----------------|
| ABN AMRO Clearing Hong Kong Limited | B01555 | +1,481,964 |
| Merrill Lynch Far East Limited | B01224 | +1,145,214 |
| UBS Securities Hong Kong Limited | B01161 | +903,134 |
...
Sell:
| broker | parti_no | change(shares) |
|------------------|----------|----------------|
| HSBC | C00019 | -4,325,085 |
...
```
## Examples
### Top broker holdings
```bash
longbridge broker-holding 700.HK
longbridge broker-holding 9988.HK --period rct_5
```
Shows top buying and selling brokers. Period options: `rct_1` (1 day, default), `rct_5` (5 days), `rct_20` (20 days), `rct_60` (60 days).
### Full broker detail list
```bash
longbridge broker-holding detail 700.HK
longbridge broker-holding detail 9988.HK
```
Lists all brokers with their holding positions.
### Daily history for a specific broker
```bash
longbridge broker-holding daily 700.HK --broker B01224
```
Shows daily holding changes for a specific broker identified by participant number.
### JSON output
```bash
longbridge broker-holding 700.HK --format json
```
## Notes
HK market only. US and other markets are not supported.
---
# brokers
URL: https://open.longbridge.com/docs/cli/market-data/brokers.md
# longbridge brokers
See which broker IDs are present at each price level in the HK order book. Useful for identifying institutional order flow.
## Basic Usage
```bash
longbridge brokers 700.HK
```
```
Symbol: 700.HK
Ask Brokers:
| Position | Broker IDs |
|----------|---------------|
| 1 | 3014, 6409 |
| 2 | 7707, 724 |
| 3 | 1142 |
Bid Brokers:
| Position | Broker IDs |
|----------|---------------|
| 1 | 5428, 3423 |
| 2 | 3506, 3507 |
| 3 | 4482, 4483 |
```
## Examples
### View broker distribution
```bash
longbridge brokers 700.HK
longbridge brokers 700.HK --format json
```
Displays each price level in the HK order book along with the broker IDs placing orders at that level.
## Requirements
Level 2 quote subscription required. HK market only. See [Quote Subscriptions](/docs/quote/overview) for subscription options.
## Notes
Use `longbridge participants` to look up broker names by ID. Broker IDs in the `brokers` output map directly to the `broker_id` field in the participants list.
---
# calc-index
URL: https://open.longbridge.com/docs/cli/market-data/calc-index.md
# longbridge calc-index
Compute financial indexes for any symbol — P/E, P/B, dividend yield, turnover rate, options greeks, and more.
## Basic Usage
```bash
longbridge calc-index TSLA.US
```
```
| Symbol | PE TTM | PB | DPS Rate | Turnover Rate | Total Market Value |
|---------|--------|-------|----------|---------------|---------------------|
| TSLA.US | 341.83 | 15.79 | - | 2.21 | 1296915542310.08 |
```
## Examples
### Check P/E and P/B ratios
```bash
longbridge calc-index TSLA.US NVDA.US --fields pe,pb
longbridge calc-index TSLA.US NVDA.US --fields pe,pb --format json
```
Calculates the specified indexes for each symbol. Multiple symbols and multiple indexes can be requested in a single call. Only indexes that have data appear in the JSON output — indexes with no value are omitted.
### Default indexes (PE, PB, dividend yield, turnover rate, market cap)
```bash
longbridge calc-index TSLA.US
```
When `--fields` is omitted, the default set is returned: `pe`, `pb`, `dps_rate`, `turnover_rate`, `mktcap`.
### Options greeks for a derivative
```bash
longbridge calc-index 24760.HK --fields delta,gamma,vega,theta
```
For options and warrants, request greeks directly. Only indexes applicable to the instrument type will appear in the output. Greek values are only meaningful for option/warrant symbols — passing a plain stock symbol returns no greek data.
## Notes
Full list of supported field names:
**General:** `last_done`, `change_value`, `change_rate`, `vol`, `turnover`, `ytd_change_rate`, `turnover_rate`, `mktcap`, `capital_flow`, `amplitude`, `volume_ratio`, `pe`, `pb`, `dps_rate`, `five_day_change_rate`, `ten_day_change_rate`, `half_year_change_rate`, `five_minutes_change_rate`
**Options / Warrants:** `iv`, `delta`, `gamma`, `theta`, `vega`, `rho`, `oi`, `exp`, `strike`, `upper_strike_price`, `lower_strike_price`, `outstanding_qty`, `outstanding_ratio`, `premium`, `itm_otm`, `warrant_delta`, `call_price`, `to_call_price`, `effective_leverage`, `leverage_ratio`, `conversion_ratio`, `balance_point`
Unknown field names are silently ignored — double-check spelling if an expected field is missing from the output.
---
# capital
URL: https://open.longbridge.com/docs/cli/market-data/capital.md
# longbridge capital
Track intraday capital flow — view a snapshot distribution of large/medium/small money (default), or get a minute-by-minute time series with `--flow`.
## Basic Usage
```bash
longbridge capital TSLA.US
```
```
| large_in | medium_in | small_in | large_out | medium_out | small_out |
|------------|-------------|-------------|------------|-------------|-------------|
| 30160.97 | 131976.32 | 134017.99 | 21801.89 | 132803.77 | 124441.20 |
```
## Examples
### Track minute-by-minute large money inflow
```bash
longbridge capital TSLA.US --flow --format json
```
```json
[
{ "inflow": "1100.46", "time": "2026-04-09 13:30:00" },
{ "inflow": "1129.09", "time": "2026-04-09 13:31:00" },
{ "inflow": "1711.27", "time": "2026-04-09 13:32:00" }
]
```
Each bar shows net inflow for that minute. Positive values indicate net buying; negative values indicate net selling.
### Snapshot: large/medium/small money distribution
```bash
longbridge capital TSLA.US --format json
```
```json
{
"capital_in": { "large": "30160.97", "medium": "131976.32", "small": "134017.99" },
"capital_out": { "large": "21801.89", "medium": "132803.77", "small": "124441.20" },
"symbol": "TSLA.US",
"timestamp": "2026-04-09 20:00:00"
}
```
`capital_in` shows total money flowing into the stock broken down by order size (large / medium / small). `capital_out` shows the corresponding outflows. Compare the two to assess whether large institutional money is net buying or selling.
---
# constituent
URL: https://open.longbridge.com/docs/cli/market-data/constituent.md
# longbridge constituent
View constituent stocks of an index or ETF — with sorting options and rise/fall statistics.
## Basic Usage
```bash
longbridge constituent HSI.HK
```
```
Constituents (90 total) Rise: 0 Fall: 0 Flat: 0
| symbol | name | price | prev_close | change% | volume | turnover |
|---------|------------------|---------|------------|---------|-----------|------------|
| 1211.HK | BYD | 110.300 | 105.100 | 0.0495 | 50148879 | 5500136961 |
| 322.HK | Kangshifu | 13.230 | 12.990 | 0.0185 | 11929280 | 156922125 |
| 857.HK | PetroChina | 10.970 | 10.800 | 0.0157 | 96106689 | 1052688828 |
...
```
## Examples
### View index constituents
```bash
longbridge constituent HSI.HK
longbridge constituent DJI.US
```
Lists constituent stocks sorted by change percentage by default, with price and market data.
### Sort by different indicators
```bash
# Sort by turnover
longbridge constituent HSI.HK --sort turnover
# Sort by market cap, ascending
longbridge constituent DJI.US --sort market-cap --order asc
```
Supported sort fields: `change`, `price`, `turnover`, `inflow`, `turnover-rate`, `market-cap`.
### Limit results
```bash
longbridge constituent HSI.HK --limit 10
longbridge constituent SPX.US --limit 20 --sort inflow
```
### View ETF holdings
```bash
longbridge constituent IVV.US
longbridge constituent QQQ.US --limit 20
```
For ETF symbols, `constituent` switches to portfolio holdings instead of index constituents:
- **US ETFs** — the complete portfolio is fetched from SEC EDGAR N-PORT filings by default, with each holding's name, CUSIP, weight, shares, and market value:
```
ETF Holdings — IVV.US (iShares Core S&P 500 ETF)
Source: SEC N-PORT, report period 2026-03-31, filed 2026-05-28, 507 holdings
| # | name | cusip | weight | shares | value(USD) |
|----|----------------|-----------|--------|-------------|----------------|
| 1 | NVIDIA Corp. | 67066G104 | 7.564% | 312,526,688 | 54,504,654,387 |
| 2 | Apple, Inc. | 037833100 | 6.650% | 188,816,321 | 47,919,694,106 |
...
... and 457 more (use --limit 0 for all)
```
- **Other ETFs** (or when SEC data is unavailable, e.g. UIT-structured funds like `SPY.US`) — falls back to the platform's asset-allocation breakdown, shown as four grouped tables: Holdings, Regional, Asset Class, and Industry.
Notes:
- N-PORT data is a fiscal-quarter-end snapshot filed with up to ~60 days' delay — authoritative but not real-time
- `--limit` caps the holdings rows; `--limit 0` shows all; `--sort` / `--order` are ignored for pre-ranked holdings data
- Index symbols (e.g. `HSI.HK`, `.SPX.US`) behave exactly as before
### JSON output
```bash
longbridge constituent HSI.HK --format json
# ETF holdings as structured JSON (full untruncated list)
longbridge constituent IVV.US --format json
```
---
# depth
URL: https://open.longbridge.com/docs/cli/market-data/depth.md
# longbridge depth
View the Level 2 order book for a symbol — the top 10 bid and ask prices with order counts and volumes.
## Basic Usage
```bash
longbridge depth TSLA.US
```
```
Symbol: TSLA.US
Asks (Sell):
| Position | Price | Volume | Orders |
|----------|---------|--------|--------|
| 1 | 344.990 | 200 | 3 |
| 2 | 345.000 | 500 | 8 |
| 3 | 345.010 | 300 | 4 |
Bids (Buy):
| Position | Price | Volume | Orders |
|----------|---------|--------|--------|
| 1 | 344.980 | 400 | 6 |
| 2 | 344.970 | 600 | 9 |
| 3 | 344.960 | 250 | 3 |
```
## Examples
### View the order book
```bash
longbridge depth 700.HK
longbridge depth 700.HK --format json
```
Shows the current bid and ask ladder for 700.HK, including price levels, volume at each level, and order count. Up to 10 levels are returned per side when the market is open.
## Requirements
Level 2 quote subscription required. See [Quote Subscriptions](/docs/quote/overview) for subscription options.
---
# intraday
URL: https://open.longbridge.com/docs/cli/market-data/intraday.md
# longbridge intraday
Get minute-by-minute price and volume data (intraday line) for any symbol — today's live data or a historical date.
## Basic Usage
```bash
longbridge intraday TSLA.US
```
```
| Time | Price | Avg Price | Volume | Turnover |
|---------------------|---------|-----------|---------|----------------|
| 2026-04-09 13:30:00 | 343.150 | 343.150 | 1234567 | 423567890.000 |
| 2026-04-09 13:31:00 | 344.200 | 343.675 | 987654 | 339876540.000 |
| 2026-04-09 13:32:00 | 343.800 | 343.717 | 876543 | 301234560.000 |
...
```
## Examples
### View today's intraday price line
```bash
longbridge intraday TSLA.US
longbridge intraday TSLA.US --format json
```
Outputs one bar per minute from market open to the latest available tick, showing price, average price, volume, and turnover.
### Include pre-market and post-market for US stocks
```bash
longbridge intraday AAPL.US --session all
```
```json
[
{
"avg_price": "258.368439",
"price": "258.330",
"time": "2026-04-09 08:00:00",
"turnover": "97663.270",
"volume": "378"
},
{
"avg_price": "258.382920",
"price": "258.240",
"time": "2026-04-09 08:01:00",
"turnover": "1622133.447",
"volume": "6278"
}
]
```
`--session all` includes pre-market bars starting from approximately 8:00 AM ET, as well as post-market bars after 4:00 PM ET.
### Historical intraday data
```bash
longbridge intraday TSLA.US --date 20260401
longbridge intraday AAPL.US --date 20260401 --format json
```
Use `--date YYYYMMDD` to retrieve intraday data for a past trading date instead of today's live data.
---
# kline
URL: https://open.longbridge.com/docs/cli/market-data/kline.md
# longbridge kline
Fetch candlestick (K-line) data for any symbol. Supports multiple periods and historical date ranges.
## Quota System
Access to historical K-line data is quota-based. Each account has a monthly limit on the number of unique symbols that can be queried. The quota resets at the start of each calendar month; unused quota does not carry over. Querying the same symbol multiple times in a month counts as one use.
For newly funded accounts, the quota takes effect on the next trading day. When total assets or monthly trade count increases to a higher tier, the new quota takes effect on the next trading day.
**Total assets**: combined value of HK, US, and CN securities accounts converted to HKD. Uses the higher of the last trading day of the previous calendar month vs. the most recent complete trading day.
**Monthly trades**: number of orders with at least one fill (partial, multiple, or single fill all count as 1). Uses the higher of last month's vs. current month's fill count.
| Account Tier | Monthly Symbol Limit |
|---|---|
| Account opened | 100 |
| Total assets ≥ HKD 10,000 | 400 |
| Total assets ≥ HKD 80,000 | 600 |
| Total assets ≥ HKD 400,000 or monthly trades > 160 | 1,000 |
| Total assets ≥ HKD 4,000,000 or monthly trades > 1,600 | 2,000 |
| Total assets ≥ HKD 6,000,000 or monthly trades > 2,500 | 3,000 |
## Basic Usage
```bash
longbridge kline TSLA.US --period day --count 3
```
```
| Time | Open | High | Low | Close | Volume | Turnover |
|---------------------|---------|---------|---------|---------|----------|-----------------|
| 2026-04-07 04:00:00 | 346.440 | 348.020 | 337.240 | 346.650 | 74515355 | 25563965746.000 |
| 2026-04-08 04:00:00 | 363.790 | 364.500 | 339.670 | 343.250 | 78838616 | 27457043487.000 |
| 2026-04-09 04:00:00 | 343.150 | 348.880 | 337.250 | 345.620 | 62164016 | 21375312140.000 |
```
## Examples
### Daily candles (last 100 days, default)
```bash
longbridge kline TSLA.US
```
Returns the last 100 daily candles by default, with open, high, low, close, volume, and turnover for each day.
### Intraday candles with different period
```bash
longbridge kline TSLA.US --period 1h --count 48
```
Use `--period` to switch granularity (e.g. `1m`, `5m`, `15m`, `30m`, `1h`, `day`, `week`, `month`, `year`) and `--count` to control how many bars are returned.
### Historical date range
```bash
longbridge kline history TSLA.US --period day --start 2025-01-01 --end 2025-03-31
longbridge kline history TSLA.US --period day --start 2025-01-01 --end 2025-03-31 --format json
```
Use the `history` subcommand with `--start` and `--end` (format: `YYYY-MM-DD`) to fetch candles for a specific date window. `--adjust forward` applies forward-adjusted prices. The `time` field in JSON output represents the candle open time — for US daily candles, this is US Eastern midnight expressed in UTC.
---
# market-status
URL: https://open.longbridge.com/docs/cli/market-data/market-status.md
# longbridge market-status
Check the current open/close status for each exchange.
## Basic Usage
```bash
longbridge market-status
```
```
| market | status |
|--------|------------|
| US | Pre-Market |
| HK | Closed |
| CN | Closed |
| SG | Closed |
```
## Examples
### View all market statuses
```bash
longbridge market-status
longbridge market-status --format json
```
Displays whether each exchange (US, HK, CN, SG, etc.) is currently open, closed, or in a pre/post-market session.
---
# market-temp
URL: https://open.longbridge.com/docs/cli/market-data/market-temp.md
# longbridge market-temp
Get the Longbridge market temperature index — a composite 0–100 sentiment gauge combining valuation and market sentiment. Higher = more bullish.
## Basic Usage
```bash
longbridge market-temp US
```
```
| Field | Value |
|-------------|---------------------------------------|
| Market | US |
| Temperature | 64 |
| Description | Temp Comfortable & Gradually Dropping |
| Valuation | 83 |
| Sentiment | 45 |
```
## Examples
### Current market temperature
```bash
# Hong Kong market
longbridge market-temp HK
# US market
longbridge market-temp US
# China A-shares
longbridge market-temp CN
# JSON output for scripting or monitoring
longbridge market-temp US --format json
```
Supported markets: `HK` (default), `US`, `CN` (aliases: `SH`, `SZ`), `SG`. Running without an argument defaults to `HK`.
### Historical temperature trend
```bash
longbridge market-temp US --history --start 2026-04-01 --end 2026-04-09 --format json
```
```json
[
{ "description": "", "sentiment": "70", "temperature": "67", "time": "2026-04-01 04:00:00", "valuation": "64" },
{ "description": "", "sentiment": "34", "temperature": "50", "time": "2026-04-02 04:00:00", "valuation": "67" },
{ "description": "", "sentiment": "56", "temperature": "61", "time": "2026-04-06 04:00:00", "valuation": "67" }
]
```
Returns one record per trading day over the specified range. Useful for charting sentiment shifts around market events.
---
# participants
URL: https://open.longbridge.com/docs/cli/market-data/participants.md
# longbridge participants
Get the complete broker/participant directory for the HK market — maps broker IDs to firm names, letting you decode the `brokers` command output.
## Basic Usage
```bash
longbridge participants
```
```
| Broker ID | Name EN | Name CN |
|------------|----------------------------------|-------------------------|
| 6596 | WE | WE Securities |
| 3014 | DRW (Hong Kong) Limited | DRW (Hong Kong) Limited |
| 7707, 7708 | Ark Securities (Hong Kong) Ltd | Ark Securities |
| 724 | UTR8 Hong Kong Limited | UTR8 Hong Kong Limited |
| 1142 | Wanhai Securities (HK) Limited | Wanhai Securities (HK) |
| 6409 | Standard Chartered(HK) | Standard Chartered (HK) |
...
```
## Examples
### Look up all broker IDs
```bash
longbridge participants
longbridge participants --format json
```
Returns the full directory of HK exchange participants, each with their broker ID(s) and firm name. Some firms have multiple broker IDs listed together in a single `broker_id` string.
## Notes
HK market only. Use in conjunction with `longbridge brokers` to identify which firms are placing orders at each price level. The `broker_id` values here correspond directly to the IDs returned by the `brokers` command.
---
# quote
URL: https://open.longbridge.com/docs/cli/market-data/quote.md
# longbridge quote
Get real-time quotes for one or more symbols — price, volume, change from previous close, and extended-hours data for US stocks.
## Basic Usage
```bash
longbridge quote TSLA.US NVDA.US
```
```
| Symbol | Last | Prev Close | Open | High | Low | Volume | Turnover | Status |
|---------|---------|------------|---------|---------|---------|-----------|-----------------|--------|
| TSLA.US | 345.620 | 343.250 | 343.150 | 348.880 | 337.250 | 62164016 | 21375312140.000 | Normal |
| NVDA.US | 183.910 | 182.080 | 181.840 | 184.080 | 180.620 | 116428523 | 21303315176.000 | Normal |
Extended Hours:
| Symbol | Session | Last | High | Low | Volume | Prev Close | Time |
|---------|---------|---------|---------|---------|---------|------------|---------------------|
| TSLA.US | Pre | 343.100 | 346.450 | 339.695 | 945393 | 343.250 | 2026-04-09 13:30:00 |
| TSLA.US | Post | 344.930 | 346.260 | 344.820 | 1348872 | 345.620 | 2026-04-09 23:59:59 |
| NVDA.US | Pre | 181.990 | 182.080 | 180.000 | 1116645 | 182.080 | 2026-04-09 13:30:00 |
| NVDA.US | Post | 183.020 | 183.950 | 182.900 | 6021581 | 183.910 | 2026-04-09 23:59:58 |
```
## Examples
### Check a single stock
```bash
longbridge quote TSLA.US
```
Displays the latest price, open, high, low, volume, turnover, and previous close for TSLA.
### Compare multiple symbols across markets
```bash
longbridge quote TSLA.US NVDA.US 700.HK
longbridge quote TSLA.US NVDA.US 700.HK --format json
```
Pass multiple symbols in one call to compare quotes side by side. Symbols from different markets (US, HK, CN) are all supported. US stocks include `pre_market_quote` and `post_market_quote` fields when extended-hours data is available.
### Get pre-market and after-hours data
```bash
# pre_market_quote and post_market_quote fields appear in US stock output
longbridge quote TSLA.US --format json
```
For US stocks, JSON output includes `pre_market_quote` and `post_market_quote` objects when extended-hours data is available. These fields are `null` during regular US market hours.
---
# rank
URL: https://open.longbridge.com/docs/cli/market-data/rank.md
# longbridge rank
LB popularity rankings — a composite score of trading activity, community discussion, watchlist additions, and other signals. Without `--key`, lists all available rank categories. With `--key`, shows the ranked stock list for that category.
## Basic Usage
```bash
longbridge rank
```
```
Ranking Categories (use second-level key with --key)
| key | name | sub-key | market |
|----------------|----------------|-------------------|--------|
| hot_all | Trending Now | hot_all-us | US |
| hot_all | Trending Now | hot_all-hk | HK |
| hot_up | On The Rise | hot_up-us | US |
| hot_up | On The Rise | hot_up-hk | HK |
| trade_heat | Popular Trades | trade_heat-us | US |
| trade_heat | Popular Trades | trade_heat-hk | HK |
| discuss_heat | Hot Topics | discuss_heat-us | US |
| discuss_heat | Hot Topics | discuss_heat-hk | HK |
| discuss_heat | Hot Topics | discuss_heat-cn | CN |
| discuss_heat | Hot Topics | discuss_heat-sg | SG |
| watchlist_heat | Most Followed | watchlist_heat-us | US |
| watchlist_heat | Most Followed | watchlist_heat-hk | HK |
| watchlist_heat | Most Followed | watchlist_heat-cn | CN |
| watchlist_heat | Most Followed | watchlist_heat-sg | SG |
```
## Examples
### View US total heat ranking
```bash
longbridge rank --key hot_all-us
```
```
Rank — hot_all-us
| rank | symbol | name | price | chg% | pre/post | pre/post chg% |
|------|---------|--------|---------|---------|----------|---------------|
| 1 | NVDA.US | NVIDIA | 215.330 | -0.0190 | 214.297 | -0.0048 |
| 2 | AAPL.US | Apple | 205.100 | -0.42% | 204.800 | -0.0015 |
```
### View HK total heat ranking
```bash
longbridge rank --key hot_all-hk
```
### View heat-rising ranking (top 20)
```bash
longbridge rank --key hot_up-us --count 20
```
### List all categories
```bash
longbridge rank
```
Without `--key`, displays a table of all available rank categories and their sub-keys.
### JSON output — with `--key`
```bash
longbridge rank --key hot_all-us --format json
```
```json
{
"bmp": false,
"lists": [
{
"symbol": "NVDA.US",
"name": "NVIDIA",
"last_done": "215.330",
"chg": "-0.0190",
"pre_post_price": "214.297",
"pre_post_chg": "-0.0048",
"inflow": "-750205778"
}
]
}
```
Key JSON fields:
| Field | Description |
|-------|-------------|
| `lists[].symbol` | Symbol in `CODE.MARKET` format |
| `lists[].name` | Stock name |
| `lists[].last_done` | Last traded price |
| `lists[].chg` | Price change ratio (e.g. `-0.0190` = −1.90%) |
| `lists[].pre_post_price` | Pre/post-market price |
| `lists[].pre_post_chg` | Pre/post-market change ratio |
| `lists[].inflow` | Net capital inflow (positive = inflow, negative = outflow) |
### JSON output — without `--key`
```bash
longbridge rank --format json
```
```json
{
"first_tags": [
{
"key": "hot_all",
"name": "Trending Now",
"second_tags": [
{ "key": "hot_all-us", "market": "US", "name": "US Stocks" },
{ "key": "hot_all-hk", "market": "HK", "name": "HK Stocks" }
]
}
]
}
```
## Options
| Flag | Description |
|------|-------------|
| `--key` | Rank category sub-key (from the no-args table, e.g. `hot_all-us`) |
| `--count` | Number of results (default: 20) |
| `--format` | Output format: `table` (default) or `json` |
## Notes
- Rankings are a composite of trading volume, community discussion, watchlist additions, and more — not simply price performance
---
# security-list
URL: https://open.longbridge.com/docs/cli/market-data/security-list.md
# longbridge security-list
List securities available for a given market on Longbridge. Supports US, HK, CN, and SG markets.
## Basic Usage
```bash
longbridge security-list [MARKET] [--page N] [--count N]
```
```
| Symbol | Name |
|----------|----------------------------|
| GDS.US | GDS |
| ZK.US | ZEEKR Intelligent Tech |
| ALTM.US | Arcadium Lithium |
| HE.US | Hawaiian Electric Inds |
| WB.US | Weibo |
...
```
## Examples
### List securities by market
```bash
# Default (US market)
longbridge security-list
# Hong Kong market
longbridge security-list HK
# China A-shares
longbridge security-list CN
# Singapore market
longbridge security-list SG
# JSON output for scripting
longbridge security-list HK --format json
```
### Pagination
```bash
# First page (default: 50 records per page)
longbridge security-list HK
# Second page
longbridge security-list HK --page 2
# Custom page size
longbridge security-list HK --page 1 --count 100
```
Use `--format json` to get a machine-readable list for automating eligibility checks or further processing.
## Notes
This list changes as eligibility is updated — query it fresh rather than relying on a cached copy.
---
# static
URL: https://open.longbridge.com/docs/cli/market-data/static.md
# longbridge static
Get static reference data for any symbol — name, exchange, currency, lot size, shares outstanding, EPS, BPS, and dividend yield.
## Basic Usage
```bash
longbridge static TSLA.US
```
```
| Symbol | Name | Exchange | Currency | Lot Size | Total Shares | Circ. Shares | EPS | EPS TTM | BPS | Dividend |
|---------|-------------|----------|----------|----------|--------------|--------------|--------|---------|--------|----------|
| TSLA.US | Tesla, Inc. | NASD | USD | 1 | 3752431984 | 2812676349 | 1.0111 | 1.0111 | 21.889 | 0 |
```
## Examples
### Look up multiple symbols at once
```bash
longbridge static NVDA.US TSLA.US
longbridge static NVDA.US TSLA.US --format json
```
Returns reference data for all requested symbols in one call. Useful for quick comparison of fundamental attributes.
### Verify a symbol before trading
```bash
longbridge static 700.HK
```
Confirms the symbol is valid and shows its exchange, currency, lot size, and current share count — handy before placing a trade.
---
# subscriptions
URL: https://open.longbridge.com/docs/cli/market-data/subscriptions.md
# longbridge subscriptions
List your current active real-time quote subscriptions.
## Basic Usage
```bash
longbridge subscriptions
```
## Examples
### Check active subscriptions
```bash
longbridge subscriptions
```
Returns all symbols you are currently subscribed to for real-time quote streaming, along with the subscription types (e.g. quote, depth, trades).
### Debug missing push notifications
```bash
# Check what symbols are subscribed in the current session
longbridge subscriptions
```
If a real-time quote feed goes silent, run `subscriptions` to confirm the symbol is still active. Subscriptions are session-scoped — they reset each time you start a new session.
## Notes
Returns an empty list if you have no active subscriptions. Subscriptions are created through the TUI (or programmatically via the OpenAPI SDK). They are session-scoped and reset when you log out or the session expires.
---
# top-movers
URL: https://open.longbridge.com/docs/cli/market-data/top-movers.md
# longbridge top-movers
Stocks whose price movement exceeds their 20-day standard deviation. The system automatically links related news to explain the reason behind each move. Unlike `anomaly` (pure technical signal), `top-movers` focuses on price moves with news context.
## Basic Usage
```bash
longbridge top-movers
```
```
| time | symbol | change% | reason | tags |
|----------------------|---------|---------|-------------------------------|---------------------------|
| 2026-05-22T17:44:45Z | TSLA.US | +3.24% | Volatility exceeds 20-day avg | Automobile Manufacturers |
| 2026-05-22T14:42:36Z | RKLB.US | +11.32% | Volatility exceeds 20-day avg | Aerospace and Defense |
```
## Examples
### View movers across all markets
```bash
longbridge top-movers
```
Omitting `--market` returns movers across all markets.
### View US movers
```bash
longbridge top-movers --market US
```
### View HK movers
```bash
longbridge top-movers --market HK
```
### Sort by time and increase result count
```bash
longbridge top-movers --market US --sort time --count 50
```
### Sort by price change
```bash
longbridge top-movers --market US --sort change
```
### JSON output
```bash
longbridge top-movers --market US --format json
```
```json
{
"events": [
{
"alert_reason": "Volatility exceeds 20-day avg",
"alert_type": 11,
"timestamp": "1779471885",
"stock": {
"symbol": "TSLA.US",
"code": "TSLA",
"market": "US",
"name": "Tesla, Inc.",
"change": "0.0324",
"last_done": "426.010",
"labels": ["Automobile Manufacturers"]
}
}
],
"updated_at": 1779471885
}
```
Key JSON fields:
| Field | Description |
|-------|-------------|
| `events[].timestamp` | Event time as Unix timestamp (seconds) |
| `events[].alert_reason` | Reason for the alert |
| `events[].stock.symbol` | Symbol in `CODE.MARKET` format (e.g. `TSLA.US`) |
| `events[].stock.code` | Stock code (without market suffix) |
| `events[].stock.market` | Market (`US`, `HK`, etc.) |
| `events[].stock.change` | Price change ratio (e.g. `"0.0324"` = +3.24%) |
| `events[].stock.last_done` | Last traded price |
| `events[].stock.labels` | Industry/category tags |
## Options
| Flag | Description |
|------|-------------|
| `--market` | Market: `HK`, `US`, `CN`, `SG`. Optional — omit for all markets. |
| `--sort` | Sort order: `hot` (default), `time`, or `change` |
| `--count` | Number of results (default: 20) |
| `--format` | Output format: `table` (default) or `json` |
## Notes
- `top-movers` links related news, making it useful for understanding the context behind a move; `anomaly` focuses on pure technical signals
- The volatility threshold is based on the 20-day historical standard deviation
---
# trade-stats
URL: https://open.longbridge.com/docs/cli/market-data/trade-stats.md
# longbridge trade-stats
View trade statistics — price distribution by volume for a stock.
## Basic Usage
```bash
longbridge trade-stats 700.HK
```
```
Prev Close: 504.500 Avg Price: 491.63 Trades: 32782
| price | buy(shares) | sell(shares) | neutral(shares) |
|---------|-------------|--------------|-----------------|
| 504.500 | 0 | 0 | 142 |
| 504.000 | 0 | 0 | 15 |
| 503.000 | 700 | 0 | 103 |
| 502.500 | 4,200 | 0 | 0 |
...
```
## Examples
### View trade distribution
```bash
longbridge trade-stats 700.HK
longbridge trade-stats TSLA.US
```
Shows how trading volume is distributed across different price levels.
### JSON output
```bash
longbridge trade-stats AAPL.US --format json
```
---
# trades
URL: https://open.longbridge.com/docs/cli/market-data/trades.md
# longbridge trades
Fetch recent tick-by-tick trade records for a symbol, including price, volume, time, and trade direction.
## Basic Usage
```bash
longbridge trades TSLA.US
```
```
| Time | Price | Volume | Direction | Type |
|---------------------|---------|--------|-----------|------|
| 2026-04-09 23:59:43 | 344.940 | 5 | Down | I |
| 2026-04-09 23:59:43 | 344.940 | 40 | Down | |
| 2026-04-09 23:59:44 | 344.980 | 40 | Up | |
| 2026-04-09 23:59:44 | 344.980 | 5 | Up | I |
| 2026-04-09 23:59:45 | 344.970 | 1 | Down | I |
| 2026-04-09 23:59:52 | 344.975 | 100 | Neutral | |
```
## Examples
### View last 20 trades
```bash
longbridge trades TSLA.US
```
Returns the 20 most recent trades for TSLA, showing price, volume, timestamp, and direction for each tick.
### Get more trades with --count
```bash
longbridge trades TSLA.US --count 50
```
Use `--count` to fetch up to 50 (or more) recent trades in a single call.
### Read buy/sell pressure from trade direction
```bash
# The direction field shows Up, Down, or Neutral relative to the prior trade
longbridge trades TSLA.US --count 50 --format json
```
Each entry includes a `direction` field indicating whether the trade printed above, below, or at the previous price — useful for gauging short-term momentum.
---
# trading
URL: https://open.longbridge.com/docs/cli/market-data/trading.md
# longbridge trading
Look up trading session schedules and trading day calendars for any market.
## Basic Usage
```bash
longbridge trading session
```
```
| Market | Session | Open | Close |
|--------|----------|----------|----------|
| US | Pre | 04:00:00 | 09:30:00 |
| US | Intraday | 09:30:00 | 16:00:00 |
| US | Post | 16:00:00 | 20:00:00 |
| HK | Intraday | 09:30:00 | 12:00:00 |
| HK | Intraday | 13:00:00 | 16:00:00 |
```
## Examples
### View trading hours for all markets
```bash
longbridge trading session --format json
```
```json
[
{
"market": "US",
"sessions": [
{ "close": "9:30:00.0", "open": "4:00:00.0", "session": "Pre" },
{ "close": "16:00:00.0", "open": "9:30:00.0", "session": "Intraday" },
{ "close": "20:00:00.0", "open": "16:00:00.0", "session": "Post" }
]
},
{
"market": "HK",
"sessions": [
{ "close": "12:00:00.0", "open": "9:30:00.0", "session": "Intraday" },
{ "close": "16:00:00.0", "open": "13:00:00.0", "session": "Intraday" }
]
}
]
```
The US market has three sessions (Pre, Intraday, Post). HK has two Intraday blocks separated by a lunch break.
### Get trading calendar for a date range
```bash
longbridge trading days HK --start 2026-04-01 --end 2026-04-10 --format json
```
```json
{
"half_trading_days": [],
"trading_days": ["2026-04-01", "2026-04-02", "2026-04-08", "2026-04-09", "2026-04-10"]
}
```
Returns the list of full trading days and any half-trading days within the range. Public holidays are excluded automatically.
### Check if today is a trading day
```bash
longbridge trading days US
```
Omitting `--start` and `--end` returns today's trading status. If today is a trading day, it appears in the `trading_days` list.
---
# exchange-rate
URL: https://open.longbridge.com/docs/cli/orders/exchange-rate.md
# longbridge exchange-rate
Get current foreign exchange rates for all currency pairs used in your Longbridge account.
## Basic Usage
```bash
longbridge exchange-rate
```
```
| pair | average_rate | bid_rate | offer_rate |
|-----------|--------------|----------|------------|
| HKD → CNH | 1.1465 | 1.1465 | 1.1465 |
| HKD → HKD | 1 | 1 | 1 |
| HKD → USD | 7.7925 | 7.7925 | 7.7925 |
| HKD → CNY | 1.1465 | 1.1465 | 1.1465 |
```
## Examples
### View all exchange rates
```bash
longbridge exchange-rate
longbridge exchange-rate --format json
```
Displays bid, offer, and average rates for all currency pairs available in your account (e.g., HKD/USD, HKD/CNH). All rates are expressed with HKD as the base currency.
## Requirements
No login is required. This command is available without authentication.
---
# grid
URL: https://open.longbridge.com/docs/cli/orders/grid.md
# longbridge grid
Manage grid trading strategy orders from the terminal — submit a grid, inspect running grids and their triggers, and suspend, restart, replace, or cancel them.
## Basic Usage
```bash
# List your grid orders
longbridge grid
```
```
| Order ID | Symbol | Status | Base | Range | Trigger | Qty | Triggers | Currency |
|--------------------|---------|------------|--------|---------------|-----------|-----|----------|----------|
| 764609681686573056 | 700.HK | Performing | 300.00 | 240.00–360.00 | ±2% | 100 | 3 | HKD |
```
## Examples
### Prepare
```bash
# Record the one-time strategy risk-disclosure consent (required before grid trading)
longbridge grid questionnaire
# Show a symbol's grid info: lot size, last price, authorization, currency
longbridge grid info 700.HK
```
### Submit a grid
```bash
# Preview a percent-triggered grid on 700.HK (nothing is sent; prints a confirmation code)
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
# Submit it by re-running the identical command with that code
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 --execute
```
Replace `` with the confirmation code printed by the preview.
### Inspect
```bash
# Filter the list by symbol / status
longbridge grid --symbol 700.HK --status Performing
# Query specific grids by ID
longbridge grid --ids 764609681686573056 764609681686573057
# Grid detail: rule, sub-orders, and lifecycle history
longbridge grid detail 764609681686573056
# Trigger history for a grid
longbridge grid triggers 764609681686573056
```
### Manage a running grid
```bash
# Modify the grid rule (same flags as submit)
longbridge grid replace 764609681686573056 --base-price 305 --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
# Suspend a running grid (kept, can be restarted)
longbridge grid suspend 764609681686573056
# Restart a suspended grid
longbridge grid restart 764609681686573056
# Cancel a grid (permanent)
longbridge grid cancel 764609681686573056
```
## Options
| Option | Description | Default |
| ------ | ----------- | ------- |
| `--symbol` | Filter the list by security symbol (e.g. `700.HK`) | — |
| `--status` | Filter the list by status, comma-joined (e.g. `Performing,Suspended`) | — |
| `--market` | Filter the list by market: `US` \| `HK` \| `CN` \| `SG` | — |
| `--ids` | Query specific grid orders by ID | — |
| `--currency` | Settlement currency for `submit` (e.g. `HKD`) | — |
| `--base-price` / `--upper-price` / `--lower-price` | Grid base price and upper/lower bounds | — |
| `--trigger-type` | Trigger interpretation: `percent` \| `spread` | — |
| `--trigger-up` / `--trigger-down` | Up/down trigger, read as percent or spread per `--trigger-type` | — |
| `--quantity` | Quantity per trigger | — |
| `--upper-quantity` / `--lower-quantity` | Quantity handled at the upper/lower bound | — |
| `--order-type` | Order type applied to both sides: `GMO` \| `GLO` \| `GTG` (`--order-type-up` / `--order-type-down` override) | — |
| `--tif` | Time in force: `day` \| `gtc` \| `gtd` | — |
| `--execute` | Confirmation code printed by the preview of `submit`, `replace`, `cancel`, `suspend` or `restart`; without it nothing is sent | — |
## Requirements
OAuth trade permission is required to submit or manage grid orders. Before your first grid order, run `longbridge grid questionnaire` once to record the strategy risk-disclosure consent (also visible as the authorization flag in `longbridge grid info`). See the [grid trading](/docs/trade/grid/overview) reference for the full rule and field definitions.
## Notes
`submit`, `replace`, `cancel`, `suspend` and `restart` are two-step. Run the command without `--execute` to validate it and print a preview (nothing is sent) ending in a three-digit confirmation code, then re-run the identical command with `--execute` and that code to execute it. The code is single-use, expires in 10 minutes, and stops working if any field changes. The old `--dry-run` flag has been removed because previewing is now the default.
---
# margin-ratio
URL: https://open.longbridge.com/docs/cli/orders/margin-ratio.md
# longbridge margin-ratio
Look up the margin requirements for a symbol — initial, maintenance, and forced liquidation ratios.
## Basic Usage
```bash
longbridge margin-ratio TSLA.US
```
```
| Field | Value |
|--------------------------|---------|
| Symbol | TSLA.US |
| Initial Margin Ratio | 0.35 |
| Maintenance Margin Ratio | 0.33 |
| Forced Liquidation Ratio | 0.25 |
```
## Examples
### Check margin requirements before buying on margin
```bash
longbridge margin-ratio TSLA.US
# Output as JSON for scripting
longbridge margin-ratio TSLA.US --format json
```
Displays the initial margin ratio, maintenance margin ratio, and forced liquidation ratio for the symbol. Use this before placing a margin buy to understand the capital requirements.
### Compare multiple symbols
```bash
longbridge margin-ratio TSLA.US NVDA.US
```
Pass multiple symbols to compare their margin requirements side by side.
## Requirements
OAuth trade or account permission is required to query margin ratios. See [Trade Permissions](/docs/trade/trade-overview) for setup details.
---
# max-qty
URL: https://open.longbridge.com/docs/cli/orders/max-qty.md
# longbridge max-qty
Estimate the maximum quantity you can buy or sell given your current account balance, at a specified price.
## Basic Usage
```bash
longbridge max-qty TSLA.US --side buy --price 340.00
```
```
| Field | Value |
|----------------|---------|
| Symbol | TSLA.US |
| Cash Max Qty | 0 |
| Margin Max Qty | 896 |
```
## Examples
### Max buy quantity at a price
```bash
longbridge max-qty TSLA.US --side buy --price 340.00
# Output as JSON for scripting
longbridge max-qty TSLA.US --side buy --price 340.00 --format json
```
Returns the maximum number of shares you can purchase at the given price, broken down by cash and margin buying power.
### Max sell quantity
```bash
longbridge max-qty TSLA.US --side sell
```
Returns the maximum number of shares you can sell, based on your current holdings.
## Requirements
OAuth trade or account permission is required to query maximum order quantities. See [Trade Permissions](/docs/trade/trade-overview) for setup details.
---
# order
URL: https://open.longbridge.com/docs/cli/orders/order.md
# longbridge order
View your orders and trade executions, or submit buy/sell orders directly from the terminal.
## Basic Usage
```bash
longbridge order
```
```
| Order ID | Symbol | Side | Order Type | Status | Qty | Price | Exec Qty | Exec Price | Created At |
|--------------------|---------|------|------------|---------------|-----|--------|----------|------------|---------------------|
| 701276261045858304 | TSLA.US | Buy | LO | Filled | 10 | 340.00 | 10 | 339.85 | 2026-04-10 09:32:14 |
| 701276261045858305 | NVDA.US | Sell | LO | PartialFilled | 20 | 185.00 | 12 | 185.00 | 2026-04-10 09:45:01 |
| 701276261045858306 | AAPL.US | Buy | MO | New | 5 | - | 0 | - | 2026-04-10 10:01:33 |
```
## Examples
### Place an order
```bash
# Step 1: preview only. Nothing is sent; the preview ends with a confirmation code
longbridge order buy TSLA.US 100 --price 250.00
# Step 2: re-run the identical command with that code to place the order
longbridge order buy TSLA.US 100 --price 250.00 --execute
```
Replace `` with the confirmation code printed by the preview.
### Cancel an open order
```bash
# Preview the cancellation, then re-run with the confirmation code to cancel
longbridge order cancel 701276261045858304
longbridge order cancel 701276261045858304 --execute
```
Only orders in cancellable states (New, PartialFilled, etc.) are accepted.
### Modify an open order
```bash
# Adjust quantity or price on a pending order
longbridge order replace 701276261045858304 --qty 5 --price 350.00
```
`--qty` is required. Omit `--price` to keep the current limit price. Like `buy`, `sell` and `cancel`, `replace` only previews the change until you re-run it with `--execute` and the confirmation code.
## Options
| Option | Description | Default |
| ------ | ----------- | ------- |
| `--execute` | Confirmation code printed by the preview of `buy`, `sell`, `cancel` or `replace`; without it nothing is sent | — |
## Requirements
OAuth trade permission is required to place, cancel, or replace orders. See the [trade permission setup](/docs/trade/trade-overview) guide to enable trading access.
## Notes
`buy`, `sell`, `cancel` and `replace` are two-step. Run the command without `--execute` to print a preview of the exact request (nothing is sent); the preview ends with a three-digit confirmation code. Re-run the identical command with `--execute` and that code to execute it. The code is single-use, expires in 10 minutes, and stops working if any field changes. The legacy `-y` / `--yes` flag is no longer accepted.
---
# Backtest
URL: https://open.longbridge.com/docs/cli/quant/backtest.md
# Backtesting
Use `strategy()` mode to simulate a trading strategy over historical data. The server executes entries and exits, then returns a performance report.
## How It Works
- Declare your script with `strategy()` instead of `indicator()`
- Use `strategy.entry()` and `strategy.close()` (or `strategy.exit()`) to simulate trades
- Use `--format json` to get the full performance report
- Parse the report with `jq`: `.report_json | fromjson`
## Strategy Settings
Common parameters for the `strategy()` declaration and their defaults:
| Parameter | Default | Description |
| --------- | ------- | ----------- |
| `initial_capital` | `1000000` | Starting capital |
| `commission_type` | `CommissionType.Percent` | Commission calculation method |
| `commission_value` | `0` | Commission rate / amount (0 = no commission) |
| `slippage` | `0` | Slippage in ticks per fill |
| `default_qty_type` | `DefaultQtyType.Fixed` | How position size is specified: `DefaultQtyType.Fixed` (contracts), `DefaultQtyType.PercentOfEquity`, `DefaultQtyType.Cash` |
| `default_qty_value` | `1` | Default position size |
| `pyramiding` | `0` | Max simultaneous entries in the same direction (0 = one at a time) |
| `risk_free_rate` | `2` | Annual risk-free rate (%) for Sharpe / Sortino |
Example with custom settings:
```nv
strategy(
"My Strategy",
initial_capital: 50000,
commission_type: CommissionType.Percent,
commission_value: 0.1,
default_qty_type: DefaultQtyType.PercentOfEquity,
default_qty_value: 10
);
```
## EMA Crossover Strategy
Buy when EMA8 crosses above EMA21; sell when it crosses below.
```bash
longbridge quant run NVDA.US \
--start 2025-01-01 --end 2026-04-28 \
--format json \
--script '
strategy("EMA Cross", overlay: true);
let fast = ta.ema(close, 8);
let slow = ta.ema(close, 21);
if ta.cross_over(fast, slow) {
strategy.entry("Long", Direction.Long);
}
if ta.cross_under(fast, slow) {
strategy.close("Long");
}
' | jq '.report_json | fromjson | .performanceAll'
```
```json
{
"netProfit": 4231.00,
"netProfitPercent": 42.31,
"grossProfit": 7850.00,
"grossLoss": 3619.00,
"profitFactor": 2.17,
"buyHoldReturnPercent": 31.20,
"maxDrawdownPercent": -28.15,
"sharpeRatio": 0.87,
"sortinoRatio": 1.24,
"totalClosedTrades": 18,
"percentProfitable": 50.0,
"avgWinningTradePercent": 8.72,
"avgLosingTradePercent": -4.02,
"commissionPaid": 180.00
}
```
## RSI Mean-Reversion Strategy
Buy when RSI drops below 30 (oversold); exit when RSI recovers above 55.
```bash
longbridge quant run AAPL.US \
--start 2025-01-01 --end 2026-04-28 \
--format json \
--script '
strategy("RSI Reversion", overlay: false);
let r = ta.rsi(close, 14);
if ta.cross_under(r, 30.0) {
strategy.entry("Long", Direction.Long);
}
if ta.cross_over(r, 55.0) {
strategy.close("Long");
}
' | jq '.report_json | fromjson | .performanceAll'
```
## Report Reference
Parse the full report object:
```bash
longbridge quant run NVDA.US ... --format json --script '...' \
| jq '.report_json | fromjson'
```
### Top-Level Structure
| Field | Description |
| ----- | ----------- |
| `performanceAll` | Performance metrics across all trades |
| `performanceLong` | Performance metrics for long trades only |
| `performanceShort` | Performance metrics for short trades only |
| `closedTrades` | Array of completed trade records |
| `openTrades` | Array of unrealized positions at backtest end |
| `equityCurve` | Per-bar account equity |
| `drawdownCurve` | Per-bar drawdown from equity peak |
| `buyHoldCurve` | Per-bar buy-and-hold benchmark equity |
| `config` | Strategy configuration snapshot |
### Performance Metrics
`performanceAll`, `performanceLong`, and `performanceShort` share the same shape. Fields marked **all only** are always `0` / `null` in `performanceLong` and `performanceShort` — they reflect the combined equity curve and cannot be split by direction.
**Profit & Loss**
| Field | Description |
| ----- | ----------- |
| `netProfit` | Net profit in account currency |
| `netProfitPercent` | Net profit % of initial capital |
| `grossProfit` | Total profit from winning trades |
| `grossProfitPercent` | Gross profit % |
| `grossLoss` | Total loss from losing trades (positive number) |
| `grossLossPercent` | Gross loss % |
| `profitFactor` | Gross profit ÷ gross loss |
| `buyHoldReturn` | Buy-and-hold return in account currency *(all only)* |
| `buyHoldReturnPercent` | Buy-and-hold return % *(all only)* |
**Drawdown & Runup** *(all only)*
| Field | Description |
| ----- | ----------- |
| `maxDrawdown` | Largest equity drawdown in account currency |
| `maxDrawdownPercent` | Max drawdown % |
| `maxRunup` | Largest equity runup in account currency |
| `maxRunupPercent` | Max runup % |
**Risk-Adjusted Returns** *(all only)*
| Field | Description |
| ----- | ----------- |
| `sharpeRatio` | Annualized Sharpe ratio |
| `sortinoRatio` | Annualized Sortino ratio |
**Trade Statistics**
| Field | Description |
| ----- | ----------- |
| `totalClosedTrades` | Completed trades |
| `totalOpenTrades` | Unrealized positions at end of backtest |
| `numWinningTrades` | Trades with profit > 0 |
| `numLosingTrades` | Trades with profit < 0 |
| `numEvenTrades` | Break-even trades *(all only)* |
| `percentProfitable` | Win rate (0–100) |
**Average Trade**
| Field | Description |
| ----- | ----------- |
| `avgTrade` | Average P&L per trade |
| `avgTradePercent` | Average P&L % per trade |
| `avgWinningTrade` | Average profit of winning trades |
| `avgWinningTradePercent` | Average winning trade profit % |
| `avgLosingTrade` | Average loss of losing trades |
| `avgLosingTradePercent` | Average losing trade loss % |
| `ratioAvgWinLoss` | Avg winning trade ÷ avg losing trade |
| `largestWinningTrade` | Single largest profit |
| `largestWinningTradePercent` | Single largest profit % |
| `largestLosingTrade` | Single largest loss |
| `largestLosingTradePercent` | Single largest loss % |
**Holding Period**
| Field | Description |
| ----- | ----------- |
| `avgBarsInTrades` | Average bars held per trade |
| `avgBarsInWinningTrades` | Average bars held for winning trades |
| `avgBarsInLosingTrades` | Average bars held for losing trades |
**Other**
| Field | Description |
| ----- | ----------- |
| `commissionPaid` | Total commissions paid |
| `maxContractsHeld` | Peak simultaneous contracts held |
| `marginCalls` | Number of margin calls triggered |
### Trade History
Each entry in `closedTrades` is a completed round-trip:
| Field | Description |
| ----- | ----------- |
| `tradeNum` | Trade number (0-based) |
| `entrySide` | `"Long"` or `"Short"` |
| `entryId` | Entry order ID |
| `entryPrice` | Entry fill price |
| `entryTime` | Entry timestamp (Unix ms) |
| `exitId` | Exit order ID |
| `exitPrice` | Exit fill price |
| `exitTime` | Exit timestamp (Unix ms) |
| `quantity` | Contracts / shares traded |
| `profit` | Realized P&L after commission |
| `profitPercent` | Realized P&L % relative to entry value |
| `cumulativeProfit` | Running total P&L including this trade |
| `cumulativeProfitPercent` | Running total P&L % vs. initial capital |
| `maxRunup` / `maxRunupPercent` | Best unrealized gain during the trade |
| `maxDrawdown` / `maxDrawdownPercent` | Worst unrealized loss during the trade |
| `commission` | Total commission for this trade (entry + exit) |
```bash
# Print a trade-by-trade summary
longbridge quant run NVDA.US --start 2025-01-01 --end 2026-04-28 \
--format json --script '...' \
| jq -r '.report_json | fromjson | .closedTrades[]
| "#\(.tradeNum) \(.entrySide) entry=\(.entryPrice) exit=\(.exitPrice) P&L=\(.profitPercent)%"'
```
`openTrades` uses the same shape minus exit fields, and `profit` reflects current unrealized P&L.
### Equity Curves
Three parallel arrays, one value per bar (index 0 = first bar):
| Field | Description |
| ----- | ----------- |
| `equityCurve` | Account equity at bar close |
| `drawdownCurve` | Drawdown from equity peak (always ≥ 0) |
| `buyHoldCurve` | Hypothetical buy-and-hold equity (benchmark) |
```bash
# Final equity
jq '.report_json | fromjson | .equityCurve[-1]'
# Worst drawdown value
jq '.report_json | fromjson | .drawdownCurve | max'
```
### Strategy Config
`config` captures the declared `strategy()` settings:
| Field | Description |
| ----- | ----------- |
| `initialCapital` | Starting account equity |
| `commissionType` | `PerContract`, `PerTrade`, or `PercentOfValue` |
| `commissionValue` | Commission amount |
| `slippage` | Order slippage in ticks |
| `pyramiding` | Max simultaneous entries in the same direction |
| `riskFreeRate` | Annual risk-free rate used for Sharpe/Sortino (%) |
## Table Output (Quick Review)
Without `--format json`, the table shows each plotted series — useful for visually checking signal timing before running a full backtest:
```bash
longbridge quant run NVDA.US \
--start 2025-01-01 --end 2026-04-28 \
--script '
strategy("EMA Cross", overlay: true);
let fast = ta.ema(close, 8);
let slow = ta.ema(close, 21);
plot(fast, "EMA8");
plot(slow, "EMA21");
if ta.cross_over(fast, slow) {
strategy.entry("Long", Direction.Long);
}
if ta.cross_under(fast, slow) {
strategy.close("Long");
}
'
```
---
# quant run
URL: https://open.longbridge.com/docs/cli/quant.md
# longbridge quant run
Run server-side quantitative scripts against historical K-line data. Returns indicator values, backtest performance reports, or binary screening signals.
## Command
```bash
longbridge quant run \
--start YYYY-MM-DD \
--end YYYY-MM-DD \
[--period day|week|1h|30m|15m|5m|1m|month|year]
[--script "..."] # inline script text
[--input '[14,2.0]'] # override input.*() defaults
[--language navi|pine] # `navi` (default), or `pine` for PineScript compatibility
[--format table|json] # table = human chart (default); json = machine
```
Pipe a file instead of using `--script`:
```bash
cat strategy.nv | longbridge quant run TSLA.US --start 2024-01-01 --end 2024-12-31
```
## Script Language — Navi
Scripts are written in **Navi**, the default language for `quant run`. PineScript is also supported for compatibility via `--language pine`.
[navi-lang.org](https://navi-lang.org) is the authoritative reference for Navi's syntax and standard library — look up exact names and signatures there, since the API evolves. Machine-readable versions: [`llms-full.txt`](https://navi-lang.org/llms-full.txt) (everything in one file) and [`llms.txt`](https://navi-lang.org/llms.txt) (per-page index).
### Script Types
Every Navi script must begin with one of these declarations — it determines the execution mode:
| Declaration | Purpose |
| ----------- | ------- |
| `indicator()` | Plot indicators, compute screener signals |
| `strategy()` | Backtest with entry / exit orders |
| `library()` | Export reusable helper functions |
### Core Concepts
**Time series** — every variable is a bar-by-bar stream. `close[1]` is the previous bar's close; `close[N]` goes N bars back. Most `ta.*` outputs are also series.
**Per-bar values and state** — `let` recomputes each bar; `var` initializes once and carries the value across bars:
```nv
var peak: series float = na;
peak = na(peak) ? high : math.max(peak, high);
```
**Inputs** — expose tunable parameters. Named arguments use `:`:
```nv
let len = input.int(14, "Length", minval: 1);
let src = input.source(close, "Source");
let mult = input.float(2.0, "Multiplier");
```
**Collections** — `Array`, `Map`, and `Matrix` are available for advanced per-bar computation.
### Built-in Libraries
Functions are `snake_case`; types and enums are `PascalCase`.
| Namespace | Purpose |
| --------- | ------- |
| `ta.*` | Technical analysis — moving averages, oscillators, bands, crosses |
| `math.*` | Arithmetic and numeric helpers |
| `String` / `Array` / `Map` / `Matrix` | Text and collection types |
| `strategy.*` | Backtest orders and position management |
See the [standard library reference](https://navi-lang.org/api/stdlib/) for the full list of functions and their signatures.
### Outputs
| Expression | Effect |
| ---------- | ------ |
| `plot(series, "name")` | Named series — shown in the results table / sparkline |
| `plot_shape(cond, ...)` | Mark a signal shape on a specific bar |
| `bg_color(cond ? Color.GREEN : na)` | Highlight bar background |
| `strategy.entry("L", Direction.Long)` | Place a backtest long entry |
| `strategy.exit("L", stop: ..., limit: ...)` | Close with stop / take-profit |
### Quick Example
```nv
indicator("MA Cross", overlay: true);
let fast_len = input.int(10, "Fast", minval: 1);
let slow_len = input.int(20, "Slow", minval: 1);
let fast = ta.ema(close, fast_len);
let slow = ta.ema(close, slow_len);
plot(fast, "Fast", color: Color.ORANGE);
plot(slow, "Slow", color: Color.BLUE);
plot_shape(
ta.cross_over(fast, slow),
title: "Buy",
style: Shape.TriangleUp,
location: Location.BelowBar,
color: Color.GREEN
);
plot_shape(
ta.cross_under(fast, slow),
title: "Sell",
style: Shape.TriangleDown,
location: Location.AboveBar,
color: Color.RED
);
```
### Validating scripts locally
Install the [Navi CLI](https://navi-lang.org/docs/install.md) and lint before sending a script to the server — the API reports script errors only as an opaque error code:
```bash
navi lint my_indicator.nv
```
## Output
**Table format** (default) — human-readable chart with sparklines:
```
────────────────────────────────────────────────────────────────────────────────
Series │ Bars│ First│ Last│ Min│ Max Sparkline
────────────────────────────────────────────────────────────────────────────────
MACD │ 80│ +0.00│ +7.55│ -4.04│ +7.55 ⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣀⣀⣠⣴⣶⣿
Signal │ 80│ +0.00│ +5.16│ -2.96│ +5.16 ⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣤⣀⣀⣀⣠⣴⣾
Histogram │ 80│ +0.00│ +2.39│ -1.50│ +3.01 ⣤⣤⣤⣤⣤⣦⣠⣤⣤⣦⣄⣠⣤⣄⣀⣠⣴⣾⣿⣷
────────────────────────────────────────────────────────────────────────────────
3 series · 80 bars
```
**JSON format** — for scripting and backtests:
```bash
cat strategy.nv | longbridge quant run NVDA.US --start 2025-01-01 --end 2026-04-28 \
--format json | \
jq '.report_json | fromjson | .performanceAll'
```
## Supported Periods
| Flag | Description |
| ---- | ----------- |
| `day` | Daily bars (default) |
| `week` | Weekly bars |
| `month` | Monthly bars |
| `year` | Yearly bars |
| `1h` | 1-hour bars |
| `30m` | 30-minute bars |
| `15m` | 15-minute bars |
| `5m` | 5-minute bars |
| `1m` | 1-minute bars |
Intraday periods accept datetime: `--start "2024-01-02 09:30" --end "2024-01-02 16:00"`.
---
# Indicator
URL: https://open.longbridge.com/docs/cli/quant/indicator.md
# Indicators
Run any indicator script over historical K-line data with `longbridge quant run`. Each `plot()` call in your script becomes a named series in the output.
## MACD
```bash
longbridge quant run NVDA.US \
--start 2026-01-02 --end 2026-04-28 \
--script '
indicator()
fast = input.int(12)
slow = input.int(26)
sig = input.int(9)
[macdLine, signalLine, hist] = ta.macd(close, fast, slow, sig)
plot(macdLine, "MACD")
plot(signalLine, "Signal")
plot(hist, "Histogram")
'
```
## RSI
```bash
longbridge quant run NVDA.US \
--start 2026-01-02 --end 2026-04-28 \
--script '
indicator()
period = input.int(14)
plot(ta.rsi(close, period), "RSI")
'
```
## Bollinger Bands
```bash
longbridge quant run NVDA.US \
--start 2026-01-02 --end 2026-04-28 \
--script '
indicator()
length = input.int(20)
mult = input.float(2.0)
basis = ta.sma(close, length)
dev = mult * ta.stdev(close, length)
plot(basis + dev, "Upper")
plot(basis, "Mid")
plot(basis - dev, "Lower")
'
```
## EMA Ribbon
```bash
longbridge quant run NVDA.US \
--start 2026-01-02 --end 2026-04-28 \
--script '
indicator()
plot(ta.ema(close, 8), "EMA8")
plot(ta.ema(close, 21), "EMA21")
plot(ta.ema(close, 55), "EMA55")
'
```
## Stochastic
```bash
longbridge quant run NVDA.US \
--start 2026-01-02 --end 2026-04-28 \
--script '
indicator()
k = ta.stoch(close, high, low, 14)
d = ta.ema(k, 3)
plot(k, "K")
plot(d, "D")
'
```
> **Note** — `ta.stoch` returns a single `%K` value. Compute `%D` by applying `ta.ema(k, 3)` manually.
## Parabolic SAR with ATR Band
```bash
longbridge quant run NVDA.US \
--start 2026-01-02 --end 2026-04-28 \
--script '
indicator()
sarVal = ta.sar(0.02, 0.02, 0.2)
atrVal = ta.atr(14)
plot(sarVal, "SAR")
plot(close + atrVal, "Upper ATR")
plot(close - atrVal, "Lower ATR")
'
```
## Piping a Script File
For longer scripts, save to a `.pine` file and pipe it in:
```bash
cat my_indicator.pine | longbridge quant run NVDA.US \
--start 2026-01-02 --end 2026-04-28
```
## Tunable Parameters with `--input`
Override default `input.*()` values at runtime without editing the script:
```bash
longbridge quant run NVDA.US --start 2026-01-02 --end 2026-04-28 \
--input '[21]' \
--script '
indicator()
period = input.int(14)
plot(ta.rsi(close, period), "RSI")
'
```
Parameters are matched positionally: `[21]` replaces the first `input.*()` call.
## Navi — The Script Language
Scripts run on [Navi](https://navi-lang.org) — a scripting language
designed for quantitative analysis.
Install the Navi CLI to validate scripts locally before running them on Longbridge servers:
```bash
curl -fsSL https://navi-lang.org/install.sh | sh
```
Once installed, run a script file directly:
```bash
navi run my_indicator.pine
```
This lets you catch syntax errors locally without a network round-trip to `longbridge quant run`.
---
# Stock Screener
URL: https://open.longbridge.com/docs/cli/quant/screener.md
# Stock Screener
The `screener` command lets you list saved strategies, run a strategy to get matching stocks, apply ad-hoc filters, and browse all available indicator definitions.
**Try it on the web** — All strategies and filter conditions shown below are also available interactively in the [Longbridge Stock Screener](https://longbridge.com/en/screener). Try building a filter there first, then automate it with the CLI.
## screener strategies
List platform-recommended or your own saved screener strategies.
```bash
# Recommended strategies for the US market (default)
longbridge screener strategies
# Recommended strategies for Hong Kong
longbridge screener strategies --market HK
# Your own saved strategies
longbridge screener strategies --mine
```
| Flag | Default | Description |
| ---- | ------- | ----------- |
| `--market US\|HK\|CN\|SG` | `US` | Market to list strategies for |
| `--mine` | — | Show your own strategies instead of recommended ones |
| `--format json` | — | Output raw JSON |
## screener run \
Run a saved strategy and list the stocks that match.
```bash
# Run strategy 42 with defaults
longbridge screener run 42
# Paginate: second page, 50 records per page
longbridge screener run 42 --page 1 --count 50
# Show specific columns
longbridge screener run 42 --show pettm --show pbmrq
```
| Flag | Default | Description |
| ---- | ------- | ----------- |
| `--page N` | `0` | Zero-based page number |
| `--count N` | `20` | Records per page |
| `--sort KEY` | `prevchg` | Column to sort by |
| `--order asc\|desc` | `desc` | Sort direction |
| `--show KEY` | — | Extra column to display (repeatable) |
| `--format json` | — | Output raw JSON |
Default output columns: `prevclose`, `prevchg`, `marketcap`, `salesgrowthyoy`, `pettm`, `pbmrq`, `industry`.
Default sort is `prevchg` descending (top movers first).
**JSON output format** (numeric values, no `filter_` prefix on keys):
```json
{
"total": 87,
"page": 0,
"items": [
{
"symbol": "AAPL.US",
"name": "Apple Inc.",
"prevchg": 1.24,
"pettm": 28.5,
"pbmrq": 45.2,
"marketcap": 3241500000000
}
]
}
```
## screener filter
Run an ad-hoc screen without a saved strategy. Specify one or more filter conditions directly on the command line.
```bash
# Stocks with P/E between 10 and 50 and ROE above 5% in HK
longbridge screener filter pettm:10:50 roe:5: --market HK
# US stocks with market cap above $100 bn, second page
longbridge screener filter marketcap:100: --market US --page 1 --count 50
# MACD golden-cross stocks in HK (technical indicator with extra parameters)
longbridge screener filter 'macd_day:::category=goldenfork,period=day' --market HK
```
**Condition format:** `KEY:MIN:MAX` or `KEY:MIN:MAX:k=v,k=v` for technical indicators.
- `KEY` — indicator key from `screener indicators` (without `filter_` prefix)
- `MIN` — lower bound (leave empty for no lower bound)
- `MAX` — upper bound (leave empty for no upper bound)
- `k=v,...` — extra key-value parameters for technical indicators
| Flag | Default | Description |
| ---- | ------- | ----------- |
| `--market US\|HK\|CN` | `US` | Market to screen |
| `--sort KEY` | `prevchg` | Column to sort by |
| `--order asc\|desc` | `desc` | Sort direction |
| `--show KEY` | — | Extra column to display (repeatable) |
| `--page N` | `0` | Zero-based page number |
| `--count N` | `20` | Records per page |
| `--format json` | — | Output raw JSON |
## screener indicators
List all indicator definitions supported by the screener.
```bash
longbridge screener indicators
longbridge screener indicators --format json
```
**JSON output** is a flat array (no nested groups) with `filter_` prefix stripped from keys:
```json
[
{
"id": 1,
"key": "marketcap",
"name": "Market Cap",
"unit": "bn",
"min": "0",
"max": "",
"tech_values": {}
},
{
"id": 29,
"key": "divyld",
"name": "Dividend Yield (TTM)",
"unit": "%",
"min": "0",
"max": "100",
"tech_values": {}
}
]
```
---
# Release Notes
URL: https://open.longbridge.com/docs/cli/release-notes.md
# Release Notes
### [v0.31.0](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.31.0)
- **Fix: `rank --count`** is honored
### [v0.30.0](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.30.0)
- **Quote commands no longer open a WebSocket** — the one-shot quote commands use the HTTP REST quote API: `quote`, `depth`, `brokers`, `trades`, `intraday`, `kline`, `static`, `calc-index`, `capital`, `participants`, `trading`, `warrant` and `option`, plus the quote lookups in `portfolio`, `sharelist` and order previews. They start faster because there is no WebSocket handshake, and their output is unchanged. The TUI and `longbridge serve` still use the WebSocket
- **API errors show the business code and a trace id** — for example `Error: API error (code 301604): no quote access` followed by a `trace_id: …` line. The previous form was `WebSocket error (status=7, code=…)`, so update any script that parses this text
- **Fix: `option chain --date ` failed** — in v0.29.0 it returned `404000 api not found`; it now returns the full strike chain
- **Chat TUI follows the terminal theme** — `longbridge ai` adapts its colors to light and dark terminals
### [v0.29.0](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.29.0)
- **New `fund` command group — Hong Kong mutual funds** — `longbridge fund` brings the mutual-fund channel to the terminal: browse the catalog (`hot`, `list`, `filters`), read a fund's `detail`, `analysis` / `analysis-detail`, `trend`, `annual-returns` / `quarterly-returns`, `performance` / `performance-comparison`, latest and historical NAV (`nav`, `nav-history`, `nav-range`) and `holdings` / `stock-holdings`; review your holdings (`positions`, `position`, `position-performance`, `position-profits`, `position-nav`, `position-dividends`); and manage orders (`orders`, `order`, `transactions`, `validate-order`, `submit-order`, `cancel-order`). Funds are addressed by `counter_id` (e.g. `UT/FD/HK0000384492`), not a stock symbol — get one from `fund hot` / `fund list`. `submit-order` and `cancel-order` prompt for confirmation unless `--yes`. See the [Funds](/docs/cli/fund/market) docs
### [v0.28.0](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.28.0)
- **[Chat with LongbridgeAI in the terminal](/docs/cli/ai)** — the new `longbridge ai` command opens a full-screen chat: answers stream in as Markdown with terminal-drawn charts, box-drawn tables, syntax-highlighted code and live quote cards. A title-bar ticker follows every security the conversation mentions (click one for a full quote card), slash commands cover `/new` `/retry` `/copy` `/export` `/quote` `/resume` `/settings` `/agent` `/login`, and conversations are stored on your account — a chat started in the terminal continues wherever else you use LongbridgeAI
- **[New `serve` command — embed the Longbridge API in your own app](/docs/cli/serve)** — `longbridge serve` keeps one authenticated process alive and speaks JSON-RPC 2.0 over stdin/stdout: every `quote.*` and `trade.*` method, `api.get` / `api.post` passthrough to any REST endpoint, and `quote.subscribe` for live quote / depth / broker / trade pushes. Desktop widgets, bar plugins and dashboards stop paying region detection, token load and WebSocket connect on every poll — and can see the ticks between polls. Payloads are the raw OpenAPI shapes, not the CLI's `--format json` rendering
- **New `grid` command group — grid trading** — `longbridge grid` lists grid orders (`--ids`, `--symbol`, `--status`), plus `submit`, `replace`, `detail`, `triggers`, `cancel`, `suspend`, `restart`, `info` and `questionnaire`. `submit` / `replace` share one rule flag set: price range and base price, `--trigger-type percent|spread` with `--trigger-up` / `--trigger-down`, per-side quantities and order types, TIF, and what happens when the price leaves the range — with `--dry-run` to validate and print the rule without submitting it
- **Reworked TUI chrome** — primary tabs are pills, and the shortcut hints no longer overflow: they take the space the tabs leave, shed the least important first, and are clickable (Settings and Help never go). Portfolio and Orders gain a right-hand detail panel that follows the selection; the stock screen drops its Quote/News tab strip so the article pane can wrap, scroll and open on longbridge.com, and docks the news list beside the quote panel when both fit. Clicking a shortcut hint now runs the same action its key does, and the footer's index quotes carry click targets that follow the text rather than a fixed third. The settings modal is a real two-column grid, with clickable chips and `←`/`→` stepping values in either direction, and it moves off `Ctrl+,` (which conflicts on some platforms) to `,`
- **Fix: intraday charts rendered as a dot texture** — the area fill is now shade blocks in the line's own color and the volume bars are solid, instead of braille (which can only set a foreground). Two bugs behind it are fixed too: the ANSI parser read only the first parameter of an SGR escape, dropping any sequence that set more than one attribute; and the chart info bars hardcoded green/red instead of following the up/down color setting — one of them inverted in the default mode
- **`news detail` now returns structured data** — the article is read from Longbridge's own content service instead of being scraped off the web page, so title, published time, author and related securities come back as proper fields alongside the Markdown body; `--format json` prints the full item
### [v0.27.0](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.27.0)
- **[Use LongbridgeAI over ACP](/docs/cli/acp)** — The new `longbridge acp` command runs [LongbridgeAI](https://longbridge.com/ai) as an [Agent Client Protocol](https://agentclientprotocol.com/) (ACP) compatible agent. You can now look up live market data, analyze company fundamentals, and interpret account positions from compatible client applications; see the ACP guide for setup
- **New `agent` commands for LongbridgeAI** — `agent workspaces` lists AI workspaces; `agent list` discovers chat-capable agents (`--workspace`, `--name`; `--all` includes workflow agents); `agent chat chatbot "…"` holds a conversation over SSE (`--stream` for live tokens — the public `chatbot` agent is usable by any account), with `agent chat chatbot "…"` for multi-turn follow-ups; `agent continue chatbot ` resumes an interrupted run (`--answer` / `--answers-json`); and `agent --skill` prints the agent skill doc for AI harnesses
### [v0.26.0](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.26.0)
- **New TUI settings modal (`Ctrl+,`)** — first setting is up/down colors (red-up vs green-up); applied instantly and remembered across restarts in `~/.longbridge/terminal.json`
- **Context-aware shortcut hints and mouse scrolling in the TUI** — the top bar now lists only the keys available on the current screen, and the scroll wheel moves the selection in the watchlist / orders / news / portfolio lists
- **Refreshed TUI visuals** — rounded borders on panels and modals, bold titles and table headers, and a stacked asset-distribution bar on the Portfolio screen; all drawn in the terminal's own palette
- **Access point no longer gets stuck on China Mainland** — the region is now decided by the country geotest reports rather than by whether it merely responds, and is re-checked every 6 hours, so a client that has left China Mainland stops being routed to `longbridge.cn`. `check` re-detects on every run, measures both access points and switches to whichever is decisively better; a connection failure against `.cn` now explains how to override the region
- **Fix: `ipo calendar` returned no data** — the upstream aggregation endpoint began returning an empty summary for every account; the command is rebuilt on the data sources that still work
- **Fix: clearer error for US option quotes** — `option quote` now explains that the "OPRA US Options" OpenAPI market-data permission is required and links to pricing, instead of surfacing a bare `301604`
- **Fix: `ipo detail` degrades gracefully** — timeline, eligibility and holdings are treated as optional enrichment, so the core profile still prints when an auxiliary endpoint is unavailable (`null` in JSON, warnings under `-v`)
### [v0.25.0](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.25.0)
- **`quant run` moved to the v2 API with Navi support** — new `--language navi|pine` flag (Navi is the default); chart rendering handles both the v1 and v2 payload shapes
### [v0.24.0](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.24.0)
- **New `macrodata` command** — Browse 400+ macrodata indicators across US/HK/CN/EU/JP/SG; list mode with optional `--country` filter, history mode for a specific indicator code with `--start`/`--end` date range; `--format json` for AI/scripting workflows
### [v0.23.2](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.23.2)
- **Local-time date parsing for CLI arguments** — date-only and legacy minute-resolution datetime inputs are interpreted in the user's local timezone before API calls; RFC 3339 datetime inputs are also supported
- **Fix: `market-status` US post-market label** — US status code `203` now displays as `Post-Market` instead of `Trading`, so after-hours market state is reported correctly
### [v0.23.0](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.23.0)
- **Authorization-code login** — `auth login --auth-code ` now works through the `/connect` authorization-code exchange, enabling browserless login flows for AI agents and hosted environments
### [v0.22.4](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.22.4)
- **`constituent` now supports ETFs** — ETF symbols return an asset-allocation breakdown (holdings / regional / asset-class / industry tables); index symbols behave exactly as before
- **Full US ETF holdings from SEC N-PORT** — for US ETFs, `constituent` fetches the complete portfolio from SEC EDGAR N-PORT filings by default (weight, shares, market value — e.g. all 500+ holdings of `IVV.US`); falls back to the platform's asset-allocation summary when SEC data is unavailable
### [v0.22.3](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.22.3)
- **`quote` now includes the US overnight session** — `quote --format json` now populates `overnight_quote` alongside `pre_market_quote` and `post_market_quote`; previously the overnight field was always `null`, skewing after-close analysis in AI workflows
- **Account-type banner on holdings commands** — `positions`, `fund-positions`, `assets`, and `portfolio` now print a one-line banner (`Live A/C (real account)` / `Demo A/C (simulated account)`) before the table, so it's clear which account the data belongs to; `--format json` output is unchanged
### [v0.22.2](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.22.2)
- **JSON timestamps now RFC 3339** — time-series and history commands (`kline`, `kline-history`, `trades`, `intraday`, `capital-flow`, `capital-dist`, `market-temp`, `topics`) and account P&L flows now output ISO 8601 / RFC 3339 datetimes instead of raw Unix epochs
- **`market-temp --history` default range** — omitting `--start` now defaults to 30 days before the end date instead of today, so a single `--history` call returns a full month of data
### [v0.22.0](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.22.0)
- **New `shareholder --top`** — Top-20 major shareholders (institutions, individuals, insiders) with multi-period comparison; `--object-id ` for single shareholder holding history and trade details
- **Extended `short-positions`** — Added HK market support (`.HK` suffix auto-routes to HKEX short-position data)
- **New `short-trades`** — Daily short sale volume (US: FINRA/NASDAQ; HK: HKEX disclosure data)
- **New `compare`** — Multi-stock valuation comparison (PE/PB/PS/market-cap/close); server auto-selects peers when no comparison symbols given
- **New `top-movers`** — Stocks whose price movement exceeds the 20-day standard deviation, with correlated news; supports `--market`, `--sort time|change|hot`
- **New `screener` command group** — Stock screener: `strategies` (recommended/saved), `search --strategy-id ` or `--filter key:min:max`, `indicators` to list available filters
- **New `rank`** — Popularity leaderboard; list all categories without `--key`, or pass `--key ` for a specific ranking (e.g. `ib_hot_all-us`)
- MCP server updated with the same new tools
### [v0.21.0](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.21.0)
- **New: `business-segments`** — revenue breakdown by business segment, current period or historical trend
- **New: `industry-rank`** — industry ranking by market (US/HK/CN/SG) and indicator; counter_id output feeds directly into `industry-peers`
- **New: `industry-peers`** — hierarchical sub-sector tree with stock count, daily change, and YTD change per node
- **New: `financial-report snapshot`** — AI earnings summary with beat/miss analysis vs consensus estimates and upcoming peer earnings dates
- **New: `institution-rating --views`** — month-by-month buy/hold/sell distribution timeline
### [v0.20.3](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.20.3)
- **Breaking: `analyst-estimates` removed** — command has been removed; the same data is available via `consensus` (EPS and revenue estimates)
- **Fix: HK symbol leading zeros** — inputs like `00700.HK` or `09988.HK` now correctly resolve to `700.HK` / `9988.HK`; `operating` updated to reflect HK-only data coverage
- **Fix: `ipo detail`** — auto-detects market from symbol suffix (`SUJA.US` → US, `700.HK` → HK), so `--market` is no longer required; cleaner error message when no IPO data is found; Payment Deadline formatted as RFC 3339
### [v0.20.2](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.20.2)
- **Fix: `institution-rating --history`** — restructured as a proper table with logical column ordering; timestamps formatted as `YYYY-MM-DD`; price targets rounded to 2 decimal places; `evaluate_history` capped to 20 most recent records
- **Fix: IPO date display** — `ipo listed`, `ipo wait-listing`, `ipo calendar`, `ipo us-wait-listing` now show correct dates (e.g. `2026-05-11`) instead of a bogus 1970 date
### [v0.20.0](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.20.0)
- **`ipo` command group** — comprehensive IPO tools: `subscriptions`, `wait-listing`, `listed`, `calendar`, `detail`, `orders`, `profit-loss` for HK market; `us-subscriptions`, `us-wait-listing`, `us-listed` for US market; `orders detail ` for full order detail
- **`financial-statement`** — detailed, hierarchical financial statements (income statement, balance sheet, cash flow) with full line-item breakdown and YoY comparison; supports `--kind IS/BS/CF/ALL` and `--report af/saf/qf/cumul`
- **`financial-report --latest`** — new flag to fetch the latest report summary (key indicators: revenue, net profit, EPS, ROE, total assets) without fetching the full statement
- **`valuation-rank`** — daily PE/PB/PS industry percentile rank over a date range, showing `rank/total` for each metric
- **`institution-rating --history` / `--industry-rank`** — new flags: `--history` shows how analyst ratings and price targets have changed over time; `--industry-rank` ranks all stocks in the same industry by analyst coverage
- **`news search` / `topic search`** — keyword search across news articles and community topics
- **`bank-cards`** — list bank cards linked to your account
- **`withdrawals`** / **`deposits`** — view withdrawal and deposit history with date formatting and optional state/currency filters
- **`portfolio short-margin`** — short-selling margin deposit details per position
- **Fix: paper-trading account channel** — `auth status` and quote mall QR links now correctly reflect the account channel for paper-trading accounts (`lb_papertrading`), resolved from the access token JWT rather than hardcoded
### [v0.19.2](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.19.2)
- **`finance-calendar` revamp** — restructured into subcommands (`report`, `dividend`, `split`, `ipo`, `macrodata`, `closed`); new `--filter watchlist|positions` scopes events to your watchlist or holdings
- **`quote`** — new "Last Chg%" column showing price change vs previous close
- **`corp-action`** — defaults to 30 items; add `--all` to retrieve all records
- **`update --force`** — skip version check and force reinstall; auto-retries with `sudo` on permission error
- **TUI** — full mouse support; chart type toggle (line / candlestick) in stock detail view
### [v0.19.0](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.19.0)
- **TUI: History orders tab** — press `Tab` on the Orders page to switch between Today and History; History mode fetches the last 30 days by default; press `f` to open a date-range filter popup
- **TUI: Cancel and modify orders** — press `c` to cancel or `m` to modify an active today order directly from the orders table; a confirmation step is shown before submitting
- **`auth status` quote packages** — displays a formatted table of subscribed quote packages (market, name, validity period) and prints a QR code to open the quote mall in the Longbridge App
- **`calc-index` field aliases** — short aliases for common fields: `iv` (implied_volatility), `oi` (open_interest), `vol` (volume), `mktcap` (total_market_value), `exp` (expiry_date), `strike` (strike_price); `--help` now groups fields into General and Options/Warrants sections
- **`quant run` command** — run a quant indicator script server-side against historical K-line data; supply the script inline with `--script` or pipe via stdin; outputs computed plot values as JSON
- **`update` release notes** — only the 10 most recent entries are shown after `longbridge update` completes; `sudo` is suggested when the binary lives in `/usr/local/bin`
### [v0.18.0](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.18.0)
- **TUI: Orders page** — interactive orders table with trading shortcuts and an order entry dialog for placing trades without leaving the terminal
- **`dividend --page` / `--year`** — paginate through large dividend histories and filter by year; fetches 50 records per page (up from 30)
### [v0.17.4](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.17.4)
- **`--limit` alias for `--count`** — all commands that accept `--count` now also accept `--limit` as an alias, improving compatibility for AI agent tool-calling
- **Fix: Unix self-update ETXTBUSY** — `longbridge update` no longer fails with "Text file busy" on Unix; the update now uses a staged temp file and atomic rename instead of writing directly to the running binary
### [v0.17.3](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.17.3)
- **Fix: token refresh hang** — when the access token expired on a flaky network, the CLI no longer waits 5 minutes before failing; it now fails immediately with a clear error and preserves the token file for the next retry
- **`auth status` accuracy** — now shows three states: `valid` (green), `refresh pending` (yellow, access token expired but refresh token valid — next command auto-refreshes with no user action needed), `expired` (red, re-login required); previously `refresh pending` was incorrectly shown as `expired`
- **Fix: `--auth-code` login** — browser OAuth flow now triggers correctly when no token file exists
- **Fix: Windows browser launch** — OAuth URLs containing `&` parameters no longer get truncated on Windows; switched to the `open` crate for cross-platform browser launching
### [v0.17.1](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.17.1)
- **`completion` command** — generate shell tab-completion scripts for bash, zsh, fish, elvish, and powershell; redirect stdout to the appropriate file then reload your shell to activate (e.g. `longbridge completion zsh > ~/.zfunc/_longbridge`)
- Sets `User-Agent: longbridge-cli/` on all HTTP and WebSocket requests
- Adds `x-cli-cmd` request header identifying the active subcommand on every API call
### [v0.17.0](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.17.0)
- **`dca` command** — recurring investment plans: create, update, pause, resume, stop, view trade history, stats summary, check symbol eligibility, and calculate next trade date; HK/SG accounts must agree to Terms and Conditions before creating a plan (`--agree-terms` to skip the interactive prompt)
- **`sharelist` command** — community stock lists: list own and subscribed sharelists, browse trending lists (`popular`), create/delete sharelists, and add/remove/reorder constituent stocks
- **`short-positions`** — US stock short selling data: short ratio, short shares, average daily volume, days-to-cover, and close price; updated bi-monthly by FINRA; `--count` 1–100
- **`option volume`** — real-time call/put volume snapshot with put/call ratio; `daily` subcommand for historical call/put volume and open interest
- **`option chain`** — without `--date` now returns expiry dates only; pass `--date` to see strikes for a specific expiry
- **`profit-analysis`** — added `--start`/`--end` date filtering for the summary command; Simple Yield and TWR now shown as percentages; breakdown renamed from "Stock P&L Breakdown" to "P&L Breakdown" (includes funds and MMF)
### v0.16.3
- **`auth` subcommand group** — `longbridge auth login`, `auth logout`, `auth status`; `auth status` shows token validity, expiry, account info, and quote level locally without network
- **`alert enable` / `alert disable`** — toggle price alerts on/off without deleting them
- **Fix: US index symbols** — `.DJI.US`, `.VIX.US` and other US index symbols now parse correctly; US indexes require a leading dot (e.g. `.DJI.US`, not `DJI.US`)
- **"Did you mean?" hints** — when a query returns no data, the CLI suggests the correct symbol format: missing market suffix → `TSLA.US` / `700.HK`; missing leading dot → `.DJI.US`
### v0.16.1
**Enhancements**
- `option quote` — now returns all fields from the OptionQuote API (added `timestamp`, `trade_status`, `open_interest`, `historical_volatility`, `contract_multiplier`, `contract_size`, `direction`, `underlying_symbol`); JSON output uses proper typed values instead of table-column strings
- `calc-index` — Theta, Vega, and Rho values are now normalized (÷100) to standard per-share conventions; auto-detects option symbols and switches to Greeks default fields when stock defaults return empty
- `capital` — improved argument handling
- `market-status` — fixed incorrect `trade_status` mapping (105 = afternoon trading session); JSON output now returns human-readable market and status labels instead of raw API codes
- Parameter standardization: `--adjust none/forward` (was `no_adjust/forward_adjust`), `--tif day/gtc/gtd` (was `Day/GoodTilCanceled/GoodTilDate`), `--format table` as default name (alias: `pretty`), `finance-calendar --start/--end` (was `--date/--end-date`), `statement --start-date` now accepts `YYYY-MM-DD` format
- TUI: fixed watchlist sort jumping and made scrollbar more subtle
### [v0.16.0](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.16.0)
21 new commands covering company fundamentals, market data, and account features.
**New: Company & Fundamentals**
- `company` — company overview (founding date, employees, IPO price, address)
- `executive` — company executives and key personnel
- `industry-valuation` — industry valuation comparison with peers (PE/PB/EPS/DY); `dist` subcommand for percentile ranking
- `operating` — operating reviews: financial indicators table + management review
- `corp-action` — corporate actions (splits, dividends, rights, etc.)
- `invest-relation` — investment relations (subsidiary/parent companies)
**New: Market & Quotes**
- `constituent` — index/ETF constituent stocks with sorting + rise/fall stats
- `market-status` — market open/close status for each exchange
- `broker-holding` — broker holding positions for HK stocks (top/detail/daily)
- `ah-premium` — A/H premium ratio kline and intraday data for dual-listed stocks
- `trade-stats` — trade statistics (price distribution by volume)
- `anomaly` — quote anomalies / unusual market movements
**New: Account**
- `alert` — price alerts (list/add/delete)
- `profit-analysis` — P&L summary + per-stock breakdown; `detail` for individual stock P&L with transaction flows; `by-market` for market-filtered view
**Enhancements**
- `update` — cross-platform self-update with Windows support and CDN acceleration; `--release-notes` to view changelog; auto-shows release notes on version change
- `intraday --date` — retrieve historical intraday data for a past date
- TUI: press `/` to search watchlist or type a symbol to jump directly to any stock
- `BROWSER` env var support for custom browser selection during login
### [v0.15.0](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.15.0)
- **New: `portfolio` command** — total P/L, asset distribution by market (US/HK/CN/SG/Cash), holdings, and cash balances
- **New: `investors` command** — SEC 13F-based active fund manager rankings; view any investor's holdings by CIK with live prices
- **New: `insider-trades`** — SEC Form 4 insider transaction history for any symbol
- **New: `watchlist pin/unpin`** — pin securities to the top of a watchlist group
- **Enhanced: `assets`** — renamed from `balance`; now shows full asset overview: net assets, buying power, margin, risk level, and per-currency cash breakdown
### [v0.14.2](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.14.2)
- **New: `--lang` global flag** — set content language (`zh-CN`, `zh-HK`, `en`) for all commands; falls back to system `LANG` env var then `en`
### [v0.14.1](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.14.1)
- **New: CN region login** — `longbridge auth login` now supports China region routing
- **New: `-v` flag** — show version without entering the full command
### [v0.14.0](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.14.0)
- **New: Device auth login** — `longbridge auth login` now uses OAuth device flow; displays a URL and code to authorize on any device, works in SSH and headless environments; `--headless` flag removed
- **New: Order enhancements** — trailing stop and AO order types; `--expire-date`, `--outside-rth`, `--remark` added to order commands
- **Fix: Linux segfault** — prebuilt Linux binary now uses musl to fix crash on some distributions
### [v0.13.0](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.13.0)
- **New: Fundamentals & analysis commands** — `financial-report`, `valuation`, `forecast-eps`, `consensus`, `institution-rating`, `shareholder`, `fund-holder`, `dividend`, `finance-calendar`, `exchange-rate`
- **Breaking: command restructure** — 19 flat commands moved into subcommand trees (e.g. `news-detail` → `news detail`, `kline-history` → `kline history`, `warrant-list` → `warrant list`)
- **CN region support** — set `LONGBRIDGE_REGION=cn` to route through the China endpoint
### [v0.12.0](https://github.com/longbridge/longbridge-terminal/releases/tag/v0.12.0)
- **New: `statement` commands** — list and export daily/monthly account statements
- **TUI** — fixed `q` quit; added news list and detail views inside watchlist
---
Full changelog: [github.com/longbridge/longbridge-terminal/releases](https://github.com/longbridge/longbridge-terminal/releases)
---
# insider-trades
URL: https://open.longbridge.com/docs/cli/research/insider-trades.md
# longbridge insider-trades
View [SEC Form 4](https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&type=4&dateb=&owner=include&count=40) insider transaction history for any US-listed stock — purchases, sales, and option exercises by company insiders.
## Basic Usage
```bash
longbridge insider-trades TSLA.US
```
```
| date | filer | title | type | shares | price | value | owned_after |
|------------|--------------|---------------|----------|--------|---------|----------|-------------|
| 2026-03-31 | Zhu Xiaotong | SVP | EXERCISE | 20.00K | $20.57 | $411.40K | 20.00K |
| 2025-09-11 | Zhu Xiaotong | SVP, APAC and | SELL | 20.00K | $363.75 | $7.28M | 47.60K |
| 2025-06-12 | Zhu Xiaotong | SVP, APAC | EXERCISE | 15.00K | $20.57 | $308.55K | 82.60K |
| 2025-06-12 | Zhu Xiaotong | SVP, APAC | SELL | 15.00K | $323.81 | $4.86M | 67.60K |
```
## Examples
### Check insider activity
```bash
longbridge insider-trades TSLA.US
longbridge insider-trades TSLA.US --format json
```
Lists recent insider transactions including the insider's name, title, transaction date, type, share count, and price.
### Expand the filing history
```bash
# Fetch more filings to cover a wider date range
longbridge insider-trades TSLA.US --count 100
longbridge insider-trades AAPL.US --count 100 --format json
```
Use `--count` to retrieve more Form 4 filings and cover a broader time window. Useful for tracking insider activity around earnings announcements or major corporate events.
## Notes
US market only. Data sourced from [SEC EDGAR Form 4 filings](https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&type=4&dateb=&owner=include&count=40).
---
# investors
URL: https://open.longbridge.com/docs/cli/research/investors.md
# longbridge investors
Browse active institutional fund managers ranked by AUM (from [SEC 13F filings](https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&type=13F&dateb=&owner=include&count=40)), and drill into any manager's current holdings.
## Basic Usage
```bash
longbridge investors
```
```
| # | name | AUM | period | cik |
|----|-----------------------------------|----------|-------------|------------|
| 1 | Capital International Investors | $637.97B | 31-DEC-2025 | 0001562230 |
| 2 | Capital Research Global Investors | $541.73B | 31-DEC-2025 | 0001422848 |
| 3 | CTC LLC | $404.44B | 31-DEC-2025 | 0001445893 |
| 4 | BERKSHIRE HATHAWAY INC | $274.16B | 31-DEC-2025 | 0001067983 |
| 5 | DODGE & COX | $185.26B | 31-DEC-2025 | 0000200217 |
...
```
## Examples
### Browse top fund managers
Lists the largest institutional investors ranked by AUM, with their CIK identifier, name, reported AUM, and the period of the latest [13F filing](https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&type=13F&dateb=&owner=include&count=40).
### View a fund manager's holdings
```bash
# Use the CIK from the investors list to drill into holdings
longbridge investors 0001067983
longbridge investors 0001067983 --format json
```
```
BERKSHIRE HATHAWAY INC (period: 2025-12-31)
Portfolio: 42 positions, total value ~$274.16B
| company | value | shares | weight |
|-----------------------|---------|---------|--------|
| APPLE INC | $61.96B | 227.92M | 22.6% |
| AMERICAN EXPRESS CO | $56.09B | 151.61M | 20.5% |
| BANK AMERICA CORP | $28.45B | 517.30M | 10.4% |
| COCA COLA CO | $27.96B | 400.00M | 10.2% |
| CHEVRON CORP NEW | $19.84B | 130.16M | 7.2% |
...
```
Pass a CIK to see the full list of equity positions reported by that fund manager. CIK `0001067983` is Berkshire Hathaway.
### Compare position changes between filings
```bash
# Changes between the two most recent filings
longbridge investors changes 0001067983
# Compare against a specific base period
longbridge investors changes 0001067983 --from 2024-09-30
```
```
BERKSHIRE HATHAWAY INC — changes vs 2024-09-30
| action | company | shares_change | value_change | current_shares | current_value |
|---------|------------------------|---------------|--------------|----------------|---------------|
| NEW | CONSTELLATION BRANDS | +5.21M | +$1.24B | 5.21M | $1.24B |
| ADDED | SIRIUS XM HOLDINGS INC | +57.83M | +$1.52B | 144.42M | $3.80B |
| REDUCED | CHEVRON CORP NEW | -12.50M | -$1.93B | 130.16M | $19.84B |
| EXITED | FLOOR & DECOR HLDGS | -3.97M | -$414.30M | 0 | $0 |
...
```
Shows NEW positions, ADDED (increased), REDUCED (decreased), and EXITED positions between two filing periods. Defaults to comparing the latest filing against the previous one.
---
# screener
URL: https://open.longbridge.com/docs/cli/research/screener.md
# longbridge screener
Stock screener — filter stocks using preset strategies or custom indicator conditions.
## Basic Usage
```bash
longbridge screener strategies
```
```
Preset Strategies
| id | name | market | description |
|----|-------------------------|--------|------------------------------------------|
| 1 | High-Yield Defensive | HK | Dividend yield > 5%, PE < 15 |
| 2 | Accelerating Growth | US | Revenue growth > 30%, ROE > 20% |
| 42 | Undervalued Blue Chips | HK | PB < 1.5, market cap > HKD 10B |
```
## Examples
### Workflow A — Use a preset strategy
**Step 1: List available strategies**
```bash
longbridge screener strategies
```
**Step 2: Inspect a strategy's filter conditions**
```bash
longbridge screener strategies --id 42
```
```
Strategy #42: Undervalued Blue Chips
Filters:
filter_pb: 0 ~ 1.5
filter_marketcap: 100 ~ (unlimited)
filter_divyld: 2 ~ (unlimited)
```
**Step 3: Run the strategy**
```bash
longbridge screener search --strategy-id 42
```
### Workflow B — Custom filter conditions
**Step 1: List available indicators**
```bash
longbridge screener indicators
```
```
Available Indicators
Valuation:
filter_pe P/E ratio
filter_pb P/B ratio
filter_ps P/S ratio
filter_marketcap Market cap (100M)
filter_divyld Dividend yield (%)
Growth:
filter_rev_growth Revenue growth (%)
filter_roe Return on equity (%)
...
```
**Step 2: Run a custom screen**
```bash
longbridge screener search --market HK --filter marketcap:100:1000 --filter divyld:3:
```
Filter format: `::`. Omit `min` or `max` to leave that side unbounded.
### View my saved strategies
```bash
longbridge screener strategies --mine
```
Lists your saved custom strategies.
## Subcommands
| Subcommand | Description |
|------------|-------------|
| `strategies` | List preset strategies (add `--mine` for custom strategies) |
| `strategies --id ` | Show filter conditions for a specific strategy |
| `search` | Run a screen (`--strategy-id` or `--filter`) |
| `indicators` | List all available filter indicators |
## Options
| Flag | Description |
|------|-------------|
| `--mine` | Show my saved strategies (with `strategies`) |
| `--id` | View filter conditions for a specific strategy (with `strategies`) |
| `--strategy-id` | Run the specified strategy (with `search`) |
| `--market` | Target market: `HK`, `US`, `CN`, `SG` (with `search`) |
| `--filter` | Custom filter condition, format `::`, repeatable |
| `--format` | Output format: `table` (default) or `json` |
---
# shareholder
URL: https://open.longbridge.com/docs/cli/research/shareholder.md
# longbridge shareholder
View the top shareholders of a company — institutional and individual — with ownership percentages and recent share count changes.
## Basic Usage
```bash
longbridge shareholder TSLA.US
```
```
| shareholder | symbol | % shares | chg shares | report_date |
|------------------------------------|--------|----------|------------|-------------|
| Elon R. Musk | - | 24.86% | +423.53M | 2025-12-30 |
| The Vanguard Group, Inc. | - | 6.90% | +6.54M | 2025-12-31 |
| BlackRock, Inc. | BLK.US | 5.57% | +2.81M | 2025-12-31 |
| State Street Global Advisors, Inc. | - | 3.06% | +1.08M | 2025-12-31 |
| Geode Capital Management, LLC | - | 1.75% | +375.95K | 2025-12-31 |
```
## Examples
### Check top shareholders
```bash
longbridge shareholder TSLA.US
longbridge shareholder TSLA.US --format json
```
Lists the largest shareholders by ownership percentage, including both institutional investors and individual insiders.
### View top 20 shareholders (--top)
```bash
longbridge shareholder AAPL.US --top
```
```
Top 20 Shareholders — AAPL.US
Period: Latest
| shareholder | type | % shares | chg shares | filing_date |
|--------------------------------|-------------|----------|------------|-------------|
| The Vanguard Group, Inc. | Institution | 9.71% | +0.01% | 2025/12/31 |
| BlackRock, Inc. | Institution | 7.75% | -0.06% | 2026/03/31 |
| ...
Use --object-id to view holding detail for a specific shareholder.
```
`--top` mode spans multiple reporting periods, includes institutions, individuals, and insiders, and displays the shareholder type (Institution / Individual / Insider).
### View shareholder holding detail (--object-id)
```bash
longbridge shareholder AAPL.US --object-id 148057
```
```
Shareholder Detail: The Vanguard Group, Inc.
Trading History:
Period: Past 1 Year
accum_buy: 0.00 accum_sell: 0.00
```
`--object-id` accepts a shareholder ID from `--top` output and returns that shareholder's historical position changes and trading activity.
## Options
| Flag | Description |
|------|-------------|
| `--top` | Show top 20 shareholders across multiple reporting periods, including institutions and individuals |
| `--object-id` | View holding detail for a specific shareholder (ID from `--top` output) |
| `--format` | Output format: `table` (default) or `json` |
---
# serve
URL: https://open.longbridge.com/docs/cli/serve.md
# longbridge serve
`longbridge serve` turns the CLI into a long-lived data source for your own application. It
authenticates and opens the market WebSocket once, then answers newline-delimited **JSON-RPC 2.0**
requests on stdin/stdout and pushes real-time quotes back as server notifications.
```bash
longbridge serve
```
It exists because the alternative is worse. Without it, a client polls by spawning
`longbridge --format json` on a timer — and every spawn redoes region detection, token
load and WebSocket connect for a single request. The startup cost dominates, and the client is stuck
at poll-interval latency with no way to ever see a tick in between. `serve` pays that cost once and
keeps the connection.
Newline-delimited JSON-RPC 2.0 is the base protocol LSP, MCP and ACP all build on, so a client needs
only a JSON parser and a line splitter — no protocol library, no SDK, no HTTP signing.
## Quick start
Pipe requests in and read responses out:
```bash
printf '%s\n' \
'{"jsonrpc":"2.0","id":1,"method":"quote.quote","params":{"symbols":["700.HK"]}}' \
'{"jsonrpc":"2.0","id":2,"method":"shutdown"}' | longbridge serve
```
`longbridge serve --help` prints the protocol summary, the notification list and every method name —
it is the reference to keep open while writing a client.
Authentication is shared with the rest of the CLI, so `longbridge auth login` once in the same
environment is all the setup there is.
## The protocol
One compact JSON object per line, UTF-8, on stdin and stdout. One request per line — batches (a JSON
array) are not accepted, as in LSP and MCP.
```text
request {"jsonrpc":"2.0","id":1,"method":"quote.quote","params":{"symbols":["700.HK"]}}
response {"jsonrpc":"2.0","id":1,"result":[…]}
error {"jsonrpc":"2.0","id":1,"error":{"code":-32602,"message":"…"}}
notification {"jsonrpc":"2.0","method":"quote.updated","params":{…}}
```
Four properties are worth designing your client around:
- **Requests are answered concurrently**, so a slow `trade.stock_positions` never stalls the quote
feed — and **responses may arrive out of order**. Correlate by `id`, as JSON-RPC intends.
- **Up to 8 requests run upstream at once.** The rest queue, so a burst is paced rather than dropped
or throttled by the server.
- **The process exits when stdin closes**, so it can never outlive the client that spawned it.
`shutdown` is the explicit form; in-flight requests get up to 5 seconds to drain either way.
- **Everything goes through stdout in whole lines.** A single writer owns stdout, so concurrent
handlers and the push feed never interleave mid-line.
### Session
`initialize` reports the surface rather than negotiating it — a client may call any method without
calling it first, but calling it is how you discover the method list in-band instead of hard-coding
it:
```jsonc
→ {"jsonrpc":"2.0","id":1,"method":"initialize"}
← {"jsonrpc":"2.0","id":1,"result":{
"protocolVersion":"1",
"serverInfo":{"name":"longbridge","version":"0.28.0"},
"capabilities":{"subscribe":["quote","depth","brokers","trades"]},
"methods":["api.get","api.post","initialize","quote.brokers", …]
}}
```
`shutdown` returns `null` and ends the session.
## Method surface
`serve` sits *below* the CLI commands, at the API seam all of them share:
```text
CLI commands (AI-facing JSON, free to change)
│
├── QuoteApi / TradeApi ──┐
└── http_get / http_post ─┤
▼
serve (raw upstream payloads)
```
| Namespace | Covers |
| --- | --- |
| `quote.*` | Every quote API call — `quote.quote`, `quote.depth`, `quote.candlesticks`, `quote.watchlist`, … |
| `trade.*` | Every trade API call — `trade.stock_positions`, `trade.account_balance`, `trade.submit_order`, … |
| `api.get` / `api.post` | Raw passthrough to any REST endpoint. This is how the fundamentals, screener, IPO and news data is reached |
| `quote.subscribe` / `quote.unsubscribe` | The live feed. No one-shot CLI equivalent |
| `initialize` / `shutdown` | Session control |
Because the namespaces mirror the API traits plus a REST passthrough, `serve` cannot drift behind
the CLI: a new command either reuses a seam that is already exposed, or adds a trait method — and a
build-time test fails if a trait method is ever added without a matching RPC method.
### Payloads are the raw OpenAPI shapes
A `result` is the upstream response, **not** the CLI's `--format json` output. That distinction is
deliberate: `--format json` reshapes data for AI consumption and is free to change with it, while
`serve` is a contract for other people's software, so it tracks the
[Longbridge OpenAPI](/docs/api) instead.
In practice:
- `trade.account_balance` returns SDK field names — `buy_power`, `cash_infos`, `max_finance_amount`.
- `api.get /v1/quote/market-status` returns `trade_status: 204`, not a rendered label.
- Decimals cross the wire as **strings** (`"448.600"`), so a client cannot lose precision to a JSON
float on the way to an order.
- `api.get` / `api.post` return the response body as received, less the account-identifying fields
the CLI also strips (`aaid`, `account_channel`).
Look a method up under its own name in the [API reference](/docs/api) for its fields; `quote.*` and
`trade.*` are named after the SDK calls they forward to.
### What is deliberately not a method
Views the CLI computes locally — `portfolio`, which merges balances, positions and FX rates — are
not exposed. A client composes them from `trade.account_balance`, `trade.stock_positions` and
`quote.quote` rather than depending on our arithmetic. (Or, as the Omarchy plugin below does, calls
`longbridge portfolio --format json` for the snapshot and keeps it repriced from the live feed.)
## The live feed
`quote.subscribe` is the reason `serve` exists. Subscribe once, then live on notifications:
```jsonc
→ {"jsonrpc":"2.0","id":1,"method":"quote.subscribe","params":{"symbols":["700.HK"],"fields":["quote"]}}
← {"jsonrpc":"2.0","id":1,"result":{
"subscribed":[{"symbol":"700.HK","fields":["quote"]}],
"quotes":[{"symbol":"700.HK","last_done":"448.600","prev_close":"442.400","open":"438.200", …}]
}}
← {"jsonrpc":"2.0","method":"quote.updated","params":{"symbol":"700.HK","last_done":"448.600","volume":12441624,"current_volume":600,"trade_session":"Intraday","timestamp":"2026-08-19T05:51:30Z", …}}
← {"jsonrpc":"2.0","method":"quote.updated","params":{"symbol":"700.HK","last_done":"448.700", …}}
```
**`fields`** selects what to receive — `quote`, `depth`, `brokers`, `trades`; omitted, it defaults to
`["quote"]`. Each field has its own notification:
| Notification | Params |
| --- | --- |
| `quote.updated` | `symbol`, `last_done`, `open`, `high`, `low`, `volume`, `turnover`, `current_volume`, `current_turnover`, `trade_status`, `trade_session`, `timestamp` |
| `quote.depth` | `symbol`, `asks`, `bids` |
| `quote.brokers` | `symbol`, `ask_brokers`, `bid_brokers` |
| `quote.trades` | `symbol`, `trades` |
Three things to get right:
1. **`quote.updated` is a tick, not a full quote.** It carries no `prev_close` and no security name —
fold it onto a snapshot rather than treating it as one. The `quotes` array in the `subscribe`
result is that starting snapshot; if that one call failed the field is simply omitted (the
subscription is live either way) and you fall back to `quote.quote`.
2. **A push can be older than the snapshot.** The snapshot is taken after subscribing, so nothing is
lost, but a push may have raced ahead of it — keep whichever `timestamp` is newer. This is the
same rule out-of-order responses need anyway.
3. **`quote.unsubscribe` drops every field for the named symbols**, not just the ones you list. Both
subscribe and unsubscribe return the full `subscribed` list, so it is always clear what the
session is actually receiving.
Nothing about the feed requires a timer. A well-built client makes a request only when something
happens — the view opens, the session reconnects, the symbol set changes, or a security crosses into
another trading session (the one thing a push cannot describe on its own, since it carries no
previous close).
## Errors
Codes follow JSON-RPC, and the split tells your client whether a retry can help:
| Code | Meaning | Retry? |
| --- | --- | --- |
| `-32700` | Parse error — the line was not valid JSON | No |
| `-32600` | Invalid request — not a JSON-RPC 2.0 object | No |
| `-32601` | Unknown method — often an installed CLI older than the method you need | No; prompt for an update |
| `-32602` | Bad parameters — the message names the field and the offending value | No, not as-is |
| `-32000` | Upstream failure — Longbridge or the network | Yes, with backoff |
A parameter error names what is wrong, so it can be surfaced directly:
```jsonc
← {"jsonrpc":"2.0","id":4,"error":{"code":-32602,"message":"`market`: Unknown market 'MARS'. Use: HK US CN SG"}}
```
An error never ends the session — one bad symbol must not take down a client's live feed.
## Parameter conventions
Parameters follow the OpenAPI request for the same call, with these CLI-shared spellings:
| Kind | Accepted |
| --- | --- |
| `symbol` / `symbols` | `CODE.MARKET`, e.g. `"700.HK"`; `symbols` is an array |
| `market` | `HK`, `US`, `CN` (`SH` / `SZ`), `SG` |
| `period` | `1m`, `5m`, `15m`, `30m`, `1h`, `day`, `week`, `month`, `year` |
| `adjust` | `none` (default) or `forward` |
| Dates | `YYYY-MM-DD` (`start`, `end`, `expiry_date`) |
| Datetimes | `start` / `end` on `trade.history_orders`, `trade.history_executions`, `trade.cash_flow` |
| Decimals | Strings — `"quantity":"100"`, `"price":"448.6"` |
| `query` (on `api.get`) | An object; strings, numbers and booleans are all accepted and stringified |
Optional counts have defaults: `quote.trades` `count` is 20, `quote.candlesticks` `count` is 100.
## Full method list
Call `initialize` for the authoritative list — this is what version 0.28.0 exposes.
**Session and passthrough** — `initialize`, `shutdown`, `api.get`, `api.post`
**Live feed** — `quote.subscribe`, `quote.unsubscribe`
**`quote.*`** — `quote`, `depth`, `brokers`, `trades`, `intraday`, `candlesticks`,
`history_candlesticks_by_date`, `history_candlesticks_by_offset`, `static_info`,
`calc_indexes`, `capital_flow`, `capital_distribution`, `market_temperature`,
`history_market_temperature`, `trading_session`, `trading_days`, `security_list`, `participants`,
`subscriptions`, `option_quote`, `option_chain_expiry_date_list`, `option_chain_info_by_date`,
`warrant_quote`, `warrant_list`, `warrant_issuers`, `watchlist`, `create_watchlist_group`,
`delete_watchlist_group`, `update_watchlist_group`
**`trade.*`** — `today_orders`, `history_orders`, `order_detail`, `today_executions`,
`history_executions`, `submit_order`, `cancel_order`, `replace_order`, `account_balance`,
`cash_flow`, `stock_positions`, `fund_positions`, `margin_ratio`, `estimate_max_purchase_quantity`
## A minimal client
Forty lines is enough for a working live feed:
```python
import json, subprocess, threading, itertools
proc = subprocess.Popen(
["longbridge", "serve"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, bufsize=1,
)
next_id = itertools.count(1)
pending = {}
def send(method, params=None):
rid = next(next_id)
req = {"jsonrpc": "2.0", "id": rid, "method": method}
if params is not None:
req["params"] = params
proc.stdin.write(json.dumps(req) + "\n")
proc.stdin.flush()
return rid
def reader():
for line in proc.stdout:
msg = json.loads(line)
if "id" in msg: # a response — correlate by id
pending[msg["id"]] = msg
if "error" in msg:
print("error", msg["error"])
elif msg["id"] == sub_id:
for q in msg["result"].get("quotes", []):
print("snapshot", q["symbol"], q["last_done"])
else: # a notification — no id
p = msg["params"]
print(msg["method"], p["symbol"], p.get("last_done"))
threading.Thread(target=reader, daemon=True).start()
sub_id = send("quote.subscribe", {"symbols": ["700.HK", "AAPL.US"], "fields": ["quote"]})
input("streaming — Enter to stop\n")
send("shutdown")
```
The same shape works in any language: spawn the process, write one JSON object per line, read one
per line, and split responses (have an `id`) from notifications (do not).
## Case study: Longbridge for Omarchy
[Longbridge for Omarchy](https://github.com/longbridge/omarchy-longbridge) is a watchlist and
portfolio panel for the [Omarchy](https://omarchy.org) bar, written in QML — no Longbridge SDK, just
`longbridge serve` on a pipe. It is a good model for what a `serve` client looks like in practice.
| Watchlist | Portfolio | Quote detail |
| --- | --- | --- |
|  |  |  |
### Install
```bash
omarchy plugin add https://github.com/longbridge/omarchy-longbridge.git --enable
```
Then open Longbridge from the bar. The welcome page checks that Longbridge CLI is installed, links
to the [installation guide](/docs/cli/install) if it is not, offers **Log in to Longbridge**, and
verifies the session with `longbridge check --format json`. The plugin never downloads or runs an
installer itself.
### What it does with `serve`
- **One long-lived session.** While the panel is open it runs a single `longbridge serve` process.
Starting it costs about 1.5 seconds — nearly all of it process start, authentication and the
WebSocket handshake — against roughly 150ms for the requests that follow. So closing the panel
*parks* the session instead of killing it: the process and its subscriptions stay live for ten
minutes, and a reopen inside that window paints immediately, with the quotes that arrived while it
was closed already buffered. After ten idle minutes it is stopped — and `serve` exits on stdin EOF
regardless, so it never outlives the shell.
- **Nothing polls.** Groups come from `quote.watchlist`, the opening prices from `quote.quote` with
`quote.static_info` for currency and name — a snapshot only to establish what a push cannot carry.
From then on it lives on `quote.subscribe` and the `quote.updated` notifications. There is no
refresh button and no interval; a request happens only when the panel opens, the session
reconnects, the selected group changes, or a symbol crosses into another trading session.
- **Pushes are folded, not chased.** Updates are merged per symbol and applied every 500ms — a
render tick, not a fetch — so a fast-moving group repaints twenty times a minute instead of once
per notification. A `LIVE` indicator sits where a refresh button would be: green while streaming,
`CONNECTING` or `OFFLINE` otherwise.
- **Sparklines from `quote.candlesticks`.** Each row draws sixty five-minute closes with a dashed
rule at the previous close. A row asks for its own chart the first time it is drawn, with at most
three requests in flight, so a group of hundreds only fetches what is on screen.
- **The `holdings` group is special.** The watchlist API always returns it empty, because its members
are the account's own positions — so it is filled from `trade.stock_positions`, exactly as
Longbridge CLI's own TUI does.
- **Portfolio uses the CLI, not `serve`.** `longbridge portfolio --format json` supplies the
cross-currency totals and P/L that `serve` deliberately does not compute; the holdings are then
registered on the same quote feed, so market value and P/L move with the market between snapshots.
- **Last state is cached.** Groups, the selected group and the most recent quote per symbol are
written to disk, so a restart paints the previous rows in milliseconds and refreshes them in the
background instead of showing an empty panel while the session starts.
## Notes
- `serve` needs the same `longbridge auth login` session as every other command, in the same
environment that spawns it. Desktop applications may not inherit your shell's `PATH` — use the
full path to the executable if `longbridge` is not found.
- A `-32601` on a method you expect means the installed CLI predates it; prompt the user to run
`longbridge update`.
- Write commands (`trade.submit_order`, `trade.cancel_order`, `trade.replace_order`) are exposed and
place real orders. There is no confirmation step.
---
# tui
URL: https://open.longbridge.com/docs/cli/tui.md
# longbridge tui
Launch the interactive full-screen terminal UI — a real-time trading dashboard with watchlist
management, live candlestick charts, portfolio view, and stock search. Vim-style keybindings.
## Basic Usage
```bash
longbridge tui
```
## Examples
### Monitor a watchlist in real time
The TUI opens your watchlist and shows live price ticks, change percentages, and volume.
Navigate between stocks with `j`/`k` or arrow keys.
### View candlestick charts
Press `Enter` on any symbol to open the stock detail view with a live K-line chart.
Switch between timeframes with `1m`, `5m`, `1h`, `1d` keybindings.
### Search and add symbols
Press `/` to open the search overlay. Type a symbol name or code to find and add it to
your watchlist.
## Notes
- Requires a valid `longbridge auth login` session
- The TUI shares the same token as CLI commands
- Press `q` or `Ctrl+C` to quit
---
# sharelist
URL: https://open.longbridge.com/docs/cli/watchlist/sharelist.md
# longbridge sharelist
Community stock lists — view your own and subscribed sharelists, browse trending lists, and manage constituent stocks.
Without a subcommand, shows your own sharelists and the ones you have subscribed to.
## Basic Usage
```bash
longbridge sharelist
```
```
My Sharelists:
| ID | Name | Type | Day Chg | YTD Chg | Subscribers |
|-------|------------|---------|---------|---------|-------------|
| 15921 | New Energy | Regular | -0.40% | 6.64% | 500 |
Subscribed Sharelists:
| ID | Name | Type | Day Chg | YTD Chg | Subscribers |
|-------|------------------|---------|---------|---------|-------------|
| 11538 | Dividend Income | Regular | -0.04% | 5.14% | 481 |
```
## Examples
### View sharelist details
```bash
longbridge sharelist detail 15921
```
Shows the sharelist description, creator info, and all constituent stocks with live price and day change fetched via the quote API.
### Browse popular sharelists
```bash
longbridge sharelist popular
longbridge sharelist popular --count 20
```
```
| ID | Name | Type | Day Chg | YTD Chg | Subscribers |
|----------|----------------|----------|---------|---------|-------------|
| 12732294 | Drone Concepts | Official | 20.51% | -3.82% | 768 |
| 29001357 | SpaceX Concept | Regular | 13.34% | 49.86% | 107 |
```
### Create a sharelist
```bash
longbridge sharelist create --name "AI Picks" --description "Top AI infrastructure stocks"
```
Creates a new empty sharelist. Use `add` afterward to populate it with stocks.
### Add or remove stocks
```bash
longbridge sharelist add 15921 TSLA.US NVDA.US AAPL.US
longbridge sharelist remove 15921 AAPL.US
```
### Reorder stocks
```bash
longbridge sharelist sort 15921 NVDA.US TSLA.US
```
Sets the display order for stocks in the sharelist. Symbols not listed are appended after the specified ones.
### Delete a sharelist
```bash
longbridge sharelist delete 15921
```
Permanently deletes the sharelist. This cannot be undone.
## Requirements
A valid OAuth login is required. Run `longbridge auth login` if you have not yet authenticated. Only your own sharelists can be modified; subscribed sharelists are read-only.
---
# watchlist
URL: https://open.longbridge.com/docs/cli/watchlist/watchlist.md
# longbridge watchlist
View and manage your Longbridge watchlists — list groups, add or remove symbols, create new groups, and pin securities to the top.
## Basic Usage
```bash
longbridge watchlist
```
```
Group: all (ID: 2630)
| Symbol | Name | Market | Pinned |
|------------|------------------------------------|--------|--------|
| SPY.US | SPDR S&P 500 | US | yes |
| QQQ.US | Invesco QQQ Trust | US | yes |
| TSLA.US | Tesla | US | |
| AAPL.US | Apple | US | |
| QQQI.US | NEOS Nasdaq-100(R) High Income ETF | US | |
```
## Examples
### View all watchlist groups and their securities
```bash
longbridge watchlist
```
```json
[
{
"id": 2630,
"name": "all",
"securities": [
{ "is_pinned": true, "market": "US", "name": "SPDR S&P 500", "symbol": "SPY.US" },
{ "is_pinned": true, "market": "US", "name": "Invesco QQQ Trust", "symbol": "QQQ.US" },
{ "is_pinned": false, "market": "US", "name": "Tesla", "symbol": "TSLA.US" }
]
}
]
```
Lists all watchlist groups with their IDs, names, and securities. Group IDs are needed for `update`, `pin`, and `delete` subcommands.
### Add symbols to a group
```bash
longbridge watchlist update 2630 --add NVDA.US --add AAPL.US
```
Adds one or more symbols to an existing group. Run `longbridge watchlist` first to find group IDs.
### Remove symbols from a group
```bash
longbridge watchlist update 2630 --remove NVDA.US --remove AAPL.US
```
Removes one or more symbols from an existing group. Run `longbridge watchlist` first to confirm the group ID and current securities.
### Create a new watchlist group
```bash
longbridge watchlist create "Tech Stocks"
```
Creates a new empty watchlist group with the given name. Use `update` afterward to add securities.
### Rename a group
```bash
longbridge watchlist update 2630 --name "New Name"
```
Renames an existing watchlist group. Run `longbridge watchlist` first to find the group ID.
### Pin a security to the top
```bash
longbridge watchlist pin 2630 TSLA.US
```
Pins a security to the top of a watchlist group. Pinned securities appear first and have `is_pinned: true` in the output. Run the command again on a pinned security to unpin it.
### Remove a group
```bash
longbridge watchlist delete 2630
```
Permanently deletes a watchlist group and all its securities. Run `longbridge watchlist` first to confirm the group ID before deleting.
## Requirements
A valid OAuth login is required. Run `longbridge auth login` if you have not yet authenticated.
---
# Security News
URL: https://open.longbridge.com/docs/content/news/news.md
Get the news list for a specified security. Browse the full feed on [News](https://longbridge.com/news).
# latest news for Tesla
longbridge news TSLA.US
# latest news for Apple
longbridge news AAPL.US
# latest news for NVDA
longbridge news NVDA.US
## Request
HTTP Method GET
HTTP URL /v1/content/{symbol}/news
### Path Parameters
| Name | Type | Required | Description |
| ------ | ------ | -------- | -------------------------------------------------------- |
| symbol | string | YES | Stock symbol, use `ticker.region` format, e.g. `AAPL.US` |
### Request Example
```python
from longbridge.openapi import ContentContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = ContentContext(config)
resp = ctx.news("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncContentContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncContentContext.create(config)
resp = await ctx.news("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, ContentContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = ContentContext.new(config)
const resp = await ctx.news('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.content.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
ContentContext ctx = ContentContext.create(config)) {
NewsItem[] resp = ctx.getNews("AAPL.US").get();
for (NewsItem item : resp) System.out.println(item);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, content::ContentContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = ContentContext::new(config);
let resp = ctx.news("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::content;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
ContentContext ctx = ContentContext::create(config);
ctx.news("AAPL.US", [](auto res) {
if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; }
std::cout << "news: " << res->size() << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/content"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
ctx, err := content.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
items, err := ctx.News(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Println("news:", len(items))
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"items": [
{
"id": "279528757",
"title": "Beats cross-industry collaboration breaks the circle with Nike! Apple aims to ignite a new wave of wearable consumer trends, while Nike bets on the narrative of \"sports technology.\"",
"description": "Apple's Beats has collaborated with Nike to launch a limited edition Powerbeats Pro 2 headphones, featuring Nike's Swoosh logo. The headphones will be available online and at select Apple Stores on March 20, priced at $250. This marks Beats' first collaboration with an external sports brand, signifying further synergy between the two companies in branding and product ecosystems. The headphones feature real-time heart rate tracking and a battery life of up to 45 hours",
"url": "https://longbridge.com/news/279528757",
"published_at": "1773805586",
"comments_count": 0,
"likes_count": 0,
"shares_count": 0
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------- | ------------------------------------- |
| 200 | Success | [news_response](#schemanews_response) |
| 500 | Internal error | None |
## Schemas
### news_response
| Name | Type | Required | Description |
| ---------------- | -------- | -------- | ---------------------------------------- |
| items | object[] | true | News list |
| ∟ id | string | true | News ID |
| ∟ title | string | true | Title |
| ∟ description | string | true | Summary/description |
| ∟ url | string | true | Detail page URL |
| ∟ published_at | string | true | Published time, Unix timestamp (seconds) |
| ∟ comments_count | int32 | true | Comment count |
| ∟ likes_count | int32 | true | Like count |
| ∟ shares_count | int32 | true | Share count |
---
# Overview
URL: https://open.longbridge.com/docs/content/overview.md
# Content API Overview
Content APIs provide [security news](https://longbridge.com/news), community topic discussions, and sharelist management. All APIs are accessed via HTTP requests, or through the [SDK](https://open.longbridge.com/sdk).
longbridge sharelist add 123 TSLA.US AAPL.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | integer | YES | Sharelist ID |
| symbols | string[] | YES | Security symbols to add |
## Request Example
```python
from longbridge.openapi import SharelistContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = SharelistContext(config)
ctx.add_securities(123, ["TSLA.US", "AAPL.US"])
```
```python
import asyncio
from longbridge.openapi import AsyncSharelistContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncSharelistContext.create(config)
await ctx.add_securities(123, ["TSLA.US", "AAPL.US"])
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, SharelistContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = SharelistContext.new(config)
await ctx.addSecurities(123, ['TSLA.US', 'AAPL.US'])
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.sharelist.*;
import java.util.Arrays;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
SharelistContext ctx = SharelistContext.create(config)) {
ctx.addSecurities(123, Arrays.asList("TSLA.US", "AAPL.US")).get();
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, sharelist::SharelistContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = SharelistContext::new(config);
ctx.add_securities(123, vec!["TSLA.US".into(), "AAPL.US".into()]).await?;
Ok(())
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/sharelist"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := sharelist.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
if err := c.AddSecurities(context.Background(), 123, []string{"TSLA.US", "AAPL.US"}); err != nil {
log.Fatal(err)
}
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success"
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | None |
| 400 | Bad request | None |
---
# Create Sharelist
URL: https://open.longbridge.com/docs/content/sharelist/create-sharelist.md
Create a new community stock list with an optional initial set of securities.
longbridge sharelist create --name "AI Picks" --description "Top AI infrastructure stocks"
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| name | string | YES | Sharelist name |
| description | string | NO | Description |
| securities | string[] | NO | Initial list of security symbols, e.g. `["AAPL.US", "NVDA.US"]` |
## Request Example
```python
from longbridge.openapi import SharelistContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = SharelistContext(config)
resp = ctx.create_sharelist(name="AI Picks", description="Top AI infrastructure stocks")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncSharelistContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncSharelistContext.create(config)
resp = await ctx.create_sharelist(name="AI Picks", description="Top AI infrastructure stocks")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, SharelistContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = SharelistContext.new(config)
const resp = await ctx.create_sharelist()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.sharelist.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
SharelistContext ctx = SharelistContext.create(config)) {
var resp = ctx.getCreateSharelist().get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, sharelist::SharelistContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = SharelistContext::new(config);
let resp = ctx.create_sharelist().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::sharelist;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
SharelistContext ctx = SharelistContext::create(config);
ctx.create_sharelist([](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/sharelist"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := sharelist.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.CreateSharelist(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"id": 15922
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [CreateSharelistResponse](#CreateSharelistResponse) |
| 400 | Bad request | None |
## Schemas
### CreateSharelistResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | int64 | true | ID of the newly created sharelist |
---
# Delete Sharelist
URL: https://open.longbridge.com/docs/content/sharelist/delete-sharelist.md
Permanently delete a sharelist you own. This action cannot be undone.
longbridge sharelist delete 15921
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | int64 | YES | Sharelist ID (path parameter) |
## Request Example
```python
from longbridge.openapi import SharelistContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = SharelistContext(config)
resp = ctx.delete_sharelist(15921)
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncSharelistContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncSharelistContext.create(config)
resp = await ctx.delete_sharelist(15921)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, SharelistContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = SharelistContext.new(config)
const resp = await ctx.delete_sharelist()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.sharelist.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
SharelistContext ctx = SharelistContext.create(config)) {
var resp = ctx.getDeleteSharelist().get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, sharelist::SharelistContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = SharelistContext::new(config);
let resp = ctx.delete_sharelist().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::sharelist;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
SharelistContext ctx = SharelistContext::create(config);
ctx.delete_sharelist([](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/sharelist"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := sharelist.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.DeleteSharelist(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [DeleteSharelistResponse](#DeleteSharelistResponse) |
| 400 | Bad request | None |
## Schemas
### DeleteSharelistResponse
No response body fields.
---
# List Sharelists
URL: https://open.longbridge.com/docs/content/sharelist/list-sharelist.md
Get all community stock lists (sharelists) created by or subscribed to by the current user.
longbridge sharelist
longbridge sharelist --format json
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| type | string | NO | Filter: `mine` or `subscribed`. Omit for both. |
## Request Example
```python
from longbridge.openapi import SharelistContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = SharelistContext(config)
resp = ctx.list_sharelist()
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncSharelistContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncSharelistContext.create(config)
resp = await ctx.list_sharelist()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, SharelistContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = SharelistContext.new(config)
const resp = await ctx.list_sharelist()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.sharelist.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
SharelistContext ctx = SharelistContext.create(config)) {
var resp = ctx.getListSharelist().get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, sharelist::SharelistContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = SharelistContext::new(config);
let resp = ctx.list_sharelist().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::sharelist;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
SharelistContext ctx = SharelistContext::create(config);
ctx.list_sharelist([](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/sharelist"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := sharelist.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.ListSharelist(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"mine": [
{
"id": 15921,
"name": "AI Picks",
"type": "Regular",
"day_change": "-0.40",
"ytd_change": "6.64",
"subscribers": 500
}
],
"subscribed": []
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [SharelistListResponse](#SharelistListResponse) |
| 400 | Bad request | None |
## Schemas
### SharelistListResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| sharelists | object[] | false | User's own sharelists, see [SharelistInfo](#SharelistInfo) |
| subscribed_sharelists | object[] | false | Subscribed sharelists, see [SharelistInfo](#SharelistInfo) |
| tail_mark | string | false | Pagination cursor for subscribed list |
### SharelistInfo
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | integer | true | Sharelist ID |
| name | string | false | Sharelist name |
| description | string | false | Description |
| cover | string | false | Cover image URL |
| subscribers_count | integer | false | Number of subscribers |
| chg | string | false | Day change percentage |
| this_year_chg | string | false | Year-to-date change percentage |
| subscribed | boolean | false | Whether the current user is subscribed |
| sharelist_type | integer | false | Type: `0`=regular, `3`=official, `4`=industry |
| industry_code | string | false | Industry code (for industry sharelists) |
| stocks | object[] | false | Constituent stocks, see [SharelistStock](#SharelistStock) |
### SharelistStock
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | true | Security symbol |
| code | string | false | Ticker code |
| name | string | false | Security name |
| market | string | false | Market |
| intro | string | false | Brief description |
| last_done | string | false | Latest price |
| change | string | false | Day change percentage |
| trade_status | integer | false | Trade status code |
| latency | boolean | false | Whether quote data is delayed |
| unread_change_log_category | string | false | Unread change log category |
---
# Popular Sharelists
URL: https://open.longbridge.com/docs/content/sharelist/popular-sharelist.md
Get popular/trending sharelists from the community.
longbridge sharelist popular --count 10
## Parameters
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| count | integer | NO | Maximum number of results, default 20 |
## Request Example
```python
from longbridge.openapi import SharelistContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = SharelistContext(config)
resp = ctx.popular(10)
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncSharelistContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncSharelistContext.create(config)
resp = await ctx.popular(10)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, SharelistContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = SharelistContext.new(config)
const resp = await ctx.popular(10)
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.sharelist.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
SharelistContext ctx = SharelistContext.create(config)) {
var resp = ctx.popular(10).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, sharelist::SharelistContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = SharelistContext::new(config);
let resp = ctx.popular(10).await?;
println!("{:?}", resp);
Ok(())
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/sharelist"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := sharelist.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.Popular(context.Background(), 10)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"list": [
{ "id": 123, "name": "AI Picks", "description": "Top AI infrastructure stocks" },
{ "id": 456, "name": "EV Leaders", "description": "Electric vehicle sector leaders" }
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [SharelistListResponse](#SharelistListResponse) |
| 400 | Bad request | None |
## Schemas
### SharelistListResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| sharelists | object[] | false | User's own sharelists, see [SharelistInfo](#SharelistInfo) |
| subscribed_sharelists | object[] | false | Subscribed sharelists, see [SharelistInfo](#SharelistInfo) |
| tail_mark | string | false | Pagination cursor for subscribed list |
### SharelistInfo
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | integer | true | Sharelist ID |
| name | string | false | Sharelist name |
| description | string | false | Description |
| cover | string | false | Cover image URL |
| subscribers_count | integer | false | Number of subscribers |
| chg | string | false | Day change percentage |
| this_year_chg | string | false | Year-to-date change percentage |
| subscribed | boolean | false | Whether the current user is subscribed |
| sharelist_type | integer | false | Type: `0`=regular, `3`=official, `4`=industry |
| industry_code | string | false | Industry code (for industry sharelists) |
| stocks | object[] | false | Constituent stocks, see [SharelistStock](#SharelistStock) |
### SharelistStock
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | true | Security symbol |
| code | string | false | Ticker code |
| name | string | false | Security name |
| market | string | false | Market |
| intro | string | false | Brief description |
| last_done | string | false | Latest price |
| change | string | false | Day change percentage |
| trade_status | integer | false | Trade status code |
| latency | boolean | false | Whether quote data is delayed |
| unread_change_log_category | string | false | Unread change log category |
---
# Remove Securities from Sharelist
URL: https://open.longbridge.com/docs/content/sharelist/remove-securities.md
Remove one or more securities from a sharelist.
longbridge sharelist remove 123 TSLA.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | integer | YES | Sharelist ID |
| symbols | string[] | YES | Security symbols to remove |
## Request Example
```python
from longbridge.openapi import SharelistContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = SharelistContext(config)
ctx.remove_securities(123, ["TSLA.US"])
```
```python
import asyncio
from longbridge.openapi import AsyncSharelistContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncSharelistContext.create(config)
await ctx.remove_securities(123, ["TSLA.US"])
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, SharelistContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = SharelistContext.new(config)
await ctx.removeSecurities(123, ['TSLA.US'])
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.sharelist.*;
import java.util.Arrays;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
SharelistContext ctx = SharelistContext.create(config)) {
ctx.removeSecurities(123, Arrays.asList("TSLA.US")).get();
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, sharelist::SharelistContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = SharelistContext::new(config);
ctx.remove_securities(123, vec!["TSLA.US".into()]).await?;
Ok(())
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/sharelist"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := sharelist.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
if err := c.RemoveSecurities(context.Background(), 123, []string{"TSLA.US"}); err != nil {
log.Fatal(err)
}
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success"
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | None |
| 400 | Bad request | None |
---
# Sharelist Detail
URL: https://open.longbridge.com/docs/content/sharelist/sharelist-detail.md
Get sharelist detail including name, description, and constituent stocks.
longbridge sharelist detail 123
## Parameters
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | integer | YES | Sharelist ID |
## Request Example
```python
from longbridge.openapi import SharelistContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = SharelistContext(config)
resp = ctx.detail(123)
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncSharelistContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncSharelistContext.create(config)
resp = await ctx.detail(123)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, SharelistContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = SharelistContext.new(config)
const resp = await ctx.detail(123)
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.sharelist.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
SharelistContext ctx = SharelistContext.create(config)) {
var resp = ctx.detail(123).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, sharelist::SharelistContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = SharelistContext::new(config);
let resp = ctx.detail(123).await?;
println!("{:?}", resp);
Ok(())
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/sharelist"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := sharelist.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.Detail(context.Background(), 123)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"id": 123,
"name": "AI Picks",
"description": "Top AI infrastructure stocks",
"securities": ["AAPL.US", "NVDA.US"]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [SharelistDetail](#SharelistDetail) |
| 400 | Bad request | None |
## Schemas
### SharelistDetailResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| sharelist | object | true | Sharelist information |
| scopes | object | false | Subscription scope info |
### SharelistInfo
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | integer | true | Sharelist ID |
| name | string | false | Name |
| description | string | false | Description |
| cover | string | false | Cover image URL |
| subscribers_count | integer | false | Number of subscribers |
| chg | string | false | Day change percentage |
| this_year_chg | string | false | Year-to-date change |
| subscribed | boolean | false | Whether subscribed |
| sharelist_type | integer | false | Type: `0`=regular, `3`=official, `4`=industry |
| industry_code | string | false | Industry code |
| stocks | object[] | false | Constituent stocks, see [SharelistStock](#SharelistStock) |
### SharelistScopes
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| is_self | boolean | false | Whether the current user is the creator |
| subscription | boolean | false | Whether the current user is subscribed |
---
# Sort Securities in Sharelist
URL: https://open.longbridge.com/docs/content/sharelist/sort-securities.md
Reorder the securities in a sharelist. The symbols list defines the new order.
longbridge sharelist sort 123 TSLA.US AAPL.US 700.HK
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | integer | YES | Sharelist ID |
| symbols | string[] | YES | Security symbols in the desired order |
## Request Example
```python
from longbridge.openapi import SharelistContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = SharelistContext(config)
ctx.sort_securities(123, ["TSLA.US", "AAPL.US", "700.HK"])
```
```python
import asyncio
from longbridge.openapi import AsyncSharelistContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncSharelistContext.create(config)
await ctx.sort_securities(123, ["TSLA.US", "AAPL.US", "700.HK"])
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, SharelistContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = SharelistContext.new(config)
await ctx.sortSecurities(123, ['TSLA.US', 'AAPL.US', '700.HK'])
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.sharelist.*;
import java.util.Arrays;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
SharelistContext ctx = SharelistContext.create(config)) {
ctx.sortSecurities(123, Arrays.asList("TSLA.US", "AAPL.US", "700.HK")).get();
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, sharelist::SharelistContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = SharelistContext::new(config);
ctx.sort_securities(123, vec!["TSLA.US".into(), "AAPL.US".into(), "700.HK".into()]).await?;
Ok(())
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/sharelist"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := sharelist.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
if err := c.SortSecurities(context.Background(), 123, []string{"TSLA.US", "AAPL.US", "700.HK"}); err != nil {
log.Fatal(err)
}
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success"
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | None |
| 400 | Bad request | None |
---
# Update Sharelist
URL: https://open.longbridge.com/docs/content/sharelist/update-sharelist.md
Add, remove, or reorder securities in a sharelist, or rename it.
longbridge sharelist add 15921 TSLA.US NVDA.US AAPL.US
longbridge sharelist remove 15921 AAPL.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | int64 | YES | Sharelist ID (path parameter) |
| name | string | NO | New name. Omit to keep existing. |
| mode | string | NO | Operation mode for securities: `add`, `remove`, or `replace` |
| securities | string[] | NO | Security symbols affected by the operation |
## Request Example
```python
from longbridge.openapi import SharelistContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = SharelistContext(config)
resp = ctx.update_sharelist(15921, mode="add", securities=["TSLA.US", "NVDA.US"])
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncSharelistContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncSharelistContext.create(config)
resp = await ctx.update_sharelist(15921, mode="add", securities=["TSLA.US", "NVDA.US"])
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, SharelistContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = SharelistContext.new(config)
const resp = await ctx.update_sharelist()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.sharelist.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
SharelistContext ctx = SharelistContext.create(config)) {
var resp = ctx.getUpdateSharelist().get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, sharelist::SharelistContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = SharelistContext::new(config);
let resp = ctx.update_sharelist().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::sharelist;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
SharelistContext ctx = SharelistContext::create(config);
ctx.update_sharelist([](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/sharelist"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := sharelist.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.UpdateSharelist(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [UpdateSharelistResponse](#UpdateSharelistResponse) |
| 400 | Bad request | None |
## Schemas
### UpdateSharelistResponse
No response body fields.
---
# Create Topic
URL: https://open.longbridge.com/docs/content/topics/create-topic.md
Create a new community topic on [Topics](https://longbridge.com/topics). Two content types are supported:
| Type | `title` | `body` format | Notes |
| ---------------- | ------------ | --------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `post` (default) | Optional | Plain text only | Markdown syntax (e.g. `**bold**`, `# heading`) is NOT rendered — it appears as literal characters, similar to a tweet. |
| `article` | **Required** | Markdown | The server converts Markdown to HTML for display. Supports headers, tables, bold, code blocks, etc. |
Only users who have opened a **Longbridge account and hold assets** are allowed to publish community topics and replies via Longbridge Developers API or CLI. Returns `403` otherwise.
Stock symbols mentioned in the body (e.g. `700.HK`, `TSLA.US`) are automatically recognized and linked as related stocks by the platform. Use `tickers` to associate additional symbols not explicitly mentioned in the body.
> ⚠️ Do not abuse symbol linking to associate unrelated stocks. Content moderation may restrict publishing or mute the account.
**Rate limit:** Max 3 topics per user per minute and 10 per 24 hours. Exceeding the limit returns `429`.
> ⚠️ Rate limit thresholds are for reference only and may be adjusted by the platform at any time.
# publish a topic for Tesla
longbridge topic create --body "Tesla Q1 earnings analysis" --tickers TSLA.US
# publish a topic for Apple
longbridge topic create --body "Apple WWDC preview" --tickers AAPL.US
## Request
HTTP Method POST
HTTP URL /v1/content/topics
### Request Body
| Name | Type | Required | Description |
| ---------- | -------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| title | string | YES (for article) | Topic title. Required when `topic_type` is `article`; optional for `post`. |
| body | string | YES | Topic body. \n- For `post`: plain text only — Markdown is not rendered.\n- For `article`: Markdown is supported. |
| topic_type | string | NO | Content type: `post` (plain text, default) or `article` (Markdown). |
| tickers | string[] | NO | Related security symbols, format `\{symbol\}.\{market\}` (e.g. `["AAPL.US", "700.HK"]`). Maximum 10. **Note:** Symbols mentioned in the body (e.g. `700.HK`, `TSLA.US`) are automatically recognized and linked by the platform. Use `tickers` to associate additional symbols not explicitly mentioned in the body. |
| hashtags | string[] | NO | Hashtag names (e.g. `["earnings", "fed"]`). Maximum 1. |
### Request Example
# Short post — plain text (default). Markdown is NOT rendered.
longbridge topic create --body "Bullish on 700.HK today"
# Short post with related tickers
longbridge topic create --body "NVDA GTC highlights" --tickers NVDA.US,700.HK
# Article — Markdown body, title is required
longbridge topic create --title "My Analysis" --body "**Bullish** on 700.HK because..." --type article
# Article from a Markdown file
longbridge topic create --title "Q4 Earnings Preview" --body "$(cat analysis.md)" --type article
# JSON output
longbridge topic create --body "Test post" --format json
```python
from longbridge.openapi import ContentContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = ContentContext(config)
# Short post (plain text)
resp = ctx.create_topic(
title="",
body="Bullish on 700.HK today",
topic_type="post",
tickers=["700.HK"],
)
print(resp)
# Article (Markdown)
resp = ctx.create_topic(
title="My Analysis",
body="**Bullish** on 700.HK because...",
topic_type="article",
tickers=["700.HK"],
license=1,
)
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncContentContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncContentContext.create(config)
resp = await ctx.create_topic(
title="My Analysis",
body="**Bullish** on 700.HK because...",
topic_type="article",
tickers=["700.HK"],
)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, ContentContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = ContentContext.new(config)
// Article (Markdown body)
const resp = await ctx.createTopic({
title: 'My Analysis',
body: '**Bullish** on 700.HK because...',
topicType: 'article',
tickers: ['700.HK'],
})
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.content.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
ContentContext ctx = ContentContext.create(config)) {
// Article (Markdown body, title required)
CreateTopicOptions opts = new CreateTopicOptions("My Analysis", "**Bullish** on 700.HK because...")
.setTopicType("article")
.setTickers(new String[]{"700.HK"})
.setLicense(1);
OwnedTopic resp = ctx.createTopic(opts).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, content::{ContentContext, CreateTopicOptions}, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = ContentContext::new(config);
// Article (Markdown body, title required)
let opts = CreateTopicOptions {
title: "My Analysis".to_string(),
body: "**Bullish** on 700.HK because...".to_string(),
topic_type: Some("article".to_string()),
tickers: Some(vec!["700.HK".to_string()]),
hashtags: None,
license: Some(1),
};
let resp = ctx.create_topic(opts).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::content;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
ContentContext ctx = ContentContext::create(config);
// Article (Markdown body, title required)
CreateTopicOptions opts;
opts.title = "My Analysis";
opts.body = "**Bullish** on 700.HK because...";
opts.topic_type = "article";
opts.tickers = {"700.HK"};
ctx.create_topic(opts, [](auto res) {
if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; }
std::cout << "created topic: " << res->id << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/content"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
ctx, err := content.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
// Article (Markdown body, title required)
opts := content.CreateTopicOptions{
Title: "My Analysis",
Body: "**Bullish** on 700.HK because...",
TopicType: "article",
Tickers: []string{"700.HK"},
}
resp, err := ctx.CreateTopic(context.Background(), opts)
if err != nil {
log.Fatal(err)
}
fmt.Printf("created topic: %s\n", resp.ID)
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"item": {
"id": "39304657",
"title": "My View on AAPL",
"topic_type": "article",
"tickers": ["AAPL.US"],
"hashtags": ["earnings"],
"created_at": "1742000000"
}
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ---------------------------------------------------------------------- | ----------------------------------------------------- |
| 200 | Success | [create_topic_response](#schemacreate_topic_response) |
| 403 | Forbidden — user has not opened a Longbridge account or has no assets | None |
| 429 | Too Many Requests — rate limit exceeded (3/min or 10/24h); retry later | None |
| 500 | Internal error | None |
## Schemas
### create_topic_response
| Name | Type | Required | Description |
| ---------------- | -------- | -------- | --------------------------------------------------- |
| item | object | true | Newly created topic details |
| ∟ id | string | true | Topic ID |
| ∟ title | string | false | Topic title |
| ∟ description | string | false | Plain-text summary (auto-generated from body) |
| ∟ body | string | false | Full body text (Markdown for `article`) |
| ∟ topic_type | string | false | Topic type. One of `article`, `post` |
| ∟ tickers | string[] | false | Associated security symbols |
| ∟ hashtags | string[] | false | Associated hashtag names |
| ∟ images | object[] | false | Image list |
| ∟∟ url | string | false | Original image URL |
| ∟∟ sm | string | false | Small thumbnail URL |
| ∟∟ lg | string | false | Large thumbnail URL |
| ∟ likes_count | int32 | false | Number of likes |
| ∟ comments_count | int32 | false | Number of replies |
| ∟ views_count | int32 | false | Number of views |
| ∟ shares_count | int32 | false | Number of shares |
| ∟ detail_url | string | false | Direct URL to the topic |
| ∟ author | object | false | Author information |
| ∟∟ member_id | string | false | Author member ID |
| ∟∟ name | string | false | Author display name |
| ∟∟ avatar | string | false | Author avatar URL |
| ∟ created_at | string | true | Unix timestamp (seconds) when the topic was created |
| ∟ updated_at | string | false | Unix timestamp (seconds) of last update |
---
# Create Topic Reply
URL: https://open.longbridge.com/docs/content/topics/create-topic-reply.md
Post a reply to a community topic. Supports nesting under an existing reply. Browse the community on [Topics](https://longbridge.com/topics).
Only users who have opened a **[Longbridge account](https://longbridge.com/hk/download) and hold assets** are allowed to publish community topics and replies via Longbridge Developers API or CLI. Returns `403` otherwise.
**Body format:** Plain text only — HTML and Markdown are **not** rendered.
Stock symbols mentioned in the body (e.g. `700.HK`, `TSLA.US`) are automatically recognized and linked as related stocks by the platform.
⚠️ Do not abuse symbol linking to associate unrelated stocks. Content moderation may restrict publishing or mute the account.
**Rate limit:** The first 3 replies per user per topic have no wait requirement. After that, each subsequent reply must wait an incrementally longer interval since the previous one:
| Reply # (after 3rd) | Required wait |
| ------------------- | ------------- |
| 4th | 3 s |
| 5th | 5 s |
| 6th | 8 s |
| 7th | 13 s |
| 8th | 21 s |
| 9th | 34 s |
| 10th+ | 55 s (cap) |
Exceeding the limit returns `429`.
> ⚠️ Rate limit thresholds are for reference only and may be adjusted by the platform at any time.
longbridge topic create-reply 6993508780031016960 --body "Great analysis!"
## Request
HTTP Method POST
HTTP URL /v1/content/topics/:topic_id/comments
### Path Parameters
| Name | Type | Required | Description |
| -------- | ------ | -------- | ------------------------------------- |
| topic_id | string | YES | Topic ID (e.g. `6993508780031016960`) |
### Request Body
| Name | Type | Required | Description |
| ----------- | ------ | -------- | ---------------------------------------------------------------------------------------------------------------------- |
| body | string | YES | Reply body. Plain text only — Markdown is not rendered. Symbols mentioned in the body are auto-linked by the platform. |
| reply_to_id | string | NO | ID of the reply to nest under. Omit or set to `"0"` for a top-level reply. |
### Request Example
# Top-level reply
longbridge topic create-reply 6993508780031016960 --body "Great analysis!"
# Nested reply
longbridge topic create-reply 6993508780031016960 --body "I agree." --reply-to 7001234567890123456
```python
from longbridge.openapi import ContentContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = ContentContext(config)
# Top-level reply
reply = ctx.create_topic_reply("6993508780031016960", body="Great analysis!")
print(reply.id)
# Nested reply
nested = ctx.create_topic_reply(
"6993508780031016960",
body="I agree.",
reply_to_id="7001234567890123456",
)
print(nested.id)
```
```python
import asyncio
from longbridge.openapi import AsyncContentContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncContentContext.create(config)
reply = await ctx.create_topic_reply("6993508780031016960", body="Great analysis!")
print(reply.id)
if __name__ == "__main__":
asyncio.run(main())
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/content"
)
func main() {
conf, err := config.NewFromEnv()
if err != nil {
log.Fatal(err)
}
ctx, err := content.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
reply, err := ctx.CreateTopicReply(context.Background(), "6993508780031016960",
&content.CreateReplyOptions{Body: "Great analysis!"},
)
if err != nil {
log.Fatal(err)
}
fmt.Println("reply id:", reply.ID)
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, content::{ContentContext, CreateReplyOptions}, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = ContentContext::new(config);
let reply = ctx.create_topic_reply(
"6993508780031016960",
CreateReplyOptions { body: "Great analysis!".to_string(), reply_to_id: None },
).await?;
println!("reply id: {}", reply.id);
Ok(())
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"item": {
"id": "7001234567890123460",
"topic_id": "6993508780031016960",
"body": "Great analysis!",
"reply_to_id": "0",
"author": {
"member_id": "10086",
"name": "Jane Doe",
"avatar": "https://example.com/avatar.jpg"
},
"images": [],
"likes_count": 0,
"comments_count": 0,
"created_at": "1742002000"
}
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | --------------------------------------------------------------------- | ----------------------------------------------------- |
| 200 | Success | [create_reply_response](#schemacreate_reply_response) |
| 403 | Forbidden — user has not opened a Longbridge account or has no assets | None |
| 429 | Too Many Requests — rate limit exceeded; wait and retry | None |
| 500 | Internal error | None |
## Schemas
### create_reply_response
| Name | Type | Required | Description |
| ---------------- | -------- | -------- | ----------------------------------------- |
| item | object | true | Created reply details |
| ∟ id | string | true | Reply ID |
| ∟ topic_id | string | true | Parent topic ID |
| ∟ body | string | false | Reply body (plain text) |
| ∟ reply_to_id | string | false | Parent reply ID; `"0"` = top-level reply |
| ∟ author | object | false | Author info |
| ∟∟ member_id | string | false | Author member ID |
| ∟∟ name | string | false | Author display name |
| ∟∟ avatar | string | false | Author avatar URL |
| ∟ images | object[] | false | Attached images |
| ∟∟ url | string | false | Original image URL |
| ∟∟ sm | string | false | Small thumbnail URL |
| ∟∟ lg | string | false | Large image URL |
| ∟ likes_count | int32 | false | Likes count |
| ∟ comments_count | int32 | false | Nested replies count |
| ∟ created_at | string | true | Creation time as Unix timestamp (seconds) |
---
# My Topics
URL: https://open.longbridge.com/docs/content/topics/my-topics.md
Get the list of topics I have published. View them on [Topics](https://longbridge.com/topics).
longbridge topic mine
## Request
HTTP Method GET
HTTP URL /v1/content/topics/mine
### Query Parameters
| Name | Type | Required | Description |
| ---------- | ------ | -------- | -------------------------------------------------------------------------------------------- |
| page | int32 | NO | Page number (1-based). Defaults to `1`. |
| size | int32 | NO | Number of items per page, range 1–500. Defaults to `50`. |
| topic_type | string | NO | Filter by type. One of `article` (long-form), `post` (short post). Omit to return all types. |
### Request Example
longbridge topic mine # All types (default: 50 per page)
longbridge topic mine --type article # Articles only
longbridge topic mine --type post --size 10 # Short posts, 10 per page
longbridge topic mine --page 2 # Page 2
longbridge topic mine --format json # JSON output for scripting
```python
from longbridge.openapi import ContentContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = ContentContext(config)
resp = ctx.topics_mine(page=1, size=50, topic_type="article")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncContentContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncContentContext.create(config)
resp = await ctx.topics_mine(page=1, size=50, topic_type="article")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, ContentContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = ContentContext.new(config)
const resp = await ctx.topicsMine({ page: 1, size: 50, topicType: 'article' })
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.content.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
ContentContext ctx = ContentContext.create(config)) {
ListMyTopicsOptions opts = new ListMyTopicsOptions()
.setPage(1).setSize(50).setTopicType("article");
OwnedTopic[] resp = ctx.getTopicsMine(opts).get();
for (OwnedTopic item : resp) System.out.println(item);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, content::{ContentContext, ListMyTopicsOptions}, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = ContentContext::new(config);
let opts = ListMyTopicsOptions {
page: Some(1),
size: Some(50),
topic_type: Some("article".to_string()),
};
let resp = ctx.topics_mine(opts).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::content;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
ContentContext ctx = ContentContext::create(config);
ListMyTopicsOptions opts;
opts.page = 1;
opts.size = 50;
opts.topic_type = "article";
ctx.topics_mine(opts, [](auto res) {
if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; }
std::cout << "my topics: " << res->size() << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/content"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
ctx, err := content.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
opts := content.ListMyTopicsOptions{Page: 1, Size: 50, TopicType: "article"}
items, err := ctx.TopicsMine(context.Background(), opts)
if err != nil {
log.Fatal(err)
}
fmt.Println("my topics:", len(items))
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"items": [
{
"id": "39304657",
"title": "My Analysis on AAPL",
"description": "A brief summary of my article...",
"body": "Full markdown content here...",
"topic_type": "article",
"tickers": ["AAPL.US"],
"hashtags": ["earnings"],
"images": [],
"likes_count": 12,
"comments_count": 3,
"views_count": 200,
"shares_count": 1,
"license": 1,
"detail_url": "https://longbridge.com/topics/39304657",
"author": {
"member_id": "10086",
"name": "John",
"avatar": "https://example.com/avatar.jpg"
},
"created_at": "1742000000",
"updated_at": "1742000000"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------- | ----------------------------------------------- |
| 200 | Success | [my_topics_response](#schemamy_topics_response) |
| 500 | Internal error | None |
## Schemas
### my_topics_response
| Name | Type | Required | Description |
| ---------------- | -------- | -------- | --------------------------------------------------------------------- |
| items | object[] | true | Topic list |
| ∟ id | string | true | Topic ID |
| ∟ title | string | false | Topic title (may be empty for short posts) |
| ∟ description | string | false | Plain-text summary of the topic body |
| ∟ body | string | false | Full topic body in Markdown format |
| ∟ topic_type | string | true | Topic type. One of `article`, `post` |
| ∟ tickers | string[] | false | Associated security symbols (e.g. `["AAPL.US", "700.HK"]`) |
| ∟ hashtags | string[] | false | Associated hashtag names |
| ∟ images | object[] | false | Images attached to the topic |
| ∟∟ url | string | false | Original image URL |
| ∟∟ sm | string | false | Small thumbnail URL |
| ∟∟ lg | string | false | Large thumbnail URL |
| ∟ likes_count | int32 | false | Number of likes |
| ∟ comments_count | int32 | false | Number of comments |
| ∟ views_count | int32 | false | Number of views |
| ∟ shares_count | int32 | false | Number of shares |
| ∟ license | int32 | false | Copyright declaration. `0` = none, `1` = original, `2` = non-original |
| ∟ detail_url | string | false | Link to the topic detail page |
| ∟ author | object | false | Author information |
| ∟∟ member_id | string | false | Author member ID |
| ∟∟ name | string | false | Author display name |
| ∟∟ avatar | string | false | Author avatar URL |
| ∟ created_at | string | true | Unix timestamp (seconds) when the topic was created |
| ∟ updated_at | string | false | Unix timestamp (seconds) when the topic was last updated |
---
# Topic Detail
URL: https://open.longbridge.com/docs/content/topics/topic-detail.md
Get the full details of a community topic by its ID, including the body (Markdown), author info, associated tickers and hashtags, engagement counts, and the direct URL. View the topic on [Topics](https://longbridge.com/topics).
longbridge topic detail 6993508780031016960
## Request
HTTP Method GET
HTTP URL /v1/content/topics/:id
### Path Parameters
| Name | Type | Required | Description |
| ---- | ------ | -------- | ------------------------------------- |
| id | string | YES | Topic ID (e.g. `6993508780031016960`) |
### Request Example
longbridge topic detail 6993508780031016960
```python
from longbridge.openapi import ContentContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = ContentContext(config)
topic = ctx.topic_detail("6993508780031016960")
print(topic)
```
```python
import asyncio
from longbridge.openapi import AsyncContentContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncContentContext.create(config)
topic = await ctx.topic_detail("6993508780031016960")
print(topic)
if __name__ == "__main__":
asyncio.run(main())
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/content"
)
func main() {
conf, err := config.NewFromEnv()
if err != nil {
log.Fatal(err)
}
ctx, err := content.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
topic, err := ctx.TopicDetail(context.Background(), "6993508780031016960")
if err != nil {
log.Fatal(err)
}
fmt.Printf("title: %s\nauthor: %s\nlikes: %d\n", topic.Title, topic.Author.Name, topic.LikesCount)
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, content::ContentContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = ContentContext::new(config);
let topic = ctx.topic_detail("6993508780031016960").await?;
println!("{:?}", topic);
Ok(())
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"item": {
"id": "6993508780031016960",
"title": "My Analysis on AAPL",
"description": "Brief plain-text summary...",
"body": "**Bullish** on AAPL because...",
"topic_type": "article",
"tickers": ["AAPL.US"],
"hashtags": ["earnings"],
"images": [
{
"url": "https://cdn.longbridge.com/img/abc.jpg",
"sm": "https://cdn.longbridge.com/img/abc_sm.jpg",
"lg": "https://cdn.longbridge.com/img/abc_lg.jpg"
}
],
"likes_count": 42,
"comments_count": 7,
"views_count": 1500,
"shares_count": 3,
"detail_url": "https://longbridge.com/topics/6993508780031016960",
"author": {
"member_id": "10086",
"name": "Jane Doe",
"avatar": "https://example.com/avatar.jpg"
},
"created_at": "1742000000",
"updated_at": "1742001000"
}
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------- | ----------------------------------------------------- |
| 200 | Success | [topic_detail_response](#schematopic_detail_response) |
| 500 | Internal error | None |
## Schemas
### topic_detail_response
| Name | Type | Required | Description |
| ---------------- | -------- | -------- | ---------------------------------------------------------- |
| item | object | true | Topic detail object |
| ∟ id | string | true | Topic ID |
| ∟ title | string | false | Title (may be empty for short posts) |
| ∟ description | string | false | Plain-text excerpt |
| ∟ body | string | false | Markdown body |
| ∟ topic_type | string | true | Content type: `article` or `post` |
| ∟ tickers | string[] | false | Associated security symbols (e.g. `["AAPL.US", "700.HK"]`) |
| ∟ hashtags | string[] | false | Hashtag names |
| ∟ images | object[] | false | Attached images |
| ∟∟ url | string | false | Original image URL |
| ∟∟ sm | string | false | Small thumbnail URL |
| ∟∟ lg | string | false | Large image URL |
| ∟ likes_count | int32 | false | Likes count |
| ∟ comments_count | int32 | false | Replies count |
| ∟ views_count | int32 | false | Views count |
| ∟ shares_count | int32 | false | Shares count |
| ∟ detail_url | string | false | URL to the topic detail page |
| ∟ author | object | false | Author info |
| ∟∟ member_id | string | false | Author member ID |
| ∟∟ name | string | false | Author display name |
| ∟∟ avatar | string | false | Author avatar URL |
| ∟ created_at | string | true | Creation time as Unix timestamp (seconds) |
| ∟ updated_at | string | false | Last updated time as Unix timestamp (seconds) |
---
# Topic Replies
URL: https://open.longbridge.com/docs/content/topics/topic-replies.md
Get a paginated list of replies for a specific topic. Browse the discussion on [Topics](https://longbridge.com/topics).
Each reply includes author info, body (plain text), engagement counts, and a `reply_to_id` field: `"0"` indicates a top-level reply; any other value identifies the parent reply for nested replies.
longbridge topic replies 6993508780031016960
longbridge topic replies 6993508780031016960 --page 2 --size 20
## Request
HTTP Method GET
HTTP URL /v1/content/topics/:topic_id/comments
### Path Parameters
| Name | Type | Required | Description |
| -------- | ------ | -------- | ------------------------------------- |
| topic_id | string | YES | Topic ID (e.g. `6993508780031016960`) |
### Query Parameters
| Name | Type | Required | Description |
| ---- | ----- | -------- | --------------------------------------------- |
| page | int32 | NO | Page number (1-based). Defaults to `1`. |
| size | int32 | NO | Items per page, range 1–50. Defaults to `20`. |
### Request Example
longbridge topic replies 6993508780031016960
longbridge topic replies 6993508780031016960 --page 2 --size 20
```python
from longbridge.openapi import ContentContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = ContentContext(config)
replies = ctx.list_topic_replies("6993508780031016960", page=1, size=20)
for r in replies:
print(r.author.name, r.body)
```
```python
import asyncio
from longbridge.openapi import AsyncContentContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncContentContext.create(config)
replies = await ctx.list_topic_replies("6993508780031016960", page=1, size=20)
for r in replies:
print(r.author.name, r.body)
if __name__ == "__main__":
asyncio.run(main())
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/content"
)
func main() {
conf, err := config.NewFromEnv()
if err != nil {
log.Fatal(err)
}
ctx, err := content.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
replies, err := ctx.ListTopicReplies(context.Background(), "6993508780031016960",
&content.ListTopicRepliesOptions{Page: 1, Size: 20},
)
if err != nil {
log.Fatal(err)
}
for _, r := range replies {
fmt.Printf("[%s] %s: %s\n", r.ID, r.Author.Name, r.Body)
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, content::{ContentContext, ListTopicRepliesOptions}, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = ContentContext::new(config);
let replies = ctx.list_topic_replies(
"6993508780031016960",
ListTopicRepliesOptions { page: Some(1), size: Some(20) },
).await?;
for r in &replies {
println!("{}: {}", r.author.name, r.body);
}
Ok(())
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"items": [
{
"id": "7001234567890123456",
"topic_id": "6993508780031016960",
"body": "Great analysis!",
"reply_to_id": "0",
"author": {
"member_id": "10087",
"name": "John Smith",
"avatar": "https://example.com/avatar2.jpg"
},
"images": [],
"likes_count": 5,
"comments_count": 2,
"created_at": "1742001500"
},
{
"id": "7001234567890123457",
"topic_id": "6993508780031016960",
"body": "I disagree on the valuation part.",
"reply_to_id": "7001234567890123456",
"author": {
"member_id": "10088",
"name": "Alice Lee",
"avatar": "https://example.com/avatar3.jpg"
},
"images": [],
"likes_count": 1,
"comments_count": 0,
"created_at": "1742001800"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------- | ------------------------------------------------------- |
| 200 | Success | [topic_replies_response](#schematopic_replies_response) |
| 500 | Internal error | None |
## Schemas
### topic_replies_response
| Name | Type | Required | Description |
| ---------------- | -------- | -------- | ----------------------------------------- |
| items | object[] | true | List of replies |
| ∟ id | string | true | Reply ID |
| ∟ topic_id | string | true | Parent topic ID |
| ∟ body | string | false | Reply body (plain text) |
| ∟ reply_to_id | string | false | Parent reply ID; `"0"` = top-level reply |
| ∟ author | object | false | Author info |
| ∟∟ member_id | string | false | Author member ID |
| ∟∟ name | string | false | Author display name |
| ∟∟ avatar | string | false | Author avatar URL |
| ∟ images | object[] | false | Attached images |
| ∟∟ url | string | false | Original image URL |
| ∟∟ sm | string | false | Small thumbnail URL |
| ∟∟ lg | string | false | Large image URL |
| ∟ likes_count | int32 | false | Likes count |
| ∟ comments_count | int32 | false | Nested replies count |
| ∟ created_at | string | true | Creation time as Unix timestamp (seconds) |
---
# Topics by Symbol
URL: https://open.longbridge.com/docs/content/topics/topics.md
Get the topic/discussion list for a specified security. Browse the full community on [Topics](https://longbridge.com/topics).
# community discussion topics for Tesla
longbridge topic TSLA.US
# community discussion topics for Apple
longbridge topic AAPL.US
# community discussion topics for NVDA
longbridge topic NVDA.US
## Request
HTTP Method GET
HTTP URL /v1/content/{symbol}/topics
### Path Parameters
| Name | Type | Required | Description |
| ------ | ------ | -------- | -------------------------------------------------------- |
| symbol | string | YES | Stock symbol, use `ticker.region` format, e.g. `AAPL.US` |
### Request Example
```python
from longbridge.openapi import ContentContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = ContentContext(config)
resp = ctx.topics("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncContentContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncContentContext.create(config)
resp = await ctx.topics("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, ContentContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = ContentContext.new(config)
const resp = await ctx.topics('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.content.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
ContentContext ctx = ContentContext.create(config)) {
TopicItem[] resp = ctx.getTopics("AAPL.US").get();
for (TopicItem item : resp) System.out.println(item);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, content::ContentContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = ContentContext::new(config);
let resp = ctx.topics("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::content;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
ContentContext ctx = ContentContext::create(config);
ctx.topics("AAPL.US", [](auto res) {
if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; }
std::cout << "topics: " << res->size() << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/content"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
ctx, err := content.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
items, err := ctx.Topics(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Println("topics:", len(items))
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"items": [
{
"id": "39304657",
"title": "NVDA GTC in focus; Alibaba 'Token strategy' ramps up | Daily News Recap",
"description": "0317 | Dolphin Research Focus: 🐬 Stock #1, $NVIDIA(NVDA.US) — NVIDIA's GTC 2026 officially kicked off, and founder & CEO Jensen Huang delivered the keynote.He announced a Vera Rubin Space Module under the next-gen Vera Rubin architecture, designed for orbital data centers, delivering 25x performance vs. H100.He also unveiled a partnership with Groq to co-develop new LPU chips...",
"url": "https://longbridge.com/topics/39304657",
"published_at": "1773736144",
"comments_count": 1,
"likes_count": 7,
"shares_count": 4
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------- | ----------------------------------------- |
| 200 | Success | [topics_response](#schematopics_response) |
| 500 | Internal error | None |
## Schemas
### topics_response
| Name | Type | Required | Description |
| ---------------- | -------- | -------- | ---------------------------------------- |
| items | object[] | true | Topic list |
| ∟ id | string | true | Topic ID |
| ∟ title | string | true | Title |
| ∟ description | string | true | Summary/description |
| ∟ url | string | true | Detail page URL |
| ∟ published_at | string | true | Published time, Unix timestamp (seconds) |
| ∟ comments_count | int32 | true | Comment count |
| ∟ likes_count | int32 | true | Like count |
| ∟ shares_count | int32 | true | Share count |
---
# Business Segments
URL: https://open.longbridge.com/docs/fundamental/fundamental/business-segments.md
Get the current-period revenue segment breakdown for a listed company.
longbridge business-segments AAPL.US
longbridge business-segments 700.HK
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `AAPL.US` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.business_segments("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.business_segments("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.businessSegments('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getBusinessSegments("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.business_segments("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.business_segments("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.BusinessSegments(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"date": "20260331",
"total": "124300000000",
"currency": "USD",
"business": [
{"name": "iPhone", "percent": "56.19"},
{"name": "Services", "percent": "21.96"},
{"name": "Mac", "percent": "8.04"},
{"name": "iPad", "percent": "7.00"},
{"name": "Wearables", "percent": "6.81"}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [BusinessSegmentsResponse](#BusinessSegmentsResponse) |
| 400 | Bad request | None |
## Schemas
### BusinessSegmentsResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| date | string | false | Report period in YYYYMMDD format, e.g. `20260331` |
| total | string | false | Total revenue for the period |
| currency | string | false | Currency code, e.g. `USD` |
| business | object[] | false | Business segment list |
| ∟ name | string | false | Segment name |
| ∟ percent | string | false | Revenue share percentage, e.g. `40.56` |
---
# Business Segments History
URL: https://open.longbridge.com/docs/fundamental/fundamental/business-segments-history.md
Get historical business segment revenue trends across reporting periods.
longbridge business-segments AAPL.US --history
longbridge business-segments AAPL.US --history --report qf
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `AAPL.US` |
| report | string | NO | Report type: `qf` (quarterly) / `saf` (semi-annual) / `af` (annual) |
| cate | string | NO | Segment category filter |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.business_segments_history("AAPL.US", report="qf")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.business_segments_history("AAPL.US", report="qf")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.businessSegmentsHistory('AAPL.US', { report: 'qf' })
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getBusinessSegmentsHistory("AAPL.US", "qf", null).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.business_segments_history("AAPL.US", Some("qf"), None).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.business_segments_history("AAPL.US", "qf", "", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.BusinessSegmentsHistory(context.Background(), "AAPL.US", "qf", "")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"historical": [
{
"date": "20260331",
"total": "124300000000",
"currency": "USD",
"business": [
{"name": "Americas", "percent": "40.80", "value": "31968000000"},
{"name": "Europe", "percent": "23.64", "value": "18521000000"},
{"name": "Greater China", "percent": "20.72", "value": "16233000000"}
],
"regionals": []
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [BusinessSegmentsHistoryResponse](#BusinessSegmentsHistoryResponse) |
| 400 | Bad request | None |
## Schemas
### BusinessSegmentsHistoryResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| historical | object[] | false | Historical period snapshots |
| ∟ date | string | false | Report period in YYYYMMDD format, e.g. `20260331` |
| ∟ total | string | false | Total revenue for the period |
| ∟ currency | string | false | Currency code |
| ∟ business | object[] | false | Business segment list |
| ∟ ∟ name | string | false | Segment name |
| ∟ ∟ percent | string | false | Revenue share percentage, e.g. `40.80` |
| ∟ ∟ value | string | false | Absolute revenue value |
| ∟ regionals | object[] | false | Regional segment list (typically empty) |
| ∟ ∟ name | string | false | Region name |
| ∟ ∟ percent | string | false | Revenue share percentage |
| ∟ ∟ value | string | false | Absolute revenue value |
---
# Buyback
URL: https://open.longbridge.com/docs/fundamental/fundamental/buyback.md
Get share buyback data including historical buyback amounts and ratios.
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `AAPL.US` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.buyback("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.buyback("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.buyback('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getBuyback("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.buyback("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.buyback("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.Buyback(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"buyback_history": [
{
"fiscal_year": "FY2024",
"fiscal_year_range": "2024-01-01~2024-12-31",
"net_buyback": "94949000000",
"net_buyback_yield": "0.0241",
"net_buyback_growth_rate": "-0.1233"
}
],
"buyback_ratios": [
{
"net_buyback_payout_ratio": "0.9502",
"net_buyback_to_cashflow_ratio": "0.8821"
}
],
"recent_buybacks": {
"currency": "USD",
"net_buyback_ttm": "94949000000",
"net_buyback_yield_ttm": "0.0241"
}
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [BuybackDataResponse](#BuybackDataResponse) |
| 400 | Bad request | None |
## Schemas
### BuybackDataResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| buyback_history | object[] | false | Annual buyback history, see [BuybackHistoryItem](#BuybackHistoryItem) |
| buyback_ratios | object[] | false | Buyback ratio history, see [BuybackRatios](#BuybackRatios) |
| recent_buybacks | object | false | Trailing 12-month buyback summary |
### BuybackHistoryItem
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| fiscal_year | string | false | Fiscal year |
| fiscal_year_range | string | false | Fiscal year date range |
| currency | string | false | Currency |
| net_buyback | string | false | Net buyback amount |
| net_buyback_growth_rate | string | false | Buyback growth rate |
| net_buyback_yield | string | false | Buyback yield |
### BuybackRatios
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| net_buyback_payout_ratio | string | false | Buyback payout ratio |
| net_buyback_to_cashflow_ratio | string | false | Buyback to free cash flow ratio |
### RecentBuybacks
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| currency | string | false | Currency |
| net_buyback_ttm | string | false | Net buyback (trailing 12 months) |
| net_buyback_yield_ttm | string | false | Buyback yield (trailing 12 months) |
---
# Company Profile
URL: https://open.longbridge.com/docs/fundamental/fundamental/company-profile.md
Get a company's profile information including founding year, employee count, headquarters, and description.
longbridge company TSLA.US
longbridge company AAPL.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `AAPL.US` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.company_profile("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.company_profile("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.company_profile('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getCompanyProfile("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.company_profile("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.company_profile("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.CompanyProfile(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"company_name": "Apple Inc.",
"name": "Apple",
"ticker": "AAPL",
"market": "NasdaqGS",
"founded": "1976",
"employees": "166000",
"manager": "Timothy D. Cook",
"website": "www.apple.com",
"phone": "(408) 996-1010",
"address": "One Apple Park Way, Cupertino, California, United States",
"profile": "Apple Inc. designs, manufactures, and markets smartphones, personal computers, tablets, wearables, a...",
"region": "US",
"sector": 0,
"year_end": "September 27",
"icon": "https://assets.lbkrs.com/ticker/ST/US/AAPL.png"
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [CompanyProfileResponse](#CompanyProfileResponse) |
| 400 | Bad request | None |
## Schemas
### CompanyProfileResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| name | string | false | Chinese name |
| company_name | string | false | Full company name |
| ticker | string | false | Ticker symbol |
| market | string | false | Listing exchange |
| sector | integer | false | Industry sector |
| category | string | false | Company category |
| founded | string | false | Founding year |
| listing_date | string | false | IPO listing date |
| employees | string | false | Number of employees |
| chairman | string | false | Chairman |
| manager | string | false | CEO / General manager |
| secretary | string | false | Company secretary |
| address | string | false | Registered address |
| office_address | string | false | Office address |
| email | string | false | Contact email |
| website | string | false | Company website |
| profile | string | false | Business description |
| icon | string | false | Stock icon URL |
| region | string | false | Region |
| shares_offered | string | false | Total shares offered |
| issue_price | string | false | IPO issue price |
| year_end | string | false | Fiscal year-end |
| zip_code | string | false | Postal code |
| phone | string | false | Phone number |
| fax | string | false | Fax number |
| legal_repr | string | false | Legal representative |
| legal_counsel | string | false | Legal counsel |
| accounting_firm | string | false | Accounting firm |
| audit_inst | string | false | Audit institution |
| securities_rep | string | false | Securities representative |
| bus_license | string | false | Business license number |
| ads_ratio | string | false | ADS ratio |
---
# Financial Consensus
URL: https://open.longbridge.com/docs/fundamental/fundamental/consensus.md
Get financial consensus estimates including revenue, EPS, and net income forecasts.
longbridge consensus TSLA.US
longbridge consensus AAPL.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `TSLA.US` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.consensus("TSLA.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.consensus("TSLA.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.consensus('TSLA.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getConsensus("TSLA.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.consensus("TSLA.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.consensus("TSLA.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.Consensus(context.Background(), "TSLA.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"currency": "USD",
"current_index": 3,
"current_period": "qf",
"opt_periods": [
"qf",
"af",
"saf"
],
"list": [
{
"fiscal_year": 2026,
"fiscal_period": "Q2 FY2026",
"period_text": "Q2 FY2026",
"details": [
{
"key": "revenue",
"name": "Revenue",
"estimate": "95000000000",
"actual": "",
"comp": "",
"comp_value": null,
"comp_desc": "",
"description": "",
"is_released": false
}
]
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [FinancialConsensus](#FinancialConsensus) |
| 400 | Bad request | None |
## Schemas
### FinancialConsensus
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| currency | string | false | Reporting currency |
| current_index | integer | false | Index of the current period in opt_periods |
| current_period | string | false | Current period code (e.g. `qf`) |
| list | object[] | true | List of consensus forecast periods, see [ConsensusListItem](#ConsensusListItem) |
| opt_periods | string[] | false | Available period options |
### ConsensusListItem
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| fiscal_period | string | false | Fiscal period number within the fiscal year |
| fiscal_year | integer | false | Fiscal year |
| period_text | string | false | Display period label (e.g. Q1 2027) |
| details | object[] | false | List of financial indicator details, see [ConsensusDetail](#ConsensusDetail) |
### ConsensusDetail
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| key | string | false | Indicator key (e.g. `eps`, `revenue`) |
| name | string | false | Indicator display name |
| description | string | false | Full description |
| actual | string | false | Actual reported value |
| estimate | string | false | Consensus estimate |
| comp | string | false | Comparison result (e.g. `beat`, `miss`) |
| comp_desc | string | false | Comparison description |
| comp_value | string | false | Comparison percentage value |
| is_released | boolean | false | Whether actual has been released |
---
# Corporate Actions
URL: https://open.longbridge.com/docs/fundamental/fundamental/corporate-actions.md
Get corporate action history (splits, mergers, spin-offs, rights issues) for a security.
longbridge corp-action TSLA.US
longbridge corp-action AAPL.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `AAPL.US` |
| start_date | string | NO | Start date in `YYYY-MM-DD` format |
| end_date | string | NO | End date in `YYYY-MM-DD` format |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.corp_action("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.corp_action("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.corpAction('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getCorpAction("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.corp_action("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.corp_action("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.CorporateActions(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"items": [
{
"id": "622620",
"action": "DividendExDate",
"act_type": "Distribution Plan",
"act_desc": "Cash dividend 0.27 USD",
"date": "20260514",
"date_str": "05.14",
"date_type": "Payment Date",
"date_zone": "EST",
"delay_content": "",
"is_delay": false,
"recent": false,
"live": null
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [CorporateActionsResponse](#CorporateActionsResponse) |
| 400 | Bad request | None |
## Schemas
### CorporateActionsResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| items | object[] | true | Corporate action list |
| ∟ id | string | false | Action ID |
| ∟ act_desc | string | false | Action description |
| ∟ act_type | string | false | Action type category |
| ∟ action | string | false | Action code (e.g. `DividendExDate`) |
| ∟ date | string | false | Event date (YYYYMMDD) |
| ∟ date_str | string | false | Short display date (MM.DD) |
| ∟ date_type | string | false | Date type label (e.g. Payment Date) |
| ∟ date_zone | string | false | Time zone (e.g. EST) |
| ∟ delay_content | string | false | Delay content description |
| ∟ is_delay | boolean | false | Whether the event is delayed |
| ∟ live | boolean | false | Whether currently live |
| ∟ recent | boolean | false | Whether this is a recent event |
---
# Dividend Detail
URL: https://open.longbridge.com/docs/fundamental/fundamental/dividend-detail.md
Get detailed dividend information including declared, ex-dividend, and payment dates.
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `AAPL.US` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.dividend_detail("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.dividend_detail("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.dividendDetail('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getDividendDetail("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.dividend_detail("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.dividend_detail("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.DividendDetail(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"list": [
{
"id": "12345",
"symbol": "AAPL.US",
"ex_date": "2026-02-07",
"payment_date": "2026-02-13",
"record_date": "2026-02-10",
"desc": "Cash dividend 0.25 USD"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [DividendList](#DividendList) |
| 400 | Bad request | None |
## Schemas
### DividendList
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| list | object[] | true | List of dividend records |
| ∟ id | string | false | Dividend event ID |
| ∟ symbol | string | false | Security symbol |
| ∟ desc | string | false | Dividend description |
| ∟ ex_date | string | false | Ex-dividend date (YYYY-MM-DD) |
| ∟ record_date | string | false | Record date (YYYY-MM-DD) |
| ∟ payment_date | string | false | Payment date (YYYY-MM-DD) |
---
# Dividends
URL: https://open.longbridge.com/docs/fundamental/fundamental/dividends.md
Get dividend history and upcoming dividend announcements for a security.
longbridge dividend TSLA.US
longbridge dividend AAPL.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `AAPL.US` |
| start_date | string | NO | Start date in `YYYY-MM-DD` format |
| end_date | string | NO | End date in `YYYY-MM-DD` format |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.dividends("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.dividends("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.dividends('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getDividends("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.dividends("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.dividends("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.Dividends(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"list": [
{
"id": "12345",
"symbol": "AAPL.US",
"ex_date": "2026-02-07",
"payment_date": "2026-02-13",
"record_date": "2026-02-10",
"desc": "Cash dividend 0.25 USD"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [DividendsResponse](#DividendsResponse) |
| 400 | Bad request | None |
## Schemas
### DividendsResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| list | object[] | true | Dividend records |
| ∟ id | string | false | Dividend event ID |
| ∟ symbol | string | false | Security symbol |
| ∟ desc | string | false | Dividend description |
| ∟ ex_date | string | false | Ex-dividend date |
| ∟ payment_date | string | false | Payment date |
| ∟ record_date | string | false | Record date |
---
# Executives
URL: https://open.longbridge.com/docs/fundamental/fundamental/executives.md
Get the list of key executives (CEO, CFO, etc.) for a company.
longbridge executive TSLA.US
longbridge executive AAPL.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `AAPL.US` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.executives("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.executives("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.executives('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getExecutives("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.executives("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.executives("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.Executives(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"professional_list": [
{
"forward_url": "https://longbridge.com/wiki/stocks/ST.US.AAPL#company-manager",
"professionals": [
{
"biography": "Tim Cook is the CEO of Apple Inc.",
"id": "12345",
"name": "Timothy D. Cook",
"name_en": "Timothy D. Cook",
"name_zhcn": "蒂姆·库克",
"photo": "https://cdn.example.com/timcook.jpg",
"title": "Chief Executive Officer",
"wiki_url": "https://en.wikipedia.org/wiki/Tim_Cook"
}
],
"symbol": "AAPL.US",
"total": 9
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [ExecutiveResponse](#ExecutiveResponse) |
| 400 | Bad request | None |
## Schemas
### ExecutiveResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| professional_list | object[] | true | List of executive groups, see [ExecutiveGroup](#ExecutiveGroup) |
### ExecutiveGroup
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | true | Security symbol |
| forward_url | string | false | Company executives page URL |
| total | integer | false | Total number of executives |
| professionals | object[] | true | List of executives, see [Executive](#Executive) |
### Executive
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | string | false | Executive ID |
| name | string | true | Display name |
| name_en | string | false | English name |
| name_zhcn | string | false | Chinese name |
| title | string | false | Job title |
| biography | string | false | Biography |
| photo | string | false | Photo URL |
| wiki_url | string | false | Wikipedia URL |
---
# Financial Report
URL: https://open.longbridge.com/docs/fundamental/fundamental/financial-report.md
Fetch income statement, balance sheet, and cash flow statement for any public company.
longbridge financial-report TSLA.US --kind IS
longbridge financial-report AAPL.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `AAPL.US` |
| kind | string | YES | Report type: `IncomeStatement`, `BalanceSheet`, `CashFlow`, `All` |
| period | string | YES | Report period: `Annual`, `SemiAnnual`, `Q1`, `Q2`, `Q3`, `ThreeQ`, `QuarterlyFull` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.financial_report("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.financial_report("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.financial_report('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getFinancialReport("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.financial_report("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.financial_report("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.FinancialReport(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"list": {
"IS": {
"indicators": [
{
"title": "Income Statement",
"short_title": "IS",
"currency": "USD",
"has_yoy": true,
"entry": "IS",
"periods": [
"FY2025",
"FY2024"
],
"accounts": [
{
"field": "EPS",
"name": "Earnings Per Share(USD)",
"percent": false,
"tip": "",
"values": [
{
"period": "FY 2025",
"year": 2025,
"fp_end": "1758945600",
"value": "7.46",
"ratio": "",
"yoy": "0.227"
}
]
}
]
}
]
}
}
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [FinancialReportsResponse](#FinancialReportsResponse) |
| 400 | Bad request | None |
## Schemas
### FinancialReportsResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| list | object | true | Report data grouped by kind (key: report type code, e.g. `IS`, `BS`, `CF`) |
### FinancialReportIndicator
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| title | string | false | Indicator title |
| short_title | string | false | Short title |
| currency | string | false | Currency |
| has_yoy | boolean | false | Whether year-over-year data is available |
| entry | string | false | Entry identifier |
| periods | string[] | false | Available reporting periods |
| accounts | object[] | false | List of financial line items, see [FinancialAccount](#FinancialAccount) |
### FinancialAccount
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| field | string | true | Field identifier |
| name | string | false | Field display name |
| percent | boolean | false | Whether the value is a percentage |
| tip | string | false | Tooltip description |
| values | object[] | false | Historical values by period, see [FinancialValue](#FinancialValue) |
### FinancialValue
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| period | string | true | Period label (e.g. `FY 2024`) |
| year | integer | false | Fiscal year |
| fp_end | string | false | Period end timestamp |
| value | string | false | Reported value |
| ratio | string | false | Ratio value |
| yoy | string | false | Year-over-year growth rate |
---
# Financial Report Snapshot
URL: https://open.longbridge.com/docs/fundamental/fundamental/financial-report-snapshot.md
Get an AI-generated earnings summary, revenue/EBIT/EPS forecast vs actual (beat/miss analysis), and key financial ratios.
longbridge financial-report snapshot AAPL.US
longbridge financial-report snapshot AAPL.US --report qf --year 2024 --period 4
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `AAPL.US` |
| report | string | NO | Report type: `qf` (quarterly) / `saf` (semi-annual) / `af` (annual) |
| fiscal_year | uint32 | NO | Fiscal year, e.g. `2024` |
| fiscal_period | string | NO | Fiscal period, e.g. `1` / `2` / `3` / `4` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.financial_report_snapshot("AAPL.US", report="qf", fiscal_year=2024, fiscal_period="4")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.financial_report_snapshot("AAPL.US", report="qf", fiscal_year=2024, fiscal_period="4")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.financialReportSnapshot('AAPL.US', { report: 'qf', fiscalYear: 2024, fiscalPeriod: '4' })
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getFinancialReportSnapshot("AAPL.US", "qf", 2024, "4").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.financial_report_snapshot("AAPL.US", Some("qf"), Some(2024), Some("4")).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.financial_report_snapshot("AAPL.US", "qf", 2024, "4", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.FinancialReportSnapshot(context.Background(), "AAPL.US", "qf", 2024, "4")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"name": "Apple",
"ticker": "AAPL",
"fp_start": "2025.12.28",
"fp_end": "2026.03.28",
"currency": "USD",
"report_desc": "Summary: Apple (AAPL) revenue was 111.18B (+16.6%); EPS was 2.01 (+21.82%).",
"fo_revenue": {"value": "111184000000.0000", "yoy": "16.6", "cmp_desc": "", "est_value": ""},
"fo_ebit": {"value": "35885000000.0000", "yoy": "21.28", "cmp_desc": "", "est_value": ""},
"fo_eps": {"value": "2.0100", "yoy": "21.82", "cmp_desc": "", "est_value": ""},
"fr_revenue": {"value": "111184000000.0000", "yoy": "16.6"},
"fr_profit": {"value": "29578000000.0000", "yoy": "19.36"},
"fr_roe_ttm": "141.4705",
"fr_profit_margin": "26.6027",
"fr_debt_assets_ratio": "71.3025"
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [FinancialReportSnapshotResponse](#FinancialReportSnapshotResponse) |
| 400 | Bad request | None |
## Schemas
### FinancialReportSnapshotResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| name | string | false | Company name |
| ticker | string | false | Ticker symbol without market suffix, e.g. `AAPL` |
| fp_start | string | false | Fiscal period start date in `YYYY.MM.DD` format |
| fp_end | string | false | Fiscal period end date in `YYYY.MM.DD` format |
| currency | string | false | Currency code |
| report_desc | string | false | AI-generated earnings summary |
| fo_revenue | object | false | Revenue forecast vs actual, see [ForecastMetric](#ForecastMetric) |
| fo_ebit | object | false | EBIT forecast vs actual, see [ForecastMetric](#ForecastMetric) |
| fo_eps | object | false | EPS forecast vs actual, see [ForecastMetric](#ForecastMetric) |
| fr_revenue | object | false | Reported revenue, see [ReportedMetric](#ReportedMetric) |
| fr_profit | object | false | Reported net profit, see [ReportedMetric](#ReportedMetric) |
| fr_operate_cash | object | false | Operating cash flow, see [ReportedMetric](#ReportedMetric) |
| fr_invest_cash | object | false | Investing cash flow, see [ReportedMetric](#ReportedMetric) |
| fr_finance_cash | object | false | Financing cash flow, see [ReportedMetric](#ReportedMetric) |
| fr_total_assets | object | false | Total assets, see [ReportedMetric](#ReportedMetric) |
| fr_total_liability | object | false | Total liabilities, see [ReportedMetric](#ReportedMetric) |
| fr_roe_ttm | string | false | ROE TTM as percentage, e.g. `141.47` |
| fr_profit_margin | string | false | Net profit margin as percentage |
| fr_profit_margin_ttm | string | false | Net profit margin TTM as percentage |
| fr_asset_turn_ttm | string | false | Asset turnover TTM as percentage |
| fr_leverage_ttm | string | false | Leverage TTM as percentage |
| fr_debt_assets_ratio | string | false | Debt-to-assets ratio as percentage |
### ForecastMetric
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| value | string | false | Actual value |
| yoy | string | false | Year-over-year growth as percentage, e.g. `16.6` |
| cmp_desc | string | false | Beat/miss description (may be empty) |
| est_value | string | false | Consensus estimate (may be empty) |
### ReportedMetric
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| value | string | false | Value |
| yoy | string | false | Year-over-year growth as percentage |
---
# Forecast EPS
URL: https://open.longbridge.com/docs/fundamental/fundamental/forecast-eps.md
Get EPS forecasts and analyst consensus estimates.
longbridge forecast-eps TSLA.US
longbridge forecast-eps AAPL.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `TSLA.US` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.forecast_eps("TSLA.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.forecast_eps("TSLA.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.forecastEps('TSLA.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getForecastEps("TSLA.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.forecast_eps("TSLA.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.forecast_eps("TSLA.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.ForecastEps(context.Background(), "TSLA.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"items": [
{
"forecast_end_date": "1727827200",
"forecast_eps_highest": "3.71",
"forecast_eps_lowest": "2.37",
"forecast_eps_mean": "2.998",
"forecast_eps_median": "3.02",
"forecast_start_date": "1727827200",
"institution_down": 0,
"institution_total": 0,
"institution_up": 0
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [ForecastEps](#ForecastEps) |
| 400 | Bad request | None |
## Schemas
### ForecastEps
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| items | object[] | true | List of EPS forecast periods |
| ∟ forecast_start_date | string | false | Forecast period start date |
| ∟ forecast_end_date | string | false | Forecast period end date |
| ∟ forecast_eps_mean | string | false | Mean EPS estimate |
| ∟ forecast_eps_median | string | false | Median EPS estimate |
| ∟ forecast_eps_highest | string | false | Highest EPS estimate |
| ∟ forecast_eps_lowest | string | false | Lowest EPS estimate |
| ∟ institution_total | integer | false | Total contributing institutions |
| ∟ institution_up | integer | false | Institutions revising up |
| ∟ institution_down | integer | false | Institutions revising down |
---
# Fund Holdings
URL: https://open.longbridge.com/docs/fundamental/fundamental/fund-holdings.md
Get the list of funds that hold a given security, with the number of shares and ownership percentage.
longbridge fund-holder TSLA.US
longbridge fund-holder AAPL.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `AAPL.US` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.fund_holdings("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.fund_holdings("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.fund_holdings('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getFundHoldings("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.fund_holdings("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.fund_holdings("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.FundHoldings(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"lists": [
{
"symbol": "TSLT.US",
"code": "TSLT",
"name": "2x Long TSLA ETF",
"position_ratio": "101.02",
"report_date": "2026-05-07",
"currency": "USD"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [FundHoldersResponse](#FundHoldersResponse) |
| 400 | Bad request | None |
## Schemas
### FundHoldersResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| lists | object[] | true | List of fund holders |
| ∟ symbol | string | true | Fund symbol |
| ∟ code | string | false | Fund code |
| ∟ name | string | false | Fund name |
| ∟ position_ratio | string | false | Position ratio (%) |
| ∟ report_date | string | false | Report date |
| ∟ currency | string | false | Currency |
---
# Industry Peer Hierarchy
URL: https://open.longbridge.com/docs/fundamental/fundamental/industry-peers.md
Get the hierarchical sub-sector tree for an industry group, including stock count, daily change, and YTD change at each node. Symbols come from `industry_rank`.
longbridge industry-peers IN00258.US
longbridge industry-peers IN20337.HK
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Industry unique identifier (BK/MARKET/ID format) from `industry_rank` |
| market | string | YES | Market code: `US` / `HK` / `CN` / `SG` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.industry_peers("IN00258.US", "US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.industry_peers("IN00258.US", "US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.industryPeers('IN00258.US', 'US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getIndustryPeers("IN00258.US", "US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.industry_peers("IN00258.US", "US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.industry_peers("IN00258.US", "US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.IndustryPeers(context.Background(), "IN00258.US", "US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"top": {"name": "All Industries", "market": "US"},
"chain": {
"name": "Technology",
"symbol": "IN00258.US",
"stock_num": 542,
"chg": "0.0231",
"ytd_chg": "0.0875",
"next": [
{
"name": "Online Consumer Electronics Retail",
"symbol": "",
"stock_num": 4,
"chg": "0.0268",
"ytd_chg": "-0.1869",
"next": []
}
]
}
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [IndustryPeersResponse](#IndustryPeersResponse) |
| 400 | Bad request | None |
## Schemas
### IndustryPeersResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| top | object | false | Top-level industry info, see [IndustryPeersTop](#IndustryPeersTop) |
| chain | object | false | Industry hierarchy root node, see [IndustryPeerNode](#IndustryPeerNode) |
### IndustryPeersTop
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| name | string | false | Top-level industry name |
| market | string | false | Market code |
### IndustryPeerNode
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| name | string | false | Sector name |
| symbol | string | false | Sector symbol (present on root node; empty string on child nodes) |
| stock_num | integer | false | Number of stocks in this sector |
| chg | string | false | Daily change (decimal; may be empty string) |
| ytd_chg | string | false | Year-to-date change (decimal; may be empty string) |
| next | object[] | false | Child sector list with the same structure (recursive) |
---
# Industry Ranking
URL: https://open.longbridge.com/docs/fundamental/fundamental/industry-rank.md
Get the industry ranking list by market and indicator. The returned Symbol can be passed directly to `industry_peers` to explore the sub-sector hierarchy.
longbridge industry-rank --market US
longbridge industry-rank --market HK --indicator market-cap
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| market | string | YES | Market code: `US` / `HK` / `CN` / `SG` |
| indicator | string | YES | Ranking indicator: `leading-gainer` / `today-trend` / `popularity` / `market-cap` / `revenue` / `revenue-growth` / `net-profit` / `net-profit-growth` |
| sort_type | string | YES | Sort mode: `single` / `multi` |
| limit | uint32 | YES | Number of results to return, default 20 |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.industry_rank("US", "leading-gainer", "single", 20)
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.industry_rank("US", "leading-gainer", "single", 20)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.industryRank('US', 'leading-gainer', 'single', 20)
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getIndustryRank("US", "leading-gainer", "single", 20).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.industry_rank("US", "leading-gainer", "single", 20).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.industry_rank("US", "leading-gainer", "single", 20, [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.IndustryRank(context.Background(), "US", "leading-gainer", "single", 20)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"items": [
{
"lists": [
{
"name": "Technology",
"symbol": "IN00258.US",
"chg": "0.0231",
"leading_name": "NVIDIA",
"leading_ticker": "NVDA.US",
"leading_chg": "0.0512",
"value_name": "",
"value_data": ""
}
]
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [IndustryRankResponse](#IndustryRankResponse) |
| 400 | Bad request | None |
## Schemas
### IndustryRankResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| items | object[] | false | Ranked group list |
| ∟ lists | object[] | false | Industry item list |
| ∟ ∟ name | string | false | Industry name |
| ∟ ∟ symbol | string | false | Industry symbol (`BK/MARKET/ID` format), usable in `industry_peers` |
| ∟ ∟ chg | string | false | Daily change (decimal) |
| ∟ ∟ leading_name | string | false | Leading stock name |
| ∟ ∟ leading_ticker | string | false | Leading stock ticker |
| ∟ ∟ leading_chg | string | false | Leading stock daily change (decimal) |
| ∟ ∟ value_name | string | false | Indicator label (may be empty depending on indicator type) |
| ∟ ∟ value_data | string | false | Indicator value (may be empty) |
---
# Industry Valuation
URL: https://open.longbridge.com/docs/fundamental/fundamental/industry-valuation.md
Get peer valuation comparison within the same industry.
longbridge industry-valuation TSLA.US
longbridge industry-valuation AAPL.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `TSLA.US` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.industry_valuation("TSLA.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.industry_valuation("TSLA.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.industryValuation('TSLA.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getIndustryValuation("TSLA.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.industry_valuation("TSLA.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.industry_valuation("TSLA.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.IndustryValuation(context.Background(), "TSLA.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"list": [
{
"symbol": "AAPL.US",
"name": "Apple Inc.",
"market": "US",
"currency": "USD",
"pe": "28.50",
"pb": "45.2",
"ps": "7.8",
"eps": "6.08",
"bps": "4.50"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [IndustryValuationList](#IndustryValuationList) |
| 400 | Bad request | None |
## Schemas
### IndustryValuationList
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| list | object[] | true | List of peer companies |
| ∟ symbol | string | false | Security symbol |
| ∟ name | string | false | Company name |
| ∟ currency | string | false | Reporting currency |
| ∟ pe | string | false | Price-to-Earnings ratio |
| ∟ bps | string | false | Book value per share |
| ∟ eps | string | false | Earnings per share |
| ∟ dps | string | false | Dividends per share |
| ∟ div_yld | string | false | Dividend yield |
| ∟ div_payout_ratio | string | false | Dividend payout ratio |
| ∟ five_y_avg_dps | string | false | 5-year average DPS |
| ∟ assets | string | false | Total assets |
| ∟ history | object[] | false | Historical valuation data |
---
# Industry Valuation Distribution
URL: https://open.longbridge.com/docs/fundamental/fundamental/industry-valuation-dist.md
Get the valuation distribution histogram for the symbol's industry.
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `AAPL.US` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.industry_valuation_dist("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.industry_valuation_dist("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.industryValuationDist('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getIndustryValuationDist("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.industry_valuation_dist("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.industry_valuation_dist("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.IndustryValuationDist(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"pe": {
"value": "28.5",
"high": "120.0",
"low": "5.0",
"median": "22.0",
"ranking": "35",
"rank_index": "12",
"rank_total": "30"
},
"pb": {
"value": "45.2",
"high": "200.0",
"low": "1.0",
"median": "8.0",
"ranking": "85",
"rank_index": "25",
"rank_total": "30"
},
"ps": {
"value": "7.8",
"high": "30.0",
"low": "0.5",
"median": "4.0",
"ranking": "70",
"rank_index": "21",
"rank_total": "30"
}
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [IndustryValuationDist](#IndustryValuationDist) |
| 400 | Bad request | None |
## Schemas
### IndustryValuationDist
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| pe | object | false | P/E ratio distribution |
| pb | object | false | P/B ratio distribution |
| ps | object | false | P/S ratio distribution |
---
# Institution Rating
URL: https://open.longbridge.com/docs/fundamental/fundamental/institution-rating.md
Get analyst institution rating snapshot (rating distribution and average target price).
longbridge institution-rating TSLA.US
longbridge institution-rating AAPL.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `TSLA.US` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.institution_rating("TSLA.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.institution_rating("TSLA.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.institutionRating('TSLA.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getInstitutionRating("TSLA.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.institution_rating("TSLA.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.institution_rating("TSLA.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.InstitutionRating(context.Background(), "TSLA.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"latest": {
"evaluate": {
"buy": 18,
"hold": 17,
"sell": 4,
"no_opinion": 4,
"over": 5,
"under": 3,
"total": 51,
"start_date": "1778198400",
"end_date": "0"
},
"industry_id": 87676,
"industry_mean": 10,
"industry_median": 4,
"industry_name": "Automobiles",
"industry_rank": 1,
"industry_total": 30,
"target": {
"highest_price": "600.000",
"lowest_price": "123.000",
"prev_close": "428.35",
"start_date": "1778198400",
"end_date": "0"
}
},
"summary": {
"ccy_symbol": "$",
"change": "0",
"recommend": "Buy",
"updated_at": "1778198400",
"evaluate": {
"buy": 18,
"hold": 17,
"sell": 4
},
"target": {
"average_target": "350.00",
"highest_price": "600.000",
"lowest_price": "123.000"
}
}
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [InstitutionRatingResponse](#InstitutionRatingResponse) |
| 400 | Bad request | None |
## Schemas
### InstitutionRatingResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| latest | object | true | Latest analyst rating snapshot |
| latest.evaluate | object | true | Rating distribution |
| latest.evaluate.buy | integer | false | Buy ratings count |
| latest.evaluate.hold | integer | false | Hold ratings count |
| latest.evaluate.sell | integer | false | Sell ratings count |
| latest.evaluate.over | integer | false | Outperform count |
| latest.evaluate.under | integer | false | Underperform count |
| latest.evaluate.no_opinion | integer | false | No opinion count |
| latest.evaluate.total | integer | false | Total analyst count |
| latest.evaluate.start_date | string | false | Period start date |
| latest.evaluate.end_date | string | false | Period end date |
| latest.industry_id | integer | false | Industry ID |
| latest.industry_name | string | false | Industry name |
| latest.industry_rank | integer | false | Rank within industry |
| latest.industry_total | integer | false | Total stocks in industry |
| latest.industry_mean | integer | false | Industry mean rating |
| latest.industry_median | integer | false | Industry median rating |
| latest.target | object | false | Price target range |
| latest.target.highest_price | string | false | Highest target price |
| latest.target.lowest_price | string | false | Lowest target price |
| latest.target.prev_close | string | false | Previous close price |
| latest.target.start_date | string | false | Period start date |
| latest.target.end_date | string | false | Period end date |
| summary | object | false | Consensus rating snapshot |
| summary.recommend | object | false | Recommendation distribution mapping |
| summary.change | string | false | Price change value |
| summary.ccy_symbol | string | false | Currency symbol |
| summary.evaluate | object | false | Rating distribution counts |
| summary.evaluate.buy | integer | false | Buy count |
| summary.evaluate.strong_buy | integer | false | Strong buy count |
| summary.evaluate.hold | integer | false | Hold count |
| summary.evaluate.sell | integer | false | Sell count |
| summary.evaluate.under | integer | false | Underperform count |
| summary.target | string | false | Consensus average target price |
| summary.updated_at | string | false | Last update date string |
---
# Institution Rating Detail
URL: https://open.longbridge.com/docs/fundamental/fundamental/institution-rating-detail.md
Get historical analyst rating and target price details.
longbridge institution-rating detail TSLA.US
longbridge institution-rating detail AAPL.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `TSLA.US` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.institution_rating_detail("TSLA.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.institution_rating_detail("TSLA.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.institutionRatingDetail('TSLA.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getInstitutionRatingDetail("TSLA.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.institution_rating_detail("TSLA.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.institution_rating_detail("TSLA.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.InstitutionRatingDetail(context.Background(), "TSLA.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"ccy_symbol": "$",
"evaluate": {
"list": [
{
"date": "2021/05/14",
"buy": 3,
"hold": 11,
"sell": 2,
"strong_buy": 9,
"under": 6
}
]
},
"target": {
"list": [
{
"broker_name": "Goldman Sachs",
"date": "2026-04-30",
"rating": "Buy",
"target_price": "250.00"
}
]
}
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [InstitutionRatingDetail](#InstitutionRatingDetail) |
| 400 | Bad request | None |
## Schemas
### InstitutionRatingDetail
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| ccy_symbol | string | false | Currency symbol |
| evaluate | object | false | Rating distribution history |
| evaluate.list | object[] | false | List of historical rating snapshots |
| target | object | false | Target price history |
| target.list | object[] | false | List of historical target price data |
| target.data_percent | string | false | Data coverage percentage |
| target.prediction_accuracy | string | false | Prediction accuracy percentage |
| target.updated_at | string | false | Last update date string |
### EvaluateHistoryItem
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| date | string | false | Date |
| buy | integer | false | Buy count |
| strong_buy | integer | false | Strong buy count |
| hold | integer | false | Hold count |
| sell | integer | false | Sell count |
| no_opinion | integer | false | No opinion count |
| under | integer | false | Underperform count |
### TargetHistoryItem
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| date | string | false | Date |
| avg_target | string | false | Average target price |
| max_target | string | false | Highest target price |
| min_target | string | false | Lowest target price |
| price | string | false | Closing price on that date |
| meet | boolean | false | Whether price met target |
| timestamp | string | false | Unix timestamp |
---
# Institutional Rating Views Timeline
URL: https://open.longbridge.com/docs/fundamental/fundamental/institution-rating-views.md
Get the monthly institutional rating (buy/hold/sell) distribution timeline, newest first.
longbridge institution-rating AAPL.US --views
longbridge institution-rating TSLA.US --views
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `AAPL.US` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.institution_rating_views("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.institution_rating_views("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.institutionRatingViews('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getInstitutionRatingViews("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.institution_rating_views("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.institution_rating_views("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.InstitutionRatingViews(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"elist": [
{
"date": 1746057600,
"buy": "18",
"over": "5",
"hold": "17",
"under": "3",
"sell": "4",
"total": "51"
},
{
"date": 1743379200,
"buy": "17",
"over": "6",
"hold": "18",
"under": "3",
"sell": "5",
"total": "53"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [InstitutionRatingViewsResponse](#InstitutionRatingViewsResponse) |
| 400 | Bad request | None |
## Schemas
### InstitutionRatingViewsResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| elist | object[] | false | Monthly rating distribution list, newest first |
| ∟ date | integer | false | Unix timestamp (seconds) |
| ∟ buy | string | false | Number of Buy ratings |
| ∟ over | string | false | Number of Outperform ratings |
| ∟ hold | string | false | Number of Hold ratings |
| ∟ under | string | false | Number of Underperform ratings |
| ∟ sell | string | false | Number of Sell ratings |
| ∟ total | string | false | Total analyst count |
---
# Investment Relations
URL: https://open.longbridge.com/docs/fundamental/fundamental/invest-relation.md
Get investment relations including parent company, subsidiaries, and major holdings.
longbridge invest-relation 700.HK
longbridge invest-relation AAPL.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `700.HK` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.invest_relation("700.HK")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.invest_relation("700.HK")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.investRelation('700.HK')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getInvestRelation("700.HK").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.invest_relation("700.HK").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.invest_relation("700.HK", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.InvestRelation(context.Background(), "700.HK")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"forward_url": "https://longbridge.com/wiki/stocks/ST.HK.700#invest",
"invest_securities": [
{
"symbol": "HUYA.US",
"company_id": "12345",
"company_name": "Huya Inc.",
"company_name_en": "Huya Inc.",
"company_name_zhcn": "虎牙直播",
"currency": "USD",
"percent_of_shares": "19.00",
"shares_rank": "1",
"shares_value": "19000000"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [InvestRelations](#InvestRelations) |
| 400 | Bad request | None |
## Schemas
### InvestRelations
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| forward_url | string | false | Company investment relations page URL |
| invest_securities | object[] | false | List of investment holdings |
| ∟ symbol | string | false | Security symbol |
| ∟ company_id | string | false | Company ID |
| ∟ company_name | string | false | Display company name |
| ∟ company_name_en | string | false | English company name |
| ∟ company_name_zhcn | string | false | Chinese company name |
| ∟ currency | string | false | Currency |
| ∟ percent_of_shares | string | false | Ownership percentage |
| ∟ shares_rank | string | false | Rank by shares held |
| ∟ shares_value | string | false | Value of shares held |
---
# Macroeconomic Historical Data
URL: https://open.longbridge.com/docs/fundamental/fundamental/macroeconomic.md
Get historical releases for a specific macroeconomic indicator — actual values, forecasts, previous values, and next release dates.
# Historical data for Non-Farm Payroll
longbridge macrodata 61744
# Date range filter
longbridge macrodata 61744 --start 2024-01-01 --end 2024-12-31
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| indicator_code | string | YES | Indicator code from `macroeconomic_indicators` |
| start_date | string | NO | Start date in `YYYY-MM-DD` format |
| end_date | string | NO | End date in `YYYY-MM-DD` format |
| offset | int | NO | Pagination offset. Default: 0 |
| limit | int | NO | Max records. Default: 100, max: 100 |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.macroeconomic("61744", start_date="2024-01-01", end_date="2024-12-31")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.macroeconomic("61744", start_date="2024-01-01", end_date="2024-12-31")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.macroeconomic('61744', { startDate: '2024-01-01', endDate: '2024-12-31' })
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getMacroeconomic("61744", "2024-01-01", "2024-12-31", null, null).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.macroeconomic("61744", Some("2024-01-01"), Some("2024-12-31"), None, None).await?;
println!("{:?}", resp);
Ok(())
}
```
## Response
### Response Example
```json
{
"count": 24,
"info": {
"indicator_code": "61744",
"country": "US",
"name": "Non-Farm Payroll",
"periodicity": "Monthly",
"describe": "...",
"importance": 3
},
"data": [
{
"period": "2024-12-01",
"release_at": 1735900200,
"actual_value": "256000",
"previous_value": "212000",
"forecast_value": "165000"
}
]
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [MacroeconomicResponse](#MacroeconomicResponse) |
| 400 | Bad request | None |
## Schemas
### MacroeconomicResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| info | MacroeconomicIndicator | true | Indicator metadata |
| data | Macroeconomic[] | true | Historical data points |
| count | int | true | Total number of data points |
### Macroeconomic
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| period | string | true | Statistical period (e.g. `2024-12-01`, `2024-Q4`) |
| release_at | int | false | Unix timestamp of release datetime |
| actual_value | string | true | Actual released value |
| previous_value | string | true | Previous period value |
| forecast_value | string | true | Market consensus forecast |
---
# Macroeconomic Indicators
URL: https://open.longbridge.com/docs/fundamental/fundamental/macroeconomic-indicators.md
List macroeconomic indicators available through Longbridge, optionally filtered by country.
# List all indicators
longbridge macrodata
# Filter by US indicators
longbridge macrodata --country US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| country | MacroeconomicCountry | NO | Filter by country. Omit for all countries. |
| keyword | string | NO | Fuzzy search by indicator name (case-insensitive) |
| offset | int | NO | Pagination offset. Default: 0 |
| limit | int | NO | Max records per page. Default: 100, max: 1000 |
### MacroeconomicCountry
| Value | Country |
| ----- | ------- |
| HK | Hong Kong SAR |
| CN | China (Mainland) |
| US | United States |
| EU | Euro Zone |
| JP | Japan |
| SG | Singapore |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder, MacroeconomicCountry
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
# All indicators
resp = ctx.macroeconomic_indicators()
print(resp)
# US only
resp = ctx.macroeconomic_indicators(country=MacroeconomicCountry.UnitedStates, limit=50)
print(resp)
# Search by keyword
resp = ctx.macroeconomic_indicators(keyword="payroll")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder, MacroeconomicCountry
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.macroeconomic_indicators(country=MacroeconomicCountry.UnitedStates)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth, MacroeconomicCountry } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.macroeconomicIndicators({ country: MacroeconomicCountry.UnitedStates })
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getMacroeconomicIndicators(null, null, null).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.macroeconomic_indicators(None, None, None).await?;
println!("{:?}", resp);
Ok(())
}
```
## Response
### Response Example
```json
{
"count": 619,
"list": [
{
"indicator_code": "61744",
"country": "US",
"name": "Non-Farm Payroll",
"periodicity": "Monthly",
"describe": "Employment situation report...",
"importance": 3
}
]
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [MacroeconomicIndicatorListResponse](#MacroeconomicIndicatorListResponse) |
| 400 | Bad request | None |
## Schemas
### MacroeconomicIndicatorListResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| list | MacroeconomicIndicator[] | true | Indicator list |
| count | int | true | Total number of matching indicators |
### MacroeconomicIndicator
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| indicator_code | string | true | Indicator code (use as input to `macroeconomic`) |
| country | string | true | Country name |
| name | string | true | Indicator name |
| periodicity | string | true | Release periodicity (e.g. `Monthly`, `Quarterly`) |
| describe | string | true | Indicator description |
| importance | int | true | Importance level (1 = Low, 2 = Medium, 3 = High) |
---
# Operating Metrics
URL: https://open.longbridge.com/docs/fundamental/fundamental/operating.md
:::warning Longbridge HK / SG accounts only
This method is available to Longbridge HK / SG accounts only. It works with any supported symbol, including US stocks.
:::
Get operating metrics and financial indicator summaries by report period.
longbridge operating AAPL.US
longbridge operating TSLA.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `AAPL.US` |
| period | string | NO | Report period filter, e.g. `q1`, `q2`, `q3`, `q4`, `annual` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.operating("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.operating("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.operating('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getOperating("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.operating("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.operating("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.Operating(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"list": [
{
"id": "12345",
"report": "af",
"title": "FY2025 Annual Report Summary",
"txt": "Management discussion...",
"latest": true,
"web_url": "https://longbridge.com/wiki/...",
"financial": {
"code": "700",
"currency": "HKD",
"name": "Tencent",
"region": "HK",
"report": "af",
"indicators": [
{
"field_name": "operating_revenue",
"indicator_name": "Revenue",
"indicator_value": "678.6B",
"yoy": "0.0800"
}
]
}
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [OperatingList](#OperatingList) |
| 400 | Bad request | None |
## Schemas
### OperatingListResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| list | object[] | true | List of operating summary reports, see [OperatingItem](#OperatingItem) |
### OperatingItem
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | string | false | Internal report ID |
| report | string | false | Report period code (e.g. `af` = annual) |
| title | string | false | Report title |
| txt | string | false | Management discussion text |
| latest | boolean | false | Whether this is the most recent report |
| web_url | string | false | URL to the full report page |
| financial | object | false | Key financial metrics |
### OperatingFinancial
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| code | string | false | Ticker code |
| name | string | false | Company name |
| currency | string | false | Reporting currency |
| region | string | false | Market region |
| report | string | false | Report period code |
| indicators | object[] | false | Financial indicators, see [OperatingIndicator](#OperatingIndicator) |
### OperatingIndicator
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| field_name | string | true | Field name key (e.g. `operating_revenue`) |
| indicator_name | string | false | Display name |
| indicator_value | string | false | Formatted value |
| yoy | string | false | Year-over-year change rate |
---
# Shareholder Detail
URL: https://open.longbridge.com/docs/fundamental/fundamental/shareholder-detail.md
Get holding history and trade details for a specific shareholder. The `object_id` comes from the `shareholder_top` response.
longbridge shareholder AAPL.US --object-id 19463
longbridge shareholder 700.HK --object-id 20181
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `AAPL.US` |
| object_id | integer | YES | Shareholder ID from `shareholder_top` `object_id` field |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.shareholder_detail("AAPL.US", 19463)
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.shareholder_detail("AAPL.US", 19463)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.shareholderDetail('AAPL.US', 19463)
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getShareholderDetail("AAPL.US", 19463L).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.shareholder_detail("AAPL.US", 19463).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.shareholder_detail("AAPL.US", 19463, [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.ShareholderDetail(context.Background(), "AAPL.US", 19463)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"name": "The Vanguard Group, Inc.",
"title": "",
"avatar": "",
"owner_source": "Institution",
"holding_periods": [],
"holding_details": [],
"holding_summary": [],
"trading_periods": ["Past 1 Month", "Past 3 Months", "Past 1 Year", "Past 3 Years"],
"tradings": [
{
"period": "Past 1 Month",
"accum_buy": "8500000.00",
"accum_sell": "2687264.00",
"net_buy": "5812736.00",
"trading_details": [
{
"trading_date": "2025-12-18",
"trading_shares": "5200000",
"trading_price": "248.12",
"trading_type": "Buy"
}
]
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [ShareholderDetailResponse](#ShareholderDetailResponse) |
| 400 | Bad request | None |
## Schemas
### ShareholderDetailResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| name | string | false | Shareholder name |
| title | string | false | Shareholder title / type |
| avatar | string | false | Avatar URL |
| owner_source | string | false | Shareholder type: `Company`, `Institution`, `Person`, `Insider` |
| holding_periods | string[] | false | Available holding periods |
| holding_details | object[] | false | Holding detail records |
| holding_summary | object[] | false | Holding summary records |
| trading_periods | string[] | false | Available trading periods (e.g. `Past 1 Month`, `Past 3 Months`) |
| tradings | object[] | false | Trade aggregates per period |
| ∟ period | string | false | Period label (e.g. `Past 1 Month`) |
| ∟ accum_buy | string | false | Cumulative shares bought in this period |
| ∟ accum_sell | string | false | Cumulative shares sold in this period |
| ∟ net_buy | string | false | Net shares bought (buy minus sell) in this period |
| ∟ trading_details | object[] | false | Individual transactions within the period |
| ∟ ∟ trading_date | string | false | Trade date |
| ∟ ∟ trading_shares | string | false | Number of shares traded |
| ∟ ∟ trading_price | string | false | Trade price |
| ∟ ∟ trading_type | string | false | Trade direction: `Buy` or `Sell` |
> Note: Some fields return an empty string or empty array when data is unavailable.
---
# Top Shareholders
URL: https://open.longbridge.com/docs/fundamental/fundamental/shareholder-top.md
Get the top 20 major shareholders (institutional, individual, and insider) for a listed company, with support for multi-period comparison. `object_id` can be passed to `shareholder_detail` to retrieve full holding history.
longbridge shareholder AAPL.US --top
longbridge shareholder 700.HK --top
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `AAPL.US` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.shareholder_top("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.shareholder_top("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.shareholderTop('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getShareholderTop("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.shareholder_top("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.shareholder_top("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.ShareholderTop(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"info": [
{
"period": "Latest",
"share_holders": [
{
"object_id": "148057",
"name": "The Vanguard Group, Inc.",
"title": "",
"shares_held": "1426283914.00",
"percent_shares_held": "9.71%",
"percent_shares_changed": "0.01%",
"shares_changed": "0.00",
"period": "Latest",
"filing_date": "2025/12/31"
},
{
"object_id": "452583",
"name": "BlackRock, Inc.",
"title": "",
"shares_held": "1138572603.00",
"percent_shares_held": "7.75%",
"percent_shares_changed": "-0.06%",
"shares_changed": "-10565359.00",
"period": "Latest",
"filing_date": "2026/03/31"
}
]
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [ShareholderTopResponse](#ShareholderTopResponse) |
| 400 | Bad request | None |
## Schemas
### ShareholderTopResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| info | object[] | false | Shareholder data per reporting period |
| ∟ period | string | false | Reporting period label (e.g. `Latest`) |
| ∟ share_holders | object[] | false | List of shareholders (up to 20) |
| ∟ ∟ object_id | string | false | Unique shareholder ID; pass to `shareholder_detail` |
| ∟ ∟ name | string | false | Shareholder name |
| ∟ ∟ title | string | false | Shareholder type (Institution / Individual / Insider) |
| ∟ ∟ shares_held | string | false | Number of shares held |
| ∟ ∟ percent_shares_held | string | false | Ownership percentage, including `%` sign (e.g. `9.71%`) |
| ∟ ∟ percent_shares_changed | string | false | Change in ownership percentage, including `%` sign |
| ∟ ∟ shares_changed | string | false | Net share count change (positive = bought, negative = sold) |
| ∟ ∟ period | string | false | Period label for this entry |
| ∟ ∟ filing_date | string | false | Filing date |
---
# Shareholders
URL: https://open.longbridge.com/docs/fundamental/fundamental/shareholders.md
Get the top institutional and individual shareholders of a company.
longbridge shareholder TSLA.US
longbridge shareholder AAPL.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `AAPL.US` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.shareholders("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.shareholders("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.shareholders('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getShareholders("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.shareholders("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.shareholders("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.Shareholders(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"forward_url": "",
"total": 33,
"shareholder_list": [
{
"shareholder_name": "Timothy D. Cook",
"percent_of_shares": "2.84",
"institution_type": "",
"report_date": "2026-04-21",
"shareholder_id": "0",
"shares_changed": "0",
"stocks": []
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [ShareholderResponse](#ShareholderResponse) |
| 400 | Bad request | None |
## Schemas
### ShareholderResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| shareholder_list | object[] | true | List of shareholders |
| ∟ shareholder_name | string | true | Shareholder name |
| ∟ percent_of_shares | string | true | Percentage of shares held |
| ∟ institution_type | string | false | Institution type |
| ∟ report_date | string | false | Report date |
| ∟ shareholder_id | string | false | Shareholder ID |
| ∟ shares_changed | string | false | Change in shares held |
| ∟ stocks | object[] | false | Associated stocks |
| forward_url | string | false | Link to full shareholder page |
| total | integer | true | Total number of shareholders |
---
# Valuation Comparison
URL: https://open.longbridge.com/docs/fundamental/fundamental/valuation-comparison.md
Compare valuation metrics (PE/PB/PS/market cap/close price) across multiple stocks. When no comparison symbols are provided, the server automatically selects peers from the same industry.
longbridge compare AAPL.US
longbridge compare AAPL.US MSFT.US GOOGL.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Primary security symbol, e.g. `AAPL.US` |
| currency | string | YES | Result currency: `USD`, `HKD`, or `CNY` |
| comparison_symbols | string[] | NO | Symbols to compare against; if omitted, the server auto-selects industry peers |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
# Auto-select peers
resp = ctx.valuation_comparison("AAPL.US", "USD")
# Specify comparison symbols
resp = ctx.valuation_comparison("AAPL.US", "USD", ["MSFT.US", "GOOGL.US"])
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.valuation_comparison("AAPL.US", "USD", ["MSFT.US", "GOOGL.US"])
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.valuationComparison('AAPL.US', 'USD', ['MSFT.US', 'GOOGL.US'])
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
import java.util.Arrays;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getValuationComparison("AAPL.US", "USD", Arrays.asList("MSFT.US", "GOOGL.US")).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.valuation_comparison("AAPL.US", "USD", Some(vec!["MSFT.US", "GOOGL.US"])).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.valuation_comparison("AAPL.US", "USD", {"MSFT.US", "GOOGL.US"}, [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.ValuationComparison(context.Background(), "AAPL.US", "USD", []string{"MSFT.US", "GOOGL.US"})
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"list": [
{
"symbol": "AAPL.US",
"name": "Apple Inc.",
"currency": "USD",
"market_value": "3241500000000",
"price_close": "213.49",
"pe": "32.15",
"pb": "50.21",
"ps": "8.04",
"roe": "136.45",
"eps": "6.43",
"bps": "4.38",
"dps": "0.99",
"div_yld": "0.46",
"assets": "371082000000",
"history": [
{ "date": "1622520000", "pe": "37.56", "pb": "30.16", "ps": "6.41" },
{ "date": "1625112000", "pe": "41.49", "pb": "35.64", "ps": "6.60" }
]
},
{
"symbol": "MSFT.US",
"name": "Microsoft",
"currency": "USD",
"market_value": "3085000000000",
"price_close": "415.32",
"pe": "35.42",
"pb": "12.87",
"ps": "12.61",
"roe": "38.21",
"eps": "11.72",
"bps": "32.28",
"dps": "3.32",
"div_yld": "0.80",
"assets": "512163000000",
"history": [
{ "date": "1622520000", "pe": "33.12", "pb": "11.94", "ps": "11.84" }
]
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [ValuationComparisonResponse](#ValuationComparisonResponse) |
| 400 | Bad request | None |
## Schemas
### ValuationComparisonResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| list | object[] | false | Valuation comparison list |
| ∟ symbol | string | false | Symbol (e.g. `AAPL.US`) |
| ∟ name | string | false | Security name |
| ∟ currency | string | false | Currency of the values |
| ∟ market_value | string | false | Market capitalisation |
| ∟ price_close | string | false | Latest closing price |
| ∟ pe | string | false | P/E ratio (TTM) |
| ∟ pb | string | false | P/B ratio |
| ∟ ps | string | false | P/S ratio (TTM) |
| ∟ roe | string | false | Return on equity (%) |
| ∟ eps | string | false | Earnings per share (TTM) |
| ∟ bps | string | false | Book value per share |
| ∟ dps | string | false | Dividends per share (TTM) |
| ∟ div_yld | string | false | Dividend yield (%) |
| ∟ assets | string | false | Total assets |
| ∟ history | object[] | false | Historical valuation time series |
| ∟ ∟ date | string | false | Date as Unix timestamp (seconds) |
| ∟ ∟ pe | string | false | Historical PE |
| ∟ ∟ pb | string | false | Historical PB |
| ∟ ∟ ps | string | false | Historical PS |
---
# Valuation History
URL: https://open.longbridge.com/docs/fundamental/fundamental/valuation-history.md
Get historical valuation metric time series (PE, PB, PS, dividend yield).
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `AAPL.US` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.valuation_history("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.valuation_history("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.valuationHistory('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getValuationHistory("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.valuation_history("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.valuation_history("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.ValuationHistory(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"history": {
"metrics": {
"pe": {
"desc": "P/E Ratio",
"high": "35.2",
"low": "18.1",
"median": "26.5",
"list": [
{
"timestamp": "1622520000",
"value": "28.5"
}
]
},
"pb": null,
"ps": null
}
}
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [ValuationHistoryResponse](#ValuationHistoryResponse) |
| 400 | Bad request | None |
## Schemas
### ValuationHistoryResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| history | object | true | Valuation history data |
| history.metrics | object | false | Valuation metrics |
| history.metrics.pe | object | false | P/E ratio history |
| history.metrics.pb | object | false | P/B ratio history |
| history.metrics.ps | object | false | P/S ratio history |
### ValuationMetric
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| desc | string | false | Description of current valuation |
| high | string | false | Historical high value |
| low | string | false | Historical low value |
| median | string | false | Median value |
| list | object[] | false | Time series data points, see [ValuationMetric](#ValuationMetric) |
| list[].date | string | false | Date (YYYY-MM-DD) |
| list[].value | string | false | Valuation value |
---
# Valuations
URL: https://open.longbridge.com/docs/fundamental/fundamental/valuations.md
Get current valuation metrics (P/E, P/B, P/S, dividend yield) with 5-year historical context.
longbridge valuation TSLA.US --indicator pe
longbridge valuation AAPL.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `AAPL.US` |
| indicator | string | NO | Indicator filter: `pe`, `pb`, `ps`, `dvd_yld` |
## Request Example
```python
from longbridge.openapi import FundamentalContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = FundamentalContext(config)
resp = ctx.valuations("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncFundamentalContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncFundamentalContext.create(config)
resp = await ctx.valuations("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, FundamentalContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = FundamentalContext.new(config)
const resp = await ctx.valuations('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.fundamental.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
FundamentalContext ctx = FundamentalContext.create(config)) {
var resp = ctx.getValuations("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, fundamental::FundamentalContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = FundamentalContext::new(config);
let resp = ctx.valuations("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::fundamental;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
FundamentalContext ctx = FundamentalContext::create(config);
ctx.valuations("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/fundamental"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := fundamental.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.Valuations(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"metrics": {
"pe": { "current": "29.5", "high": "35.2", "low": "18.0", "median": "26.0" },
"pb": { "current": "45.1", "high": "50.0", "low": "30.0", "median": "42.0" }
}
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [ValuationsResponse](#ValuationsResponse) |
| 400 | Bad request | None |
## Schemas
### ValuationsResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| metrics | object | true | Valuation metrics map |
| ∟ pe | object | false | P/E ratio data |
| ∟∟ current | string | true | Current value |
| ∟∟ high | string | true | 5-year high |
| ∟∟ low | string | true | 5-year low |
| ∟∟ median | string | true | 5-year median |
---
# A/H Premium
URL: https://open.longbridge.com/docs/fundamental/market/ah-premium.md
Get the A/H premium ratio for dual-listed stocks comparing A-share and H-share prices.
longbridge ah-premium 939.HK
longbridge ah-premium 0939.HK
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | H-share symbol of a dual-listed stock, e.g. `939.HK` |
## Request Example
```python
from longbridge.openapi import MarketContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = MarketContext(config)
resp = ctx.ah_premium("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncMarketContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncMarketContext.create(config)
resp = await ctx.ah_premium("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, MarketContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = MarketContext.new(config)
const resp = await ctx.ah_premium('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.market.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
MarketContext ctx = MarketContext.create(config)) {
var resp = ctx.getAhPremium("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, market::MarketContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = MarketContext::new(config);
let resp = ctx.ah_premium("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::market;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
MarketContext ctx = MarketContext::create(config);
ctx.ah_premium("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/market"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := market.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.AhPremium(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"klines": [
{
"ahpremium_rate": "0.1523",
"apreclose": "24.80",
"aprice": "25.10",
"currency_rate": "0.8920",
"hpreclose": "19.20",
"hprice": "19.50",
"price_spread": "1.23",
"timestamp": "1778198400"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [AhPremiumResponse](#AhPremiumResponse) |
| 400 | Bad request | None |
## Schemas
### AhPremiumResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| klines | object[] | true | A/H premium daily kline records |
| ∟ timestamp | string | false | Unix timestamp |
| ∟ ahpremium_rate | string | false | A/H premium rate |
| ∟ aprice | string | false | A-share price (CNY) |
| ∟ apreclose | string | false | A-share previous close (CNY) |
| ∟ hprice | string | false | H-share price (HKD) |
| ∟ hpreclose | string | false | H-share previous close (HKD) |
| ∟ currency_rate | string | false | CNH/HKD exchange rate |
| ∟ price_spread | string | false | Price spread |
---
# A/H Premium Intraday
URL: https://open.longbridge.com/docs/fundamental/market/ah-premium-intraday.md
Get intraday A/H premium timeseries data for a dual-listed security.
longbridge ah-premium intraday 939.HK
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | HK-side symbol of a dual-listed stock, e.g. `939.HK` |
## Request Example
```python
from longbridge.openapi import MarketContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = MarketContext(config)
resp = ctx.ah_premium_intraday("939.HK")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncMarketContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncMarketContext.create(config)
resp = await ctx.ah_premium_intraday("939.HK")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, MarketContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = MarketContext.new(config)
const resp = await ctx.ahPremiumIntraday('939.HK')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.market.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
MarketContext ctx = MarketContext.create(config)) {
var resp = ctx.getAhPremiumIntraday("939.HK").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, market::MarketContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = MarketContext::new(config);
let resp = ctx.ah_premium_intraday("939.HK").await?;
println!("{:?}", resp);
Ok(())
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/market"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := market.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.AhPremiumIntraday(context.Background(), "939.HK")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"klines": [
{
"ahpremium_rate": "0.1523",
"apreclose": "24.80",
"aprice": "25.10",
"currency_rate": "0.8920",
"hpreclose": "19.20",
"hprice": "19.50",
"price_spread": "1.23",
"timestamp": "1778198400"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [AhPremiumIntradayResponse](#AhPremiumIntradayResponse) |
| 400 | Bad request | None |
## Schemas
### AhPremiumIntradayResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| klines | object[] | true | Intraday A/H premium kline data, see [AhPremiumKline](#AhPremiumKline) |
| ∟ timestamp | string | false | Unix timestamp |
| ∟ ahpremium_rate | string | false | A/H premium rate |
| ∟ aprice | string | false | A-share price (CNY) |
| ∟ apreclose | string | false | A-share previous close (CNY) |
| ∟ hprice | string | false | H-share price (HKD) |
| ∟ hpreclose | string | false | H-share previous close (HKD) |
| ∟ currency_rate | string | false | CNH/HKD exchange rate |
| ∟ price_spread | string | false | Price spread |
---
# Broker Holding Daily
URL: https://open.longbridge.com/docs/fundamental/market/broker-holding-daily.md
:::warning Longbridge HK / SG accounts only
This method is available to Longbridge HK / SG accounts only. It works with any supported symbol, including US stocks.
:::
Get daily holding history for a specific broker in an HK-listed security.
longbridge broker-holding daily 700.HK --broker B01224
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | HK security symbol, e.g. `700.HK` |
| broker_id | string | YES | Broker participant ID, e.g. `B01224` |
## Request Example
```python
from longbridge.openapi import MarketContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = MarketContext(config)
resp = ctx.broker_holding_daily("700.HK", "B01224")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncMarketContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncMarketContext.create(config)
resp = await ctx.broker_holding_daily("700.HK", "B01224")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, MarketContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = MarketContext.new(config)
const resp = await ctx.brokerHoldingDaily('700.HK', 'B01224')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.market.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
MarketContext ctx = MarketContext.create(config)) {
var resp = ctx.getBrokerHoldingDaily("700.HK", "B01224").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, market::MarketContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = MarketContext::new(config);
let resp = ctx.broker_holding_daily("700.HK", "B01224").await?;
println!("{:?}", resp);
Ok(())
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/market"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := market.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.BrokerHoldingDaily(context.Background(), "700.HK", "B01224")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"list": [
{
"date": "2026.05.13",
"holding": "22903430",
"chg": "7029132.0000",
"ratio": "0.0025"
},
{
"date": "2026.05.12",
"holding": "15874298",
"chg": "-2150000.0000",
"ratio": "0.0017"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [BrokerHoldingDailyResponse](#BrokerHoldingDailyResponse) |
| 400 | Bad request | None |
## Schemas
### BrokerHoldingDailyHistoryResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| list | object[] | true | Daily holding history records |
| ∟ date | string | true | Date (e.g. `2026.05.13`) |
| ∟ holding | string | false | Total shares held |
| ∟ chg | string | false | Daily change in shares |
| ∟ ratio | string | false | Holding ratio |
---
# Broker Holding Detail
URL: https://open.longbridge.com/docs/fundamental/market/broker-holding-detail.md
:::warning Longbridge HK / SG accounts only
This method is available to Longbridge HK / SG accounts only. It works with any supported symbol, including US stocks.
:::
Get full broker holding detail list for an HK-listed security (all brokers and their positions).
longbridge broker-holding detail 700.HK
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | HK security symbol, e.g. `700.HK` |
## Request Example
```python
from longbridge.openapi import MarketContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = MarketContext(config)
resp = ctx.broker_holding_detail("700.HK")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncMarketContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncMarketContext.create(config)
resp = await ctx.broker_holding_detail("700.HK")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, MarketContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = MarketContext.new(config)
const resp = await ctx.brokerHoldingDetail('700.HK')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.market.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
MarketContext ctx = MarketContext.create(config)) {
var resp = ctx.getBrokerHoldingDetail("700.HK").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, market::MarketContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = MarketContext::new(config);
let resp = ctx.broker_holding_detail("700.HK").await?;
println!("{:?}", resp);
Ok(())
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/market"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := market.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.BrokerHoldingDetail(context.Background(), "700.HK")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"updated_at": "2026.05.13",
"list": [
{
"parti_number": "B01224",
"name": "HSBC Securities",
"strong": false,
"shares": {
"value": "25100",
"chg_1": "4000.0000",
"chg_5": "6100.0000",
"chg_20": "12600.0000",
"chg_60": "8800.0000"
},
"ratio": {
"value": "0.0025",
"chg_1": "0.0004",
"chg_5": "0.0006",
"chg_20": "0.0012",
"chg_60": "0.0009"
}
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [BrokerHoldingDetailResponse](#BrokerHoldingDetailResponse) |
| 400 | Bad request | None |
## Schemas
### BrokerHoldingDetailResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| updated_at | string | false | Last update date |
| list | object[] | true | Broker holding detail records, see [BrokerHoldingItem](#BrokerHoldingItem) |
### BrokerHoldingItem
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| parti_number | string | true | Broker participant number |
| name | string | false | Broker name |
| strong | boolean | false | Whether marked as strong holder |
| shares | object | false | Holding share counts |
| shares.value | string | false | Current shares held |
| shares.chg_1 | string | false | 1-day change |
| shares.chg_5 | string | false | 5-day change |
| shares.chg_20 | string | false | 20-day change |
| shares.chg_60 | string | false | 60-day change |
| ratio | object | false | Holding ratio |
| ratio.value | string | false | Current ratio |
| ratio.chg_1 | string | false | 1-day ratio change |
| ratio.chg_5 | string | false | 5-day ratio change |
| ratio.chg_20 | string | false | 20-day ratio change |
| ratio.chg_60 | string | false | 60-day ratio change |
---
# Broker Positions
URL: https://open.longbridge.com/docs/fundamental/market/broker-positions.md
:::warning Longbridge HK / SG accounts only
This method is available to Longbridge HK / SG accounts only. It works with any supported symbol, including US stocks.
:::
View broker holding positions for HK-listed stocks, including top buyers/sellers and full detail.
longbridge broker-holding 700.HK
longbridge broker-holding 9988.HK
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | HK security symbol, e.g. `700.HK` |
## Request Example
```python
from longbridge.openapi import MarketContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = MarketContext(config)
resp = ctx.broker_positions("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncMarketContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncMarketContext.create(config)
resp = await ctx.broker_positions("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, MarketContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = MarketContext.new(config)
const resp = await ctx.broker_positions('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.market.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
MarketContext ctx = MarketContext.create(config)) {
var resp = ctx.getBrokerPositions("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, market::MarketContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = MarketContext::new(config);
let resp = ctx.broker_positions("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::market;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
MarketContext ctx = MarketContext::create(config);
ctx.broker_positions("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/market"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := market.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.BrokerPositions(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"buy": [
{
"parti_number": "B01224",
"name": "HSBC",
"chg": "5000000",
"strong": true
}
],
"sell": [
{
"parti_number": "B01274",
"name": "Goldman Sachs HK",
"chg": "-3000000",
"strong": false
}
],
"updated_at": "2026.05.13"
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [BrokerHoldingResponse](#BrokerHoldingResponse) |
| 400 | Bad request | None |
## Schemas
### BrokerHoldingResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| buy | object[] | false | Top buying brokers |
| ∟ parti_number | string | true | Broker participant number |
| ∟ name | string | false | Broker name |
| ∟ chg | string | false | Position change |
| ∟ strong | boolean | false | Whether marked as strong holder |
| sell | object[] | false | Top selling brokers |
| ∟ parti_number | string | true | Broker participant number |
| ∟ name | string | false | Broker name |
| ∟ chg | string | false | Position change |
| ∟ strong | boolean | false | Whether marked as strong holder |
| updated_at | string | false | Last update timestamp |
---
# Index Components
URL: https://open.longbridge.com/docs/fundamental/market/index-components.md
Get the constituent stocks of an index or ETF with sorting options and rise/fall statistics.
longbridge constituent HSI.HK
longbridge constituent SPY.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Index or ETF symbol, e.g. `HSI.HK`, `SPY.US` |
## Request Example
```python
from longbridge.openapi import MarketContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = MarketContext(config)
resp = ctx.index_components("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncMarketContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncMarketContext.create(config)
resp = await ctx.index_components("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, MarketContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = MarketContext.new(config)
const resp = await ctx.index_components('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.market.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
MarketContext ctx = MarketContext.create(config)) {
var resp = ctx.getIndexComponents("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, market::MarketContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = MarketContext::new(config);
let resp = ctx.index_components("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::market;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
MarketContext ctx = MarketContext::create(config);
ctx.index_components("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/market"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := market.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.IndexComponents(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"fall_num": 10,
"flat_num": 3,
"rise_num": 7,
"stocks": [
{
"symbol": "9988.HK",
"name": "BABA-W",
"market": "HK",
"last_done": "140.90",
"prev_close": "132.80",
"chg": "0.0610",
"amount": "93828577",
"inflow": "18483450",
"balance": "13320299492",
"circulating_shares": "19192403958",
"total_shares": "19192403958",
"trade_status": 105,
"intro": "China's largest e-commerce platform",
"delay": false,
"tags": [
"Top gainers"
]
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [IndexConstituentsResponse](#IndexConstituentsResponse) |
| 400 | Bad request | None |
## Schemas
### IndexConstituentsResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| rise_num | integer | false | Number of rising stocks |
| fall_num | integer | false | Number of falling stocks |
| flat_num | integer | false | Number of flat stocks |
| stocks | object[] | true | List of constituent stocks |
| ∟ symbol | string | true | Security symbol |
| ∟ name | string | true | Security name |
| ∟ market | string | false | Market |
| ∟ last_done | string | false | Last trade price |
| ∟ prev_close | string | false | Previous close |
| ∟ chg | string | false | Price change percentage |
| ∟ amount | string | false | Trading volume amount |
| ∟ inflow | string | false | Capital inflow |
| ∟ circulating_shares | string | false | Circulating shares |
| ∟ total_shares | string | false | Total shares |
| ∟ balance | string | false | Market cap |
| ∟ trade_status | integer | false | Trading status code |
| ∟ intro | string | false | Brief description |
| ∟ delay | boolean | false | Whether data is delayed |
| ∟ tags | string[] | false | Tags |
---
# Trading Stats
URL: https://open.longbridge.com/docs/fundamental/market/trading-stats.md
Get trade statistics showing price distribution by volume for a security.
longbridge trade-stats 700.HK
longbridge trade-stats TSLA.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `700.HK` |
## Request Example
```python
from longbridge.openapi import MarketContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = MarketContext(config)
resp = ctx.trading_stats("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncMarketContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncMarketContext.create(config)
resp = await ctx.trading_stats("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, MarketContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = MarketContext.new(config)
const resp = await ctx.trading_stats('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.market.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
MarketContext ctx = MarketContext.create(config)) {
var resp = ctx.getTradingStats("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, market::MarketContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = MarketContext::new(config);
let resp = ctx.trading_stats("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::market;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
MarketContext ctx = MarketContext::create(config);
ctx.trading_stats("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/market"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := market.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.TradingStats(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"statistics": {
"avgprice": "210.50",
"buy": "45000000",
"sell": "38000000",
"neutral": "12000000",
"total_amount": "95000000",
"trades_count": "125000",
"preclose": "208.20",
"timestamp": "1778198400",
"trade_date": [
"2026-05-13"
]
},
"trades": [
{
"price": "210.00",
"buy_amount": "5000000",
"sell_amount": "4000000",
"neutral_amount": "1000000"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [TradeStatsResponse](#TradeStatsResponse) |
| 400 | Bad request | None |
## Schemas
### TradeStatsResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| statistics | object | true | Aggregate trade statistics |
| statistics.avgprice | string | false | Average trade price |
| statistics.buy | string | false | Total buy volume |
| statistics.sell | string | false | Total sell volume |
| statistics.neutral | string | false | Total neutral volume |
| statistics.total_amount | string | false | Total traded amount |
| statistics.trades_count | string | false | Total trade count |
| statistics.preclose | string | false | Previous close price |
| statistics.timestamp | string | false | Statistics timestamp |
| statistics.trade_date | string[] | false | Trading dates included |
| trades | object[] | false | Price-level trade distribution |
| ∟ price | string | true | Price level |
| ∟ buy_amount | string | false | Buy amount at this price |
| ∟ sell_amount | string | false | Sell amount at this price |
| ∟ neutral_amount | string | false | Neutral amount at this price |
---
# Overview
URL: https://open.longbridge.com/docs/fundamental/overview.md
# Fundamental API Overview
Research and market data APIs covering company fundamentals, market structure, and financial calendars. All methods are read-only and available through the SDK.
## FundamentalContext
Company-level financial data and corporate information.
| Method | Description |
|---|---|
| [company_profile](./fundamental/company-profile) | Company overview, industry, and key facts |
| [financial_report](./fundamental/financial-report) | Income statement, balance sheet, and cash flow |
| [valuations](./fundamental/valuations) | PE, PB, PS, EV/EBITDA and other valuation metrics |
| [dividends](./fundamental/dividends) | Historical dividend records |
| [fund_holdings](./fundamental/fund-holdings) | Institutional and fund ownership |
| [shareholders](./fundamental/shareholders) | Major shareholders |
| [executives](./fundamental/executives) | Executive team and board members |
| [corp_action](./fundamental/corporate-actions) | Splits, bonus issues, rights offerings |
## MarketContext
Market-level data including index components, broker positions, and anomaly scanning.
| Method | Description |
|---|---|
| [market_status](../market/market-status) | Current trading session status for each market |
| [trading_stats](./market/trading-stats) | Intraday trading statistics for a symbol |
| [index_components](./market/index-components) | Constituents of a market index |
| [ah_premium](./market/ah-premium) | A/H share premium ratio for dual-listed stocks |
| [broker_positions](./market/broker-positions) | HK broker participant holdings (CCASS) |
| [unusual_items](../market/unusual-items) | Unusual price or volume movements |
## CalendarContext
[Financial event calendars](https://longbridge.com/calendar/macrodata) for planning around earnings, dividends, and macro releases.
| Method | Description |
|---|---|
| [earnings_calendar](../market/calendar/earnings-calendar) | Upcoming and recent earnings release dates |
| [dividend_calendar](../market/calendar/dividend-calendar) | Ex-dividend and payment dates |
| [ipo_calendar](../market/calendar/ipo-calendar) | IPO subscription and listing dates |
| [split_calendar](../market/calendar/split-calendar) | Stock split effective dates |
| [macro_calendar](../market/calendar/macro-calendar) | Economic data release schedule |
---
# Getting Started
URL: https://open.longbridge.com/docs/getting-started.md
## Foreword
Longbridge OpenAPI SDK is implemented based on Rust we have released SDK for Python, Node.js, Rust, C++/C and Java ..., and support for other languages will be launched in the future.
## API Host
- HTTP API - `https://openapi.longbridge.com`
- WebSocket Quote - `wss://openapi-quote.longbridge.com`
- WebSocket Trade - `wss://openapi-trade.longbridge.com`
:::tip
For access in mainland China, you can use `.cn` domains for better connectivity:
- HTTP API - `https://openapi.longbridge.cn`
- WebSocket Quote - `wss://openapi-quote.longbridge.cn`
- WebSocket Trade - `wss://openapi-trade.longbridge.cn`
The SDK automatically selects the access point by network. If the SDK selects incorrectly, set the environment variable `LONGBRIDGE_REGION` (e.g. `cn` or `hk`).
:::
### Access Points
The access point (`.com` / `.cn`) is network routing only. Both serve identical data and identical auth: a token issued through one is accepted by the other.
## Time Format
All API response are used [Unix Timestamp](https://en.wikipedia.org/wiki/Unix_time), timezone is UTC.
## Environment Requirements
- Python 3
- Pip
## CLI Quick Start
If you don't need to write code, the [Longbridge CLI](/docs/cli) offers a lightweight alternative — install once, authorize via OAuth, no environment variables needed.
### Installation
```bash
brew install --cask longbridge/tap/longbridge-terminal
```
```bash
curl -sSL https://open.longbridge.com/longbridge/longbridge-terminal/install | sh
```
```powershell
scoop install https://open.longbridge.com/longbridge/longbridge-terminal/longbridge.json
```
```powershell
iwr https://open.longbridge.com/longbridge/longbridge-terminal/install.ps1 | iex
```
### Login
longbridge auth login
The browser opens the authorization page automatically. The token is saved after approval — no need to repeat.
## Install SDK
:::warning Package Renamed
The SDK package has been renamed from `longport` to `longbridge`. The old `longport` package is deprecated. If you were previously using `longport`, please uninstall it before installing the new package.
:::
```bash
pip3 install longbridge
```
```bash
yarn add longbridge
```
```toml
[dependencies]
longbridge = "4.0.5"
tokio = { version = "1", features = "rt-multi-thread" }
```
```xml
io.github.longbridge
openapi-sdk
4.0.5
```
```shell
go get github.com/longbridge/openapi-go
```
Let's take obtaining assets as an example to demonstrate how to use the SDK.
## Configuration
1. [Download App](https://longbridge.com/hk/download) and open an account.
2. Get authentication credentials from [Longbridge Developers](https://open.longbridge.com) official website
### Authentication Methods
Longbridge OpenAPI supports two authentication methods:
#### Method 1: OAuth 2.0 (Recommended) ⭐ {#oauth-2-0}
OAuth 2.0 is the modern authentication method that uses Bearer tokens without requiring HMAC signatures, making it more secure and convenient.
**Step 1: Register OAuth Client**
Run the following command to register an OAuth client and get your `client_id`:
```bash
curl -X POST https://openapi.longbridge.com/oauth2/register \
-H "Content-Type: application/json" \
-d '{
"redirect_uris": ["http://localhost:60355/callback"],
"token_endpoint_auth_method": "none",
"grant_types": ["authorization_code","refresh_token"],
"response_types": ["code"],
"client_name": "My Longbridge OpenAPI"
}'
```
```powershell
$body = @{
redirect_uris = @("http://localhost:60355/callback")
token_endpoint_auth_method = "none"
grant_types = @("authorization_code", "refresh_token")
response_types = @("code")
client_name = "My Longbridge OpenAPI"
} | ConvertTo-Json
Invoke-RestMethod -Method POST `
-Uri "https://openapi.longbridge.com/oauth2/register" `
-ContentType "application/json" `
-Body $body
```
Response example:
```json
{
"client_id": "72d9caaf-0bd4-4000-85a7-8c7978c74544",
"client_id_issued_at": 1773311221,
"client_secret_expires_at": 1773314821,
"client_name": "My Longbridge OpenAPI",
"redirect_uris": ["http://localhost:60355/callback"],
"grant_types": ["authorization_code", "refresh_token"],
"token_endpoint_auth_method": "none",
"response_types": ["code"],
"registration_access_token": "BVlMLEtNUUu4FoRFNItC2FfeR/rLpqLNyEuCJNNTCWE=",
"registration_client_uri": "https://openapi.longbridge.com/oauth2/register/72d9caaf-0bd4-4000-85a7-8c7978c74544"
}
```
Save the `client_id` for later use.
**Step 2: Authorize and Get Token**
The SDK provides built-in OAuth support. Use `OAuthBuilder` to run the browser flow; after authorization, use `Config.from_oauth()` to create the configuration. The token is persisted automatically and refreshed when expired.
**Token storage path:** `~/.longbridge/openapi/tokens/` (macOS/Linux), or `%USERPROFILE%\.longbridge\openapi\tokens\` on Windows.
```python
from longbridge.openapi import Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(
lambda url: print(f"Open this URL to authorize: {url}")
)
config = Config.from_oauth(oauth)
```
```python
import asyncio
from longbridge.openapi import Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print(f"Open this URL to authorize: {url}")
)
config = Config.from_oauth(oauth)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, OAuth } = require('longbridge')
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
```
```rust
use std::sync::Arc;
use longbridge::{Config, oauth::OAuthBuilder};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
Ok(())
}
```
```java
import com.longbridge.*;
public class Main {
public static void main(String[] args) throws Exception {
String clientId = "your-client-id";
OAuth oauth = new OAuthBuilder(clientId)
.build(url -> System.out.println("Open to authorize: " + url))
.get();
try (oauth) {
Config config = Config.fromOAuth(oauth);
}
}
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
_ = conf // use conf for TradeContext or QuoteContext
}
```
```cpp
#include
#include
using namespace longbridge;
int main(int argc, char const* argv[]) {
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
Config config = Config::from_oauth(*res);
// Use config to create QuoteContext or TradeContext
});
std::cin.get();
return 0;
}
```
:::tip OAuth Benefits
- More secure (no shared secret)
- Simpler integration (no signature calculation)
- Token-based modern authentication
- Better suited for modern applications
:::
:::caution Token Security
OAuth tokens should be stored securely in your application (e.g., encrypted file, secure keychain), **not in environment variables** for security reasons.
:::
**OAuth Scopes**
APIs that read account data or trade require the token to carry the matching scope; market data and other general APIs need no extra scope. Scopes are identified by key:
| Scope key | Grants |
| --------- | ------ |
| `watchlist` | Watchlist groups (read and write) |
| `account.read` | Account assets, positions and cash flow (read-only) |
| `trade.read` | Order and execution lookup (read-only) |
| `trade.write` | Placing, replacing and canceling orders, and other trading writes |
Longbridge US accounts currently have market data permission only.
The `/oauth2/register` response lists scopes as numeric ids (for example `"4 6 10 11 12"`). The ids are environment-specific: on `openapi.longbridge.com`, `4`, `6`, `10` and `11` are `watchlist`, `account.read`, `trade.read` and `trade.write`. Treat any other id as opaque and rely on the scope keys.
If an API returns error `403308` (`Target API's scope is not in authorized scopes`), the token was not granted the scope that API needs. Delete the stored token under `~/.longbridge/openapi/tokens/`, authorize again and grant that scope. See [Error Codes](/docs/api?page=error-codes).
**Sign Out**
The SDK has no logout method. To sign out, delete the stored token file `~/.longbridge/openapi/tokens/`; the next run asks you to authorize again. If you use the CLI, run `longbridge auth logout`, which removes the token file and the client registration. Deleting the file only stops this machine from reusing it; an access token that has already been issued stays valid until it expires.
#### Method 2: Legacy API Key (Compatible)
**_Get App Key, App Secret, Access Token and other information_**
Log in at [https://open.longbridge.com/](https://open.longbridge.com/) and open **User Center**.
The **application credential** (App Key, App Secret, Access Token) is shown on that page. This Access Token is the **legacy** API Key credential; it is **not** the same as the access token obtained via OAuth or the Refresh Token API. Set these as environment variables for development.
### Environment Variables
:::caution
Please pay attention to protect your **Access Token** information, anyone who gets it can trade your account through OpenAPI!
:::
**API Key credentials (required for legacy API Key):**
| Environment Variable | Description |
| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `LONGBRIDGE_APP_KEY` | App key from developer center |
| `LONGBRIDGE_APP_SECRET` | App secret from developer center |
| `LONGBRIDGE_ACCESS_TOKEN` | Legacy Access Token from [https://open.longbridge.com/](https://open.longbridge.com/) (User Center → application credential). Not the OAuth access token. |
**Other environment variables:**
| Name | Description |
| ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| `LONGBRIDGE_LANGUAGE` | Language identifier, `zh-CN`, `zh-HK` or `en` (Default: `en`) |
| `LONGBRIDGE_HTTP_URL` | HTTP endpoint url (Default: `https://openapi.longbridge.com`) |
| `LONGBRIDGE_QUOTE_WS_URL` | Quote websocket endpoint url (Default: `wss://openapi-quote.longbridge.com/v2`) |
| `LONGBRIDGE_TRADE_WS_URL` | Trade websocket endpoint url (Default: `wss://openapi-trade.longbridge.com/v2`) |
| `LONGBRIDGE_REGION` | Override API region; SDK auto-selects by network. Set to `cn` or `hk` if incorrect. |
| `LONGBRIDGE_ENABLE_OVERNIGHT` | Enable overnight quote, `true` or `false` (Default: `false`). Overnight quotes are included free in US LV1. US stocks only. |
| `LONGBRIDGE_PUSH_CANDLESTICK_MODE` | `realtime` or `confirmed` (Default: `realtime`) |
| `LONGBRIDGE_PRINT_QUOTE_PACKAGES` | Print quote packages when connected, `true` or `false` (Default: `true`) |
| `LONGBRIDGE_LOG_PATH` | Set the path of the log files (Default: no logs) |
:::info
The SDK also accepts the legacy `LONGPORT_*` variable names for backward compatibility.
:::
We recommend that you set the environment variables. For the convenience of demonstration, these environment variables will be used in the sample code in the documents in the following chapters.
:::tip About ENV
The ENV variables are **not necessary** conditions, if it is inconvenient to set the ENV variables or encounter problems that are difficult to solve, you can not set the ENV variables, but directly use the parameters in the code to initialize.
The `Config` in Longbridge OpenAPI SDK can be created with `Config.from_apikey_env()` (or `Config.fromApikeyEnv()` in Node/Java) when using environment variables, or `Config.from_apikey(app_key, app_secret, access_token)` when passing parameters directly. See the comments in the example code below for "Init config without ENV".
:::
#### Set Environment for macOS / Linux
Open the terminal and enter the following command:
```bash
export LONGBRIDGE_APP_KEY="App Key from user center"
export LONGBRIDGE_APP_SECRET="App Secret from user center"
export LONGBRIDGE_ACCESS_TOKEN="Access Token from user center"
```
#### Set Environment for Windows
Windows is a little more complicated, we provide two methods to set the environment variables.
1. **Through the GUI**: Right click on "My Computer" on the desktop, select "Properties", click "Advanced system settings" in the pop-up window.
- Click "Environment Variables" in the pop-up window.
- Click "New" in the pop-up window, then enter the environment variable name, such as `LONGBRIDGE_APP_KEY`, `Value` respectively fill in the App Key, App Secret, Access Token obtained from the page.
2. **Through the CMD**: Press the `Win + R` shortcut keys and enter the `cmd` command to start the command line (it is recommended to use [Windows Terminal](https://apps.microsoft.com/store/detail/windows-terminal/9N0DX20HK701) for a better development experience).
Enter the following command in the command line to set the environment variable:
```bash
C:\Users\jason> setx LONGBRIDGE_APP_KEY "App Key from user center"
Success: the specified value has been saved.
C:\Users\jason> setx LONGBRIDGE_APP_SECRET "App Secret from user center"
Success: the specified value has been saved.
C:\Users\jason> setx LONGBRIDGE_ACCESS_TOKEN "Access Token from user center"
Success: the specified value has been saved.
```
:::caution Windows ENV Restrictions
Windows ENV Restrictions, when the above commands are executed successfully, you need to restart Windows or log out and log in again before you can read it.
:::
After logging out or restarting, open the command line again and enter the following command to verify that the environment variables are set correctly:
```bash
C:\Users\jason> set LONGBRIDGE
LONGBRIDGE_APP_KEY=xxxxxxx
LONGBRIDGE_APP_SECRET=xxxxxx
LONGBRIDGE_ACCESS_TOKEN=xxxxxxx
```
If it prints the value you just set correctly, then the environment variable is right.
### Refresh Access Token
:::info
This applies to **Legacy API Key** authentication only. OAuth 2.0 tokens are refreshed automatically by the SDK.
:::
The Legacy API Key `Access Token` expires after 90 days by default. Call `Config.refresh_access_token()` to obtain a new token before it expires, then update your stored `LONGBRIDGE_ACCESS_TOKEN` with the returned value.
```python
from datetime import datetime, timedelta
from longbridge.openapi import Config
config = Config.from_apikey("YOUR_APP_KEY", "YOUR_APP_SECRET", "YOUR_ACCESS_TOKEN")
# Expire 3 years from now
new_token = config.refresh_access_token(expired_at=datetime.now() + timedelta(days=365 * 3))
print("New access token:", new_token)
# Use the new token to build a new Config, or persist it as LONGBRIDGE_ACCESS_TOKEN
new_config = Config.from_apikey("YOUR_APP_KEY", "YOUR_APP_SECRET", new_token)
```
```python
import asyncio
from datetime import datetime, timedelta
from longbridge.openapi import Config
async def main() -> None:
config = Config.from_apikey("YOUR_APP_KEY", "YOUR_APP_SECRET", "YOUR_ACCESS_TOKEN")
# Expire 3 years from now
new_token = await config.refresh_access_token_async(expired_at=datetime.now() + timedelta(days=365 * 3))
print("New access token:", new_token)
# Use the new token to build a new Config, or persist it as LONGBRIDGE_ACCESS_TOKEN
new_config = Config.from_apikey("YOUR_APP_KEY", "YOUR_APP_SECRET", new_token)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config } = require('longbridge')
const config = Config.fromApikey('YOUR_APP_KEY', 'YOUR_APP_SECRET', 'YOUR_ACCESS_TOKEN')
// Expire 3 years from now
const expiredAt = new Date()
expiredAt.setFullYear(expiredAt.getFullYear() + 3)
const newToken = await config.refreshAccessToken(expiredAt)
console.log('New access token:', newToken)
// Use the new token to build a new Config, or persist it as LONGBRIDGE_ACCESS_TOKEN
const newConfig = Config.fromApikey('YOUR_APP_KEY', 'YOUR_APP_SECRET', newToken)
```
```rust
use longbridge::Config;
use time::{Duration, OffsetDateTime};
#[tokio::main]
async fn main() -> Result<(), Box> {
let config = Config::from_apikey("YOUR_APP_KEY", "YOUR_APP_SECRET", "YOUR_ACCESS_TOKEN")?;
// Expire 3 years from now
let expired_at = OffsetDateTime::now_utc() + Duration::days(365 * 3);
let new_token = config.refresh_access_token(Some(expired_at)).await?;
println!("New access token: {}", new_token);
// Use the new token to build a new Config, or persist it as LONGBRIDGE_ACCESS_TOKEN
let new_config = Config::from_apikey("YOUR_APP_KEY", "YOUR_APP_SECRET", &new_token)?;
Ok(())
}
```
```java
import com.longbridge.Config;
import java.time.OffsetDateTime;
public class Main {
public static void main(String[] args) throws Exception {
Config config = Config.fromApikey("YOUR_APP_KEY", "YOUR_APP_SECRET", "YOUR_ACCESS_TOKEN");
// Expire 3 years from now
OffsetDateTime expiredAt = OffsetDateTime.now().plusYears(3);
String newToken = config.refreshAccessToken(expiredAt).get();
System.out.println("New access token: " + newToken);
// Use the new token to build a new Config, or persist it as LONGBRIDGE_ACCESS_TOKEN
Config newConfig = Config.fromApikey("YOUR_APP_KEY", "YOUR_APP_SECRET", newToken);
}
}
```
```cpp
#include
#include
#include
using namespace longbridge;
int main() {
Config config = Config::from_apikey("YOUR_APP_KEY", "YOUR_APP_SECRET", "YOUR_ACCESS_TOKEN");
// Expire 3 years from now (Unix timestamp)
int64_t expired_at = static_cast(std::time(nullptr)) + 3LL * 365 * 24 * 3600;
config.refresh_access_token(expired_at, [](auto res) {
if (!res) {
std::cerr << "Error: " << *res.status().message() << std::endl;
return;
}
std::cout << "New access token: " << *res << std::endl;
// Use the new token to build a new Config, or persist it as LONGBRIDGE_ACCESS_TOKEN
Config new_config = Config::from_apikey("YOUR_APP_KEY", "YOUR_APP_SECRET", *res);
});
std::cin.get();
return 0;
}
```
The `expired_at` parameter sets when the new token expires (default: **90 days** from now).
## Scene Demonstration
### Get Account Balance
Create `account_asset.py` and paste the code below:
```python
from longbridge.openapi import TradeContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(
lambda url: print(f"Open this URL to authorize: {url}")
)
config = Config.from_oauth(oauth)
# Or use API Key: config = Config.from_apikey_env()
# Or without ENV: config = Config.from_apikey("YOUR_APP_KEY", "YOUR_APP_SECRET", "YOUR_ACCESS_TOKEN")
ctx = TradeContext(config)
resp = ctx.account_balance()
print(resp)
```
Run it
```bash
python account_asset.py
```
Create `account_asset_async.py` and paste the code below:
```python
import asyncio
from longbridge.openapi import AsyncTradeContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print(f"Open this URL to authorize: {url}")
)
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.account_balance()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
Run it
```bash
python account_asset_async.py
```
Create `account_asset.js` and paste the code below:
```javascript
const { Config, TradeContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
// Or use API Key: const config = Config.fromApikeyEnv()
const ctx = TradeContext.new(config)
const resp = await ctx.accountBalance()
for (const obj of resp) {
console.log(obj.toString())
}
}
main().catch(console.error)
```
Run it
```bash
node account_asset.js
```
Create `main.rs` and paste the code below:
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, trade::TradeContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
// Or use API Key: let config = Arc::new(Config::from_apikey_env()?);
// Or without ENV: let config = Arc::new(Config::from_apikey("YOUR_APP_KEY", "YOUR_APP_SECRET", "YOUR_ACCESS_TOKEN")?);
let (ctx, _) = TradeContext::new(config);
let resp = ctx.account_balance(None).await?;
println!("{:?}", resp);
Ok(())
}
```
Run it
```bash
cargo run
```
Create `Main.java` and paste the code below:
```java
import com.longbridge.*;
import com.longbridge.trade.*;
class Main {
public static void main(String[] args) throws Exception {
String clientId = "your-client-id";
OAuth oauth = new OAuthBuilder(clientId)
.build(url -> System.out.println("Open to authorize: " + url))
.get();
try (oauth;
Config config = Config.fromOAuth(oauth);
TradeContext ctx = TradeContext.create(config)) {
// Or use API Key: Config.fromApikeyEnv(); TradeContext.create(config)
for (AccountBalance obj : ctx.getAccountBalance().get()) {
System.out.println(obj);
}
}
}
}
```
Run it
```bash
mvn compile exec:exec
```
Create `main.go` and paste the code below:
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/trade"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
// Or use API Key from ENV: config.New()
// Or without ENV: config.New(config.WithConfigKey("YOUR_APP_KEY", "YOUR_APP_SECRET", "YOUR_ACCESS_TOKEN"))
if err != nil {
log.Fatal(err)
}
tradeContext, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer tradeContext.Close()
ctx := context.Background()
ab, err := tradeContext.AccountBalance(ctx, &trade.GetAccountBalance{})
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", ab[0])
}
```
Run:
```shell
go mod tidy
go run ./
```
Create `account_asset.cpp` and paste the code below:
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::trade;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
TradeContext ctx = TradeContext::create(config);
ctx.account_balance([](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
for (const auto& b : *res) {
std::cout << b.currency << " " << (double)b.available_cash << std::endl;
}
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
Run it
```bash
g++ -std=c++17 account_asset.cpp -o account_asset -llongbridge && ./account_asset
```
After running, the output is as follows:
```
[
AccountBalance {
total_cash: 503898884.81,
max_finance_amount: 0.00,
remaining_finance_amount: 501403229.49,
risk_level: Some(1),
margin_call: 0,
currency: "HKD",
cash_infos: [
CashInfo {
withdraw_cash: 501214985.15,
available_cash: 501214985.15,
frozen_cash: 584438.25,
settling_cash: -3897793.90,
currency: "HKD",
},
CashInfo {
withdraw_cash: -25546.89,
available_cash: -25546.89,
frozen_cash: 295768.57,
settling_cash: 2326.60,
currency: "USD",
}
]
}
]
```
### Subscribe Quote
To subscribe to market data, please check the [Developer Center](https://open.longbridge.com/account) - "Quote authority" is correct
- [HK Market](https://longbridge.com/hk/) - BMP basic quotation is unable to subscribe with WebSocket as it has no real-time quote push.
- US Market - US LV1 (Only OpenAPI).
Before running, visit the [Developer Center](https://open.longbridge.com/dashboard) and ensure that the account has the correct quote level.
:::info
If you do not have the quotes authority, you can enter "Me - My Quotes - Store" to purchase the authority through the "Longbridge" mobile app.
https://longbridge.com/download
:::
When you have the correct Quote authority, it might look like this:
Create `subscribe_quote.py` and paste the code below:
```python
from time import sleep
from longbridge.openapi import QuoteContext, Config, OAuthBuilder, SubType, PushQuote
def on_quote(symbol: str, quote: PushQuote):
print(symbol, quote)
oauth = OAuthBuilder("your-client-id").build(
lambda url: print(f"Open this URL to authorize: {url}")
)
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.set_on_quote(on_quote)
ctx.subscribe(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"], [SubType.Quote])
sleep(30)
```
Run it
```bash
python subscribe_quote.py
```
Create `subscribe_quote_async.py` and paste the code below:
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder, SubType, PushQuote
async def on_quote(symbol: str, quote: PushQuote) -> None:
print(symbol, quote)
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print(f"Open this URL to authorize: {url}")
)
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config, loop_=asyncio.get_running_loop())
ctx.set_on_quote(on_quote)
await ctx.subscribe(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"], [SubType.Quote])
await asyncio.sleep(30)
if __name__ == "__main__":
asyncio.run(main())
```
Run it
```bash
python subscribe_quote_async.py
```
Create `subscribe_quote.js` and paste the code below:
```javascript
const { Config, QuoteContext, SubType, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
ctx.setOnQuote((_, event) => console.log(event.toString()))
await ctx.subscribe(['700.HK', 'AAPL.US', 'TSLA.US', 'NFLX.US'], [SubType.Quote])
await new Promise(() => {})
}
main().catch(console.error)
```
Run it
```bash
node subscribe_quote.js
```
Create `main.rs` and paste the code below:
```rust
use std::sync::Arc;
use longbridge::{
oauth::OAuthBuilder,
quote::{QuoteContext, SubFlags},
Config,
};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, mut receiver) = QuoteContext::new(config);
ctx.subscribe(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"], SubFlags::QUOTE)
.await?;
while let Some(event) = receiver.recv().await {
println!("{:?}", event);
}
Ok(())
}
```
Run it
```bash
cargo run
```
Create `Main.java` and paste the code below:
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
String clientId = "your-client-id";
OAuth oauth = new OAuthBuilder(clientId)
.build(url -> System.out.println("Open to authorize: " + url))
.get();
try (oauth;
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
ctx.setOnQuote((symbol, quote) -> {
System.out.printf("%s\t%s\n", symbol, quote);
});
ctx.subscribe(new String[] { "700.HK", "AAPL.US", "TSLA.US", "NFLX.US" }, SubFlags.Quote).get();
Thread.sleep(30000);
}
}
}
```
Run it
```bash
mvn compile exec:exec
```
Create file `main.go` and paste the code below:
```go
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"time"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/quote"
)
func main() {
// create quote context from environment variables
conf, err := config.New()
if err != nil {
log.Fatal(err)
}
quoteContext, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
return
}
defer quoteContext.Close()
ctx := context.Background()
quoteContext.OnQuote(func(pe *quote.PushQuote) {
bytes, _ := json.Marshal(pe)
fmt.Println(string(bytes))
})
quoteContext.OnDepth(func(d *quote.PushDepth) {
bytes, _ := json.Marshal(d)
if d.Sequence != 0 {
fmt.Print(time.UnixMicro(d.Sequence/1000).Format(time.RFC3339) + " ")
}
fmt.Println(string(bytes))
})
// Subscribe some symbols
err = quoteContext.Subscribe(ctx, []string{"700.HK", "AAPL.US", "NFLX.US"}, []quote.SubType{quote.SubTypeDepth}, true)
if err != nil {
log.Fatal(err)
return
}
quitChannel := make(chan os.Signal, 1)
signal.Notify(quitChannel, syscall.SIGINT, syscall.SIGTERM)
<-quitChannel
}
```
Run:
```shell
go run ./
```
Create `subscribe_quote.cpp` and paste the code below:
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static QuoteContext g_ctx;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
g_ctx = QuoteContext::create(config);
g_ctx.set_on_quote([](auto event) {
std::cout << event->symbol
<< " last_done=" << (double)event->last_done
<< " volume=" << event->volume << std::endl;
});
std::vector symbols = {"700.HK", "AAPL.US", "TSLA.US", "NFLX.US"};
g_ctx.subscribe(symbols, SubFlags::QUOTE(), [](auto res) {
if (!res) {
std::cout << "failed to subscribe: " << *res.status().message() << std::endl;
}
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
Run it
```bash
g++ -std=c++17 subscribe_quote.cpp -o subscribe_quote -llongbridge && ./subscribe_quote
```
After running, the output is as follows:
```
700.HK PushQuote {
last_done: 367.000,
open: 362.000,
high: 369.400,
low: 356.000,
timestamp: "2022-06-06T08:10:00Z",
volume: 22377421,
turnover: 8081883405.000,
trade_status: Normal,
trade_session: Normal
}
AAPL.US PushQuote {
last_done: 147.350,
open: 150.700,
high: 151.000,
low: 146.190,
timestamp: "2022-06-06T11:57:36Z",
volume: 3724407,
turnover: 550606662.815,
trade_status: Normal,
trade_session: Pre
}
NFLX.US PushQuote {
last_done: 201.250,
open: 205.990,
high: 205.990,
low: 200.110,
timestamp: "2022-06-06T11:57:26Z",
volume: 137821,
turnover: 27888085.590,
trade_status: Normal,
trade_session: Pre
}
```
### Submit Order
Next, we will do a [submit order](https://open.longbridge.com/docs/trade/order/submit) action, we assume that to buy `700.HK` at 50 HKD and quantity is `100`.
> NOTE: In order to prevent a successful test buy, the demo here gives a lower price and avoids the transaction. OpenAPI operations are equivalent to online transactions, please operate with caution, and pay attention to parameter details during development and debugging.
Create `submit_order.py` and paste the code below:
```python
from decimal import Decimal
from longbridge.openapi import TradeContext, Config, OAuthBuilder, OrderSide, OrderType, TimeInForceType
oauth = OAuthBuilder("your-client-id").build(
lambda url: print(f"Open this URL to authorize: {url}")
)
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.submit_order(
side=OrderSide.Buy,
symbol="700.HK",
order_type=OrderType.LO,
submitted_price=Decimal(50),
submitted_quantity=Decimal(200),
time_in_force=TimeInForceType.Day,
remark="Hello from Python SDK",
)
print(resp)
```
Run it
```bash
python submit_order.py
```
Create `submit_order_async.py` and paste the code below:
```python
import asyncio
from decimal import Decimal
from longbridge.openapi import AsyncTradeContext, Config, OAuthBuilder, OrderSide, OrderType, TimeInForceType
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print(f"Open this URL to authorize: {url}")
)
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.submit_order(
side=OrderSide.Buy,
symbol="700.HK",
order_type=OrderType.LO,
submitted_price=Decimal(50),
submitted_quantity=Decimal(200),
time_in_force=TimeInForceType.Day,
remark="Hello from Python SDK",
)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
Run it
```bash
python submit_order_async.py
```
Create `submit_order.js` and paste the code below:
```javascript
const { Config, TradeContext, OrderType, OrderSide, Decimal, TimeInForceType, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = TradeContext.new(config)
const resp = await ctx.submitOrder({
symbol: '700.HK',
orderType: OrderType.LO,
side: OrderSide.Buy,
timeInForce: TimeInForceType.Day,
submittedPrice: new Decimal(50),
submittedQuantity: new Decimal(200),
})
console.log(resp.toString())
}
main().catch(console.error)
```
Run it
```bash
node submit_order.js
```
Create `main.rs` and paste the code below:
```rust
use std::sync::Arc;
use longbridge::{
decimal,
oauth::OAuthBuilder,
trade::{OrderSide, OrderType, SubmitOrderOptions, TimeInForceType, TradeContext},
Config,
};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = TradeContext::new(config);
let opts = SubmitOrderOptions::new(
"700.HK",
OrderType::LO,
OrderSide::Buy,
decimal!(200),
TimeInForceType::Day,
)
.submitted_price(decimal!(50i32));
let resp = ctx.submit_order(opts).await?;
println!("{:?}", resp);
Ok(())
}
```
Run it
```bash
cargo run
```
Create `Main.java` and paste the code below:
```java
import com.longbridge.*;
import com.longbridge.trade.*;
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) throws Exception {
String clientId = "your-client-id";
OAuth oauth = new OAuthBuilder(clientId)
.build(url -> System.out.println("Open to authorize: " + url))
.get();
try (oauth;
Config config = Config.fromOAuth(oauth);
TradeContext ctx = TradeContext.create(config)) {
SubmitOrderOptions opts = new SubmitOrderOptions("700.HK",
OrderType.LO,
OrderSide.Buy,
new BigDecimal(200),
TimeInForceType.Day).setSubmittedPrice(new BigDecimal(50));
SubmitOrderResponse resp = ctx.submitOrder(opts).get();
System.out.println(resp);
}
}
}
```
Run it
```bash
mvn compile exec:exec
```
Create `main.go` and paste the code below:
```go
package main
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"github.com/shopspring/decimal"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/trade"
)
func main() {
// create trade context from environment variables
conf, err := config.New()
if err != nil {
log.Fatal(err)
}
tradeContext, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
return
}
defer tradeContext.Close()
// subscribe order status
tradeContext.OnTrade(func(ev *trade.PushEvent) {
// handle order changing event
})
ctx := context.Background()
// submit order
order := &trade.SubmitOrder{
Symbol: "700.HK",
OrderType: trade.OrderTypeLO,
Side: trade.OrderSideBuy,
SubmittedQuantity: 200,
TimeInForce: trade.TimeTypeDay,
SubmittedPrice: decimal.NewFromFloat(12),
}
orderId, err := tradeContext.SubmitOrder(ctx, order)
if err != nil {
log.Fatal(err)
return
}
fmt.Printf("orderId: %v\n", orderId)
quitChannel := make(chan os.Signal, 1)
signal.Notify(quitChannel, syscall.SIGINT, syscall.SIGTERM)
<-quitChannel
}
```
Run:
```shell
go run ./
```
Create `submit_order.cpp` and paste the code below:
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::trade;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
TradeContext ctx = TradeContext::create(config);
SubmitOrderOptions opts{
"700.HK", OrderType::LO, OrderSide::Buy,
Decimal(200), TimeInForceType::Day, Decimal(50.0),
std::nullopt, std::nullopt, std::nullopt,
std::nullopt, std::nullopt, std::nullopt,
std::nullopt,
};
ctx.submit_order(opts, [](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
std::cout << "order id: " << res->order_id << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
Run it
```bash
g++ -std=c++17 submit_order.cpp -o submit_order -llongbridge && ./submit_order
```
After running, the output is as follows:
```
SubmitOrderResponse { order_id: "718437534753550336" }
```
### Get Today Orders
Create `today_orders.py` and paste the code below:
```python
from longbridge.openapi import TradeContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(
lambda url: print(f"Open this URL to authorize: {url}")
)
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.today_orders()
print(resp)
```
Run it
```bash
python today_orders.py
```
Create `today_orders_async.py` and paste the code below:
```python
import asyncio
from longbridge.openapi import AsyncTradeContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(
lambda url: print(f"Open this URL to authorize: {url}")
)
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.today_orders()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
Run it
```bash
python today_orders_async.py
```
Create `today_orders.js` and paste the code below:
```javascript
const { Config, TradeContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = TradeContext.new(config)
const resp = await ctx.todayOrders()
for (const obj of resp) {
console.log(obj.toString())
}
}
main().catch(console.error)
```
Run it
```bash
node today_orders.js
```
Create `main.rs` and paste the code below:
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, trade::TradeContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = TradeContext::new(config);
let resp = ctx.today_orders(None).await?;
for obj in resp {
println!("{:?}", obj);
}
Ok(())
}
```
Run it
```bash
cargo run
```
Create `Main.java` and paste the code below:
```java
import com.longbridge.*;
import com.longbridge.trade.*;
class Main {
public static void main(String[] args) throws Exception {
String clientId = "your-client-id";
OAuth oauth = new OAuthBuilder(clientId)
.build(url -> System.out.println("Open to authorize: " + url))
.get();
try (oauth;
Config config = Config.fromOAuth(oauth);
TradeContext ctx = TradeContext.create(config)) {
Order[] orders = ctx.getTodayOrders(null).get();
for (Order order : orders) {
System.out.println(order);
}
}
}
}
```
Run it
```bash
mvn compile exec:exec
```
Create `main.go` and paste the code below:
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/trade"
)
func main() {
// create trade context from environment variables
conf, err := config.New()
if err != nil {
log.Fatal(err)
}
tradeContext, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer tradeContext.Close()
ctx := context.Background()
// today orders
orders, err := tradeContext.TodayOrders(ctx, &trade.GetTodayOrders{})
if err != nil {
log.Fatal(err)
}
for _, order := range orders {
fmt.Printf("%+v\n", order)
}
}
```
Run:
```shell
go run ./
```
Create `today_orders.cpp` and paste the code below:
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::trade;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
TradeContext ctx = TradeContext::create(config);
ctx.today_orders(std::nullopt, [](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
for (auto it = res->cbegin(); it != res->cend(); ++it) {
std::cout << "order_id=" << it->order_id
<< " quantity=" << it->quantity << std::endl;
}
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
Run it
```bash
g++ -std=c++17 today_orders.cpp -o today_orders -llongbridge && ./today_orders
```
After running, the output is as follows:
```
Order {
order_id: "718437534753550336",
status: NotReported,
stock_name: "TENCENT",
quantity: 200,
executed_quantity: None,
price: Some(50.000),
executed_price: None,
submitted_at: 2022-06-06T12:14:16Z,
side: Buy,
symbol: "700.HK",
order_type: LO,
last_done: None,
trigger_price: Some(0.000),
msg: "",
tag: Normal,
time_in_force: Day,
expire_date: Some(NaiveDate(Date { year: 2022, ordinal: 158 })),
updated_at: Some(2022-06-06T12:14:16Z),
trigger_at: None,
trailing_amount: None,
trailing_percent: None,
limit_offset: None,
trigger_status: None,
currency: "HKD",
outside_rth: nonce
}
```
The above example has fully demonstrated how to use the SDK to access the OpenAPI interface. For more interfaces, please read the [Longbridge Developers Documentation](https://open.longbridge.com/docs) in detail and use them according to different interfaces.
## More Examples
We provide the complete code of the above examples in the GitHub repository of Longbridge OpenAPI Python SDK, and we will continue to add or update it later.
https://github.com/longbridge/openapi/tree/master/examples
## SDK API Document
For detailed SDK API document, please visit:
https://longbridge.github.io/openapi/
## Contact & Feedback
If there are any questions or suggestions, please feel free to post an issue on GitHub, we will reply as soon as possible.
Or there have a lot old discussion in the GitHub issue, you can search the issue to find the answer.
- GitHub: https://github.com/longbridge/developers/issues
---
# Overview
URL: https://open.longbridge.com/docs.md
Longbridge Developers provides programmatic interfaces for investors with research and development capabilities, enabling them to build trading or market analysis tools based on their own investment strategies. The platform covers the following categories:
- **Quote** — [Real-time and historical quotes](https://longbridge.com/markets), market depth, candlesticks, options/warrants data, subscriptions
- **Fundamental** — Company profiles, financials, valuations, analyst ratings, market data, calendars
- **News & Contents** — [Market news](https://longbridge.com/en/news), [community topics](https://longbridge.com/topics), sharelist management
- **Trade** — Create, amend, and cancel orders; query orders, executions, and assets
- **Account** — Portfolio analysis, price alerts, DCA plans, [watchlist](https://longbridge.com/watchlist)
- **CLI** — Command-line tool covering all of the above, plus quant backtesting and research
- **MCP** — Model Context Protocol integration for AI assistant workflows
## Interface Type
Longbridge provides diversified access methods such as HTTP / WebSockets interfaces for accessing the underlying services and SDK (Python / C++, etc.) encapsulated in the upper layer, allowing flexible choices.
## How to Enable OpenAPI
1. Log in to the [Longbridge App](https://longbridge.com/download) to complete the account opening process;
2. Log in to the [longbridge.com](https://longbridge.com) and enter the developer platform, complete the developer verification (OpenAPI permission application), and obtain a token.
## Quote Coverage
Market
Symbol
HK Market
Securities (including equities, ETFs, Warrants, CBBCs)
Hang Seng Index
US Market
Securities (including stocks, ETFs)
Nasdsaq Index
OPRA Options
CN Market
Securities (including stocks, ETFs)
Index
## Trading
Supported trading functions include:
| Market | Stock and ETF | Warrant & CBBC | Options |
| --------- | ------------- | -------------- | ------- |
| HK Market | ✓ | ✓ | |
| US Market | ✓ | ✓ | ✓ |
## Rate Limit {#rate-limit}
| Category | Limitation |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Quote API | - One account can only create one long link and subscribe to a maximum of 500 symbols at the same time
- No more than 10 calls in a 1-second interval and the number of concurrent requests should not exceed 5
|
| Trade API | - No more than 30 calls in a 30-second interval, and the interval between two calls should not be less than 0.02 seconds
|
:::success
The [OpenAPI SDK](https://open.longbridge.com/sdk) has done effective frequency control internally:
- Quote: The methods under `QuoteContext` will be actively controlled by the SDK according to the server's rate limit. When the request is too fast, the SDK will automatically delay the request. Therefore, you do not need to implement the frequency control details separately.
- Trade: The methods under `TradeContext` are not limited by the SDK. Due to the special nature of the trading order placement scenario, this is left to the user to handle.
:::
## Pricing {#pricing}
Longbridge does not charge any additional fees for activating or using interface services. You only need to [open a Longbridge Integrated A/C](https://longbridge.com/hk/download) and get OpenAPI service permissions to use it for free. See the [Pricing](/pricing) page for details on quote data subscription fees. For actual transaction fees, please contact the brokerage firm where you have opened your securities account.
## Other
The OpenAPI services are provided by Longbridge and the applicable affiliates (subject to the agreement).
openapi-trade.longbridge.com
---
# Longbridge API Non-Commercial Licence Agreement — HK
URL: https://open.longbridge.com/docs/legal/api-license-agreement-hk.md
Whereas,
(1) You have applied to the securities licensed corporation of this Platform (subject to the relevant page guidelines of this Platform, the "Securities Company") to use the Application Programming Interface ("API") service;
(2) In order to provide API service to you, you acknowledge that you consent to be legally bound by this API Code Non-Commercial License Agreement ("Agreement").
This Agreement is entered into by and between this Platform (as defined in the *Longbridge Platform Service Agreement*) ("**we**", "**us**" or "**our**") and **you**, regarding the API which grants you a limited license to use the API Code solely for Non-Commercial Purposes (as defined below). Your download, installation, use or access of the API constitutes your acceptance of and agreement to be bound by the terms of this Agreement.
## 1. Definition and License Grant
**1.1** Definitions
"Affiliate" means, in relation to a party, an individual, corporation, a partnership or any other form of entity directly or indirectly controlling, controlled by or under common control with such party or any of such entities' directors, officers or employees. A person is in "control" of a company, if: (a) it is in accordance with such person's directions or instructions that the directors of the company or of another company of which it is a subsidiary are accustomed to act; or (b) such person, either alone or with any Associate, is entitled to exercise, or control the exercise of, more than 30% of the voting power at general meetings of the company or of another company of which it is a subsidiary.
"API" or "API Code" means the user code and related documents developed by this Platform that is made available to you to develop platforms, tools, or interfaces for your personal use with this Platform's accounts or this Platform's systems;
"Account" means any one or more accounts of any nature, including without limitation the securities accounts, margin accounts and fund accounts, howsoever integrated or separated, from time to time opened and maintained in the name of you with the securities licensed corporation (as may be subject to the notices and the relevant page guidelines of this Platform) under this Platform through which you may obtain services and/or effect transactions, as the same may be re-designated, re-numbered, re-located or otherwise modified from time to time.
**1.2** Subject to the terms of this Agreement, this Platform hereby grants You a personal, revocable, royalty-free, non-exclusive, non-sublicensable, non-transferable, restricted right and license to install, modify and use the API Code solely for Non-Commercial Purposes ("License").
**1.3** "Non-Commercial Purposes" means your License under this Agreement is limited to develop platforms, tools, or interfaces for your personal use. You shall not use the API Code for any application or service for yourself or for anyone else for any commercial purpose, regardless of whether You receive any consideration for such application or service.
**1.4** The License shall only become effective on the date you accept all the terms and contents of this Agreement and when this Agreement becomes effective.
**1.5** The License and the right will terminate automatically:
(1) if you fail to comply with any term(s) of this Agreement;
(2) if you commit an action for right infringement against this Platform;
(3) if you cancel your relevant this Platform's account and Account;
(4) if this Platform sends you the notice of unilateral termination;
(5) if any other circumstances occur in which to protect this Platform's legitimate rights and interests.
**1.6** Upon termination of this Agreement, you shall immediately cease all use of API Code granted hereunder, destroy all copies of API Code completely and shall not retain API Code or the copies of API Code in any form after such destruction.
## 2. Restrictions
**2.1** You acknowledge and agree that you shall only use API Code in compliance with the terms of the Agreement and for Non-Commercial Purposes. Any other uses of API Code are expressly prohibited.
**2.2** This Platform shall own all right, title and interest in and to API Code granted hereunder. You agree not to use, copy, replace, adapt, modify, regenerate, displace, distribute, transmit, broadcast, sell, authorize, publish, lease, sublicense, convert, translate, de-engineer, decompile, disassemble, create derivatives of, or disclose API Code or any part thereof in any way and for any purpose whatsoever to any third party.
**2.3** Unless otherwise authorized by this Platform in writing, you shall not engage in or agree with any third party to engage in the following actions, or provide any assistance to any third party to engage in any matter in violation of this Agreement, including but not limited to:
(1) using API Code to interrupt, damage or limit the use of API Code or other Longbridge software, hardware, platforms, applications, web pages and systems;
(2) engaging in any mining of personal information and data;
(3) bypassing or making unavailable the blocking or restriction of copying behavior in API Code, or interfering with the security-related characteristics of API Code;
(4) moving, replacing, or obscuring of any trademark, copyright, legal, or patent notice of API Code;
(5) using API Code in any software or program that may contain viruses, trojan, software, worms, time bombs, autopilot viruses, or any other computer code or documentation designed to interrupt, damage or limit the API Code or the use in any Longbridge software, hardware, platforms, applications, web pages and systems.
**2.4** You agree and confirm that you will, during the license period, continue to use the License hereunder in accordance with applicable local laws and in accordance with user agreement or service rules as updated by this Platform from time to time.
**2.5** You agree not to use the API Code for any purpose that violates any law or regulation, any right of any person, including but not limited to intellectual property rights, rights of privacy, or rights of personality, or in any manner in violation of this Agreement or the privacy policy.
## 3. Intellectual Property
Except as expressly set forth herein, this Platform shall own all right, title and interest in and to the API and API Code, including but not limited to any code or documentation written by this Platform relating to the API Code, and any intellectual property rights in and to any modifications, replacements, translations or derivatives thereof. This Platform shall, to the extent permitted by law, have all rights and interests in and to the foregoing results.
## 4. Disclaimer of Warranties
**4.1** You expressly acknowledge and agree that the API Code granted hereunder, all provided "as is" and on an "as-available" basis, may contain in whole or in part pre-release, untested, or not fully tested works. The API Code may contain errors that could cause failures or loss of data, and may be incomplete or contain inaccuracies.
**4.2** You understand and agree that the API Code granted hereunder is provided without warranty of any kind, either express or implied, including but not limited to, warranties that the API Code is free of defects, merchantable, non-infringing or fit for a particular purpose. This disclaimer of warranties constitutes an essential part of this License. You hereby agree and accept the foregoing disclaimer and that all risk resulting from Your use of the API Code or applications developed using the API Code is at Your sole and entire risk.
## 5. Warranty and Guarantee
You undertake and shall use all reasonable efforts to indemnify, defend and hold harmless Longbridge, its affiliates and their representatives, directors, employees and agents from and against any claim, action, suit or proceeding, and any loss, liability, damage, cost and expense arising out of:
(1) Your action in connection with the use of API Code;
(2) Your use of API Code to develop relevant applications, or any action that causes legitimate rights and interests of a third party (including copyright, trademark, trade secret, trade dress, patent and other intellectual property rights or other interests);
(3) any action in violation of this Agreement.
## 6. Dispute Resolution
**6.1** The Agreement and all rights, obligations and liabilities of the parties shall be governed by and construed in accordance with the laws of Hong Kong.
**6.2** The courts of Hong Kong have exclusive jurisdiction to settle any dispute arising out of or in connection with the Agreement (including any dispute regarding the existence, validity or termination of the Agreement) (a "Dispute"). The parties agree that the courts of Hong Kong are the most appropriate and convenient courts to settle Disputes and accordingly, no party will argue to the contrary. Notwithstanding the aforesaid, this Platform shall not be prevented from taking proceedings relating to a Dispute in any other courts with jurisdiction. To the extent allowed by applicable regulations, this Platform may take concurrent proceedings in any number of jurisdictions.
## 7. Miscellaneous
**7.1** You agree that if this Platform does not exercise or enforce any legal right or remedy which is contained in this Agreement or is available to this Platform under any applicable law, this will not be taken to be a formal waiver of Longbridge's rights and that those rights or remedies will still be available to Longbridge.
**7.2** This Agreement constitutes the whole legal agreement between you and this Platform and governs your use of the API Code, and completely replaces any prior agreements between you and this Platform in relation to the API Code.
**7.3** You may not assign, transfer, grant or sublicense this Agreement or any rights and authorizations hereunder, while this Platform may assign, transfer, grant or sublicense this Agreement or any rights and authorizations hereunder to its affiliates or other applicable entities without restriction.
**7.4** If you are entering into this Agreement on behalf of your employer or other entity, you represent and warrant that you have full legal authority to bind your employer or such entity to this Agreement.
**7.5** All risks and adverse consequences arising from your violation of this Agreement shall be borne by you.
---
# Longbridge Developers API Non-Commercial Licence Agreement — SG
URL: https://open.longbridge.com/docs/legal/api-license-agreement-sg.md
Whereas,
(1) You intend to use the Longbridge Developers application programming interface ("**API**") services provided by Longbridge AI Technologies Pte. Ltd. ("**Longbridge AI**" or "**Platform**"), which is associated with the entity licensed as a securities brokerage, being Long Bridge Securities Pte. Ltd. (the "**Securities Company**").
(2) In order to provide the API services to you, you acknowledge that you consent to be legally bound by this API Non-Commercial Licence Agreement ("**Agreement**").
This Agreement is between Longbridge AI and you, in relation to your right and licence to use the API Code (as defined below) for Non-Commercial Purposes (as defined below).
By clicking the "**I AGREE**" button, or downloading, installing, using or accessing API, you acknowledge that you consent to be legally bound by this Agreement.
## 1. Definitions and grant of Licence
**1.1** Definitions
"**Affiliate**" means, in relation to a party, an individual, corporation, a partnership or any other form of entity directly or indirectly controlling, controlled by, or under common control with, such party or any of such party's directors, officers or employees. A person is in "control" of a company, if: (a) the company acts in accordance with such person's directions or instructions; or (b) such person, either alone or with any associate, is entitled to exercise, or control the exercise of, more than 30% of the voting power at general meetings of the company;
"**API**" or "**API Code**" means the user code and related documents developed by this Platform that is made available to you to develop platforms, tools, or interfaces for your personal use; and
"**Account**" means any one or more accounts of any nature, including without limitation the securities accounts, margin accounts and fund accounts, howsoever integrated or separated, from time to time opened and maintained in your name with the Securities Company through which you may obtain services and/or effect transactions (as may be re-designated, re-numbered, re-located or otherwise modified from time to time);
"**Non-Commercial Purposes**" means purposes that are solely relating to your personal use.
**1.2** Subject to the terms of this Agreement, this Platform hereby grants you a personal, revocable, royalty-free, non-exclusive, non-sublicensable, non-transferable, restricted right and licence to install, modify and use the API Code solely for Non-Commercial Purposes ("**Licence**"). You shall not use the API Code for any application or service for any commercial purpose, regardless of whether you receive any consideration for such application or service.
**1.3** The Licence shall only become effective on the date you accept all the terms and contents of this Agreement and when this Agreement becomes effective.
**1.4** The Licence and the rights associated with such Licence will terminate automatically in the event:
(1) you fail to comply with any term(s) of this Agreement;
(2) you commit an act constituting the infringement of any right owned by the Platform;
(3) you cancel your relevant account on this Platform and/or your Account;
(4) this Platform sends you a notice of unilateral termination; or
(5) there is the presence of any other circumstances that may adversely affect the Platform's rights and interests.
**1.5** Upon termination of this Agreement, you shall immediately cease all use of the API Code, destroy all copies of the API Code completely, and shall not retain the API Code or the copies of API Code in any form after such destruction.
## 2. Restrictions
**2.1** You acknowledge and agree that you shall only use API Code in compliance with the terms of the Agreement and for Non-Commercial Purposes. Any other uses of API Code are expressly prohibited.
**2.2** This Platform shall own all rights, title and interest in and to the API Code granted hereunder. You agree not to use, copy, replace, adapt, modify, regenerate, displace, distribute, transmit, broadcast, sell, authorize, publish, lease, sublicense, convert, translate, de-engineer, decompile, disassemble, create derivatives of, or disclose the API Code or any part thereof in any way and for any purpose whatsoever to any third party.
**2.3** Unless otherwise authorized by this Platform in writing, you shall not provide any assistance to any third party to engage in any matter which violates this Agreement, or engage in or agree with any third party to engage in the following actions (including but not limited to):
(1) using API Code to interrupt, damage or limit the use of API Code or other software, hardware, platforms, applications, web pages and systems belonging to the Platform;
(2) engaging in any mining of personal information and data;
(3) bypassing or making unavailable the blocking or restriction of copying behavior in API Code, or interfering with the security-related characteristics of API Code;
(4) moving, replacing, or obscuring of any trademark, copyright, legal, or patent notice of API Code;
(5) using API Code in any software or program that may contain viruses, trojan, software, worms, time bombs, autopilot viruses, or any other computer code or documentation designed to interrupt, damage or limit the API Code or its use in any of the Platform's software, hardware, platforms, applications, web pages and systems.
**2.4** You agree and confirm that you will, during the licence period, continue to use the Licence hereunder in accordance with applicable local laws and in accordance with any applicable user agreement or service rules as updated by this Platform from time to time.
**2.5** You agree not to use the API Code for any purpose that violates any law, regulation, or any rights of any person (including but not limited to intellectual property rights and privacy rights).
## 3. Intellectual Property
Except as expressly set forth herein, this Platform shall own all rights, title and interest in and to the API and API Code, including but not limited to any code or documentation written by this Platform relating to the API Code, and any intellectual property rights in and to any modifications, replacements, translations or derivatives thereof.
## 4. Disclaimer of Warranties
**4.1** You expressly acknowledge and agree that the API Code granted hereunder, is provided on an "as-is" and "as-available" basis, and may contain in whole or in part pre-release, untested, or not fully tested work. You acknowledge that the API Code may contain errors that could cause failures or loss of data, and may be incomplete or contain inaccuracies.
**4.2** You understand and agree that the API Code granted hereunder is provided without warranty of any kind, either express or implied, including but not limited to: warranties that the API Code is free of defects, merchantable, non-infringing or fit for a particular purpose. This disclaimer of warranties constitutes an essential part of this Licence. You hereby agree and accept the foregoing disclaimer and that all risk resulting from your use of the API Code or applications developed using the API Code is at your sole risk.
## 5. Warranty and Guarantee
You undertake and shall use all reasonable efforts to indemnify, defend and hold harmless the Platform, its affiliates and their representatives, directors, employees and agents from and against any claim, action, suit or proceeding, and any loss, liability, damage, cost and expense arising out of:
(1) Your actions and/or omissions in connection with your use of API Code;
(2) Your use of API Code to develop relevant applications, or any of your actions that infringes upon any rights and interests of a third party (including copyright, trademark, trade secret, trade dress, patent and other intellectual property rights or other interests); and/or
(3) any action in violation of this Agreement.
## 6. Dispute Resolution
**6.1** The Agreement and all rights, obligations and liabilities of the parties shall be governed by and construed in accordance with the laws of Singapore.
**6.2** The courts of Singapore have exclusive jurisdiction to settle any dispute arising out of or in connection with the Agreement (including any dispute regarding the existence, validity or termination of the Agreement) (a "**Dispute**"). The parties agree that the courts of Singapore are the most appropriate and convenient courts to settle any Dispute. Notwithstanding the aforesaid, the Platform shall not be prevented from settling proceedings relating to a Dispute in any other courts with jurisdiction. To the extent allowed by applicable regulations, this Platform may take concurrent proceedings in any number of jurisdictions.
## 7. Miscellaneous
**7.1** You agree that if the Platform does not exercise or enforce any legal right or remedy which is contained in this Agreement under any applicable law, it will not be taken to be a formal waiver of the Platform's rights and those rights or remedies will still be available to the Platform.
**7.2** This Agreement constitutes the whole legal agreement between you and the Platform governing your use of the API services.
**7.3** You may not assign, transfer, grant or sublicense any rights and authorizations under this Agreement. However, this Platform may assign, transfer, grant or sublicense any rights and authorizations under this Agreement to its affiliates or other applicable entities without restriction.
**7.4** If you are entering into this Agreement on behalf of your employer or a corporate entity, you represent and warrant that you have full legal authority to bind your employer or such entity to this Agreement.
**7.5** All risks and adverse consequences arising from your violation of this Agreement shall be borne by you.
---
# Longbridge Developers Platform Disclaimer — HK
URL: https://open.longbridge.com/docs/legal/developers-platform-disclaimer-hk.md
You have applied to the securities licensed corporation of this Platform (subject to the relevant page guidelines of this Platform, the "Securities Company") to use the Application Programming Interface ("API") service and entrust the Securities Company to trade with recognised exchange companies on your behalf.
By entering into the transaction, you agree to be bound by these terms and conditions:
**1.** This disclaimer is binding to your Account under the terms and conditions. You confirm that you have agreed to be bound by the operation of system and received the terms and conditions including but not limited to the Client Agreement, the term of services provided by the Securities Company, the related risk disclosure statement, any other relevant provisions, the relevant operation, rules and guidelines amended by the Stock Exchange of Hong Kong from time to time and the terms and conditions of the Longbridge trading platform ("Terms and Conditions").
**2.** You confirm that you understand the risk of trading mentioned in the risk disclosure statement under the Terms and Conditions.
**3.** The API access-in methods independently selected by you (including but not limited to self-developed systems, artificial intelligence applications and other technical interfaces, collectively referred to as "API Access-in Methods") and the API which you use is designed, developed or provided by natural persons, legal entities or other organizations ("Technology Provider") which is independent from the Securities Company. The Securities Company has no affiliation with such Technology Provider and makes no express or implied warranties regarding the Technology Provider's service quality, technical performance and security. You hereby irrevocably undertake that the selection of API Access-in Methods and utilization of the API constitute decisions made solely based on your independent judgement. You confirm that you possessed the requisite professional qualifications and operational capabilities to execute such transactions, and fully acknowledge the corresponding market risks, technical risks and operational risks that may consequently arise.
**4.** You hereby irrevocably undertake that you shall bear the full responsibility for the following legal risks and losses, the Securities Company shall not bear any legal liability for including but not limited to:
- a) Any loss arising from inherent defects in the API Access-in Methods selected by you independently and the API used, including trading errors, order delays, or the data discrepancies;
- b) Trading anomalies caused by technical failures of the Technology Provider;
- c) System interruptions resulting from force majeure, cyberattacks, or other causes not attributable to the Securities Company;
- d) Abnormal trading outcomes due to your failure to comply with operational guidelines.
**5.** Although the API is compatible with Longbridge trading application ("Trading Application") as to proceed any trades, the Securities Company shall not be obliged to ensure compatibility between the API and Trading Application. The Securities Company is not liable for any loss or damage suffered as a result of any trading restrictions, obstacles or computing program errors which is caused by different network issues (including but not limited to disconnection, power outage, network congestion or system congestion), communications, trading mode selection, trading time settings, overnight trading, or system settings. The final outcome of every transaction is subject to the account statements provided by the Securities Company.
**6.** You acknowledge and agree that the Securities Company has absolute discretion to decide the scope and content of any services provided through the API. The Securities Company also has the right to terminate such service at any time. The services provided by API is subject to the prevailing service provided by the Securities Company.
**7.** You are responsible for sufficient protection of the personal account number, account password, transaction-related password and all other account security-related information and keeping your personal account secured from unauthorized use. You acknowledge and understand that you are the only user of your Account, Trading Application account, API and all relevant passwords and you are responsible for any instruction(s) or transaction(s) through the above-said account, API and all relevant passwords in any circumstances whatsoever.
**8.** Regardless of the API Access-in Methods, you are responsible for all transaction instructions. You hereby confirm that each instruction genuinely reflects your trading intent, and the instruction generation process shall always remain under effective manual control. You may not claim that any instruction does not represent your true intention on grounds including but not limited to technical complexity, operational indirectness or system opacity ("black box" nature).
**9.** You understand that any content and information such as market changes or real-time information obtained or provided by the API services shall not constitute an offer or solicitation to enter into any transaction. The Securities Company or the third party data provider provides the information on an "as is" and "as available" basis and is for general information only. You agree that while the Securities Company endeavours to ensure the accuracy and reliability of such information, the Securities Company does not warrant the accuracy, reliability, timeliness, completeness or correct sequencing of any such information and the Securities Company will not bear any liability for any loss arising from any inaccuracy, omission or incompleteness of the information or any reliance on such information. The Securities Company and the third party data provider will not be liable for any loss or damage resulting, directly or indirectly, from any error, delay or omission of information resulting from force majeure or other causes beyond the Securities Company's reasonable control.
**10.** You understand that trading through the API may be different from trading through Longbridge trading platform. If you trade through the API, you agree to bear the risks of using the API such as encountering possible malfunction of hardware or software. Your instruction(s) may not be executed due to the malfunction of the system.
**11.** You are aware of the types of trading instruction(s), trading functions and the operation and risks of the trading process provided by the API. You have to understand the operational mechanisms and the risks involved in such trading before using API. You shall be responsible for any possible compliance and regulatory matters arising from the consequence or during the process of using the API.
**12.** The use of the API / service is at your own risk while such service provided to you is without warranty of any kind, whether express or implied. The Securities Company does not guarantee the API services will operate/function without any interruption, failures or malfunctions. The Securities Company is not responsible for the outcome/consequence of the transaction by using the API service. You are solely responsible for any and all losses (including but not limited to, unlimited, special, incidental, consequential or punitive), directly or indirectly, from the use of or inability to use the services of the API.
**13.** You agree to be bound by the trading rules provided by the Securities Company which govern the use of API from time to time. The extent of rules includes but not limited to the frequency of login/logout per minute, the frequency of placing orders and cancellations of orders, server usage limits, trading period and mechanisms. The Securities Company reserves the right to restrict or modify the use of an API according to the usage, risk management or other considerations. If there is any improper use of the API service, the Securities Company may restrict, cancel or terminate your access and connection to the API at any time without prior notice.
**14.** The Securities Company absolutely prohibit you from engaging in any form of market manipulation or any suspicious activities with respect to any transaction. Subject to applicable laws and regulations, the Securities Company may, in its absolute discretion, take actions on any account(s) that is suspected of market manipulation or any suspicious activities including but not limited to investigate and review your profile, freeze or terminate the account(s) involved, approval before any instruction(s) took place and make any other necessary alterations or adjustments without prior notice. The Securities Company may, in its absolute discretion, report such those activities to any relevant regulatory and law enforcement authority where necessary.
**15.** You acknowledge that you read and fully understand the terms and conditions set out above and agree to be bound by them. The Securities Company reserves the right to vary, amend, delete or replace any of the terms and conditions contained in these Terms and Conditions at any time.
**16.** You acknowledge and agree that the Securities Company reserves the right to adjust the services abovementioned at any time without prior notice.
---
# Longbridge Developers Platform Disclaimer — SG
URL: https://open.longbridge.com/docs/legal/developers-platform-disclaimer-sg.md
You intend to use the Longbridge Developers application programming interface ("**API**") services provided by Longbridge AI Technologies Pte. Ltd. ("**Longbridge AI**"), which is associated with the trading platform provided by the entity licensed as a securities brokerage, being Long Bridge Securities Pte. Ltd. (the "**Securities Company**").
By entering into the transaction, you agree to be bound by these terms and conditions:
**1.** This disclaimer is binding with respect to your client account under the relevant terms and conditions. You confirm that you have agreed to be bound by the terms and conditions including but not limited to the customer agreement and term of services provided by the Securities Company, the related risk disclosure statements, any other relevant provisions, rules and guidelines amended by the Singapore Exchange from time to time and the terms and conditions associated with the Longbridge trading platform ("**Terms and Conditions**").
**2.** You confirm that you understand the risk of trading mentioned in the risk disclosure statement under the Terms and Conditions.
**3.** The API access-in methods independently selected by you, including but not limited to self-developed systems, artificial intelligence applications and other technical interfaces (collectively referred to as "**API Access-in Methods**"), and the API which you use is designed, developed or provided by Longbridge AI or such other relevant legal entities ("**Technology Provider**"), which is independent from the Securities Company. The Securities Company makes no express or implied warranties regarding the Technology Provider's service quality, technical performance and security. You hereby irrevocably undertake that the selection of API Access-in Methods and utilization of the API constitute decisions made solely based on your independent judgment. You confirm that you possess the requisite professional qualifications and operational capabilities to execute such transactions, and fully acknowledge the corresponding market risks, technical risks and operational risks that may consequently arise.
**4.** You hereby irrevocably undertake that you shall bear the full responsibility for the following legal risks and losses, and neither the Technology Provider nor the Securities Company shall bear any legal liability for the following, including but not limited to:
- a) Any loss arising from inherent defects in the API Access-in Methods selected by you independently and the API used, including trading errors, order delays, or data discrepancies;
- b) Trading anomalies caused by technical failures of the Technology Provider;
- c) System interruptions resulting from force majeure, cyberattacks, or other causes not attributable to the Securities Company; or
- d) Abnormal trading outcomes due to your failure to comply with operational guidelines.
**5.** Although the API is compatible with the Longbridge trading application ("**Trading Application**") to proceed any trades, the Securities Company shall not be obliged to ensure compatibility between the API and Trading Application. The Securities Company is not liable for any loss or damage suffered as a result of any trading restrictions, obstacles or computing program errors which is caused by different network issues (including but not limited to disconnection, power outage, network congestion or system congestion), communications, trading mode selection, trading time settings, overnight trading, or system settings. The final outcome of every transaction is subject to the account statements provided by the Securities Company.
**6.** You acknowledge and agree that the Securities Company has absolute discretion to decide the scope and content of any services provided through the API. The Securities Company also has the right to terminate such service at any time. The services provided by API is subject to the prevailing terms of service provided by the Securities Company.
**7.** You are responsible for ensuring the protection of your personal account number, account passwords, transaction-related passwords and all other account security-related information. You are also responsible for keeping your personal account secured from unauthorized use. You acknowledge and understand that you are the only user of your client account, Trading Application account, API and all relevant passwords, and you are responsible for any instruction(s) or transaction(s) through the above-said accounts and/or use of the API.
**8.** Regardless of the API Access-in Methods, you are responsible for all transaction instructions. You hereby confirm that each instruction genuinely reflects your trading intent, and the instruction generation process shall always remain under your effective manual control. You may not claim that any instruction does not represent your true intention on grounds including but not limited to technical complexity, operational indirectness or system opacity.
**9.** You understand that any content and information such as market changes or real-time information obtained or provided by the API services shall not constitute an offer or solicitation to enter into any transaction. The Securities Company or the third party data provider provides the information on an "as is" and "as available" basis and is for general information only. You agree that while the Securities Company endeavours to ensure the accuracy and reliability of such information, the Securities Company does not warrant the accuracy, reliability, timeliness, completeness or correct sequencing of any such information and the Securities Company will not bear any liability for any loss arising from any inaccuracy, omission or incompleteness of the information or any reliance on such information. The Securities Company and any third party data provider will not be liable for any loss or damage resulting, directly or indirectly, from any error, delay or omission of information resulting from force majeure or other causes beyond the Securities Company's reasonable control.
**10.** You understand that trading through the API may be different from trading through the Trading Application. If you trade through the API, you agree to bear the risks of using the API such as encountering possible malfunction of hardware or software. Your instruction(s) may not be executed due to the malfunction of the system.
**11.** You are aware of the types of trading instruction(s), trading functions and the operation and risks of the trading process provided by the API. You have to understand the operational mechanisms and the risks involved in such trading before using API. You shall be responsible for any possible compliance and regulatory matters arising from the consequence or during the process of using the API.
**12.** The use of the API services is at your own risk and such services provided to you are without warranty of any kind, whether express or implied. The Securities Company does not guarantee the API services will operate/function without any interruption, failures or malfunctions. The Securities Company is not responsible for the outcome/consequence of the transaction by using the API service. You are solely responsible for any and all losses (including but not limited to, unlimited, special, incidental, consequential or punitive), directly or indirectly, from the use of or inability to use the services of the API.
**13.** You agree to be bound by the trading rules provided by the Securities Company which govern the use of the API from time to time. The extent of rules includes but is not limited to the frequency of login/logout per minute, the frequency of placing orders and cancellations of orders, server usage limits, trading period and mechanisms. The Securities Company reserves the right to restrict or modify the use of an API according to the usage, risk management or other considerations. If there is any improper use of the API service, the Technology Provider and/or the Securities Company may restrict, cancel or terminate your access and connection to the API at any time without prior notice.
**14.** The Securities Company absolutely prohibits you from engaging in any form of market manipulation or any suspicious activities with respect to any transaction. Subject to applicable laws and regulations, the Securities Company may, in its absolute discretion, take action on any account(s) that is suspected of market manipulation or any suspicious activities, including but not limited to investigating and reviewing your profile, freezing or terminating the account(s) involved, having to provide approval before any instruction(s) take place, and making any other necessary alterations or adjustments without prior notice. The Securities Company may, in its absolute discretion, report such activities to any relevant regulatory and law enforcement authorities where necessary.
**15.** You acknowledge that you have read and fully understand the terms and conditions set out above and agree to be bound by them. The Technology Provider and/or Securities Company reserves the right to vary, amend, delete or replace any of the terms and conditions contained in these Terms and Conditions at any time.
**16.** You acknowledge and agree that the Technology Provider and/or the Securities Company reserve the right to adjust the services abovementioned at any time without prior notice.
---
# Legal
URL: https://open.longbridge.com/docs/legal.md
# Legal
Legal agreements and disclaimers for Longbridge Developers. Documents are provided separately for each operating region — please refer to the version applicable to your account.
## Singapore (SG)
- [User Data Authorisation and Acknowledgement](/docs/legal/user-data-authorization-sg)
- [Developers Platform Disclaimer](/docs/legal/developers-platform-disclaimer-sg)
- [API Non-Commercial Licence Agreement](/docs/legal/api-license-agreement-sg)
## Hong Kong (HK)
- [User Data Authorisation and Acknowledgement](/docs/legal/user-data-authorization-hk)
- [Developers Platform Disclaimer](/docs/legal/developers-platform-disclaimer-hk)
- [API Non-Commercial Licence Agreement](/docs/legal/api-license-agreement-hk)
---
# User Data Authorisation and Acknowledgement — HK
URL: https://open.longbridge.com/docs/legal/user-data-authorization-hk.md
Please read this Authorisation carefully before proceeding. **By completing and submitting this Authorisation, you acknowldge and confirm that you have read, understood, and agree to be bound by all terms set out below in connection with the Longbridge Developers.**
**1. Background**
Longbridge AI Technologies Limited and its relevant affiliates (collectivly, "**Longbridge**") provides programmatic interfaces through which market data, account functionalities, and related services are encapsulated and made available to users in the form of Command-Line Interface tools, Model Context Protocol integrations, and other developer tools and services (collectively, "**Longbridge Developers**").
Users may access and invoke the relevant interfaces based on their own needs and integrate them with third-party AI terminals or applications selected by the users (including, without limitation, OpenClaw, Claude Code, Cursor, and similar tools). Upon installation and successful connection, users may interact with the Longbridge Platform and/or their platform or securities accounts (where applicable) through such third-party terminals or applications.
This Authorisation governs: (a) the sharing of your selected account data among the relevant Longbridge group entities and with relevant third-party AI terminal operators as you selected ("**Third-Party AI Terminals**"); and (b) the terms on which instructions you issue through Third-Party AI Terminals are treated as your own instructions for the purpose of executing securities transactions.
**2. Data Sharing Authorisation and Purpose of Sharing**
**2.1 Authorised Data Scope**
The categories of data covered by this Authorisation are displayed below and/or under "Quotes Permission" section on the OAuth authorisation page, and are subject to your selection. Unless otherwise specified, data related to securities trading will generally be shared by Long Bridge HK Limited ("**Longbridge Securities**"), while other data will be shared by Longbridge Platform (as defined in the terms and conditions of Longbridge Platform). The data categories authorised by you will be shared by Longbridge with Third-Party AI Terminals solely for the purpose of enabling the function of the Longbridge Developers described herein.
The data categories that may be available are organized into the following capability groups, with access granted on a feature-by-feature basis depending on the functionality selected on the relevant page. The specific set of available tools and their read / create / update / delete permissions may be added, adjusted or retired from time to time as Longbridge Developers evolves; the latest inventory is as published at [https://open.longbridge.com/docs/mcp](https://open.longbridge.com/docs/mcp) and on the OAuth authorization page:
1. **Real-time Market Data** --- Real-time market quotes and order-book data across markets.
2. **Fundamentals & Research** --- Company fundamentals and research data.
3. **Derivatives** --- Data relating to options, warrants and other derivatives.
4. **Account & Portfolio** --- Access to account, cash and position data, and the maintenance of portfolio constructs such as watchlists.
5. **Trading** --- Securities trade execution and the management of the order lifecycle.
6. **Automation** --- Management of automated tasks triggered by conditions you have pre-set.
The specific functionality, coverage and read / write permissions within the categories above may be adjusted or expanded from time to time. Any newly added data capability category will be presented as a separately selectable item on the OAuth authorization page before being shared with any Third-Party AI Terminal, and the corresponding data will only be shared after you have actively selected it and completed the authorization.
**2.2 Further Sharing with Third-Party AI Terminals**
By granting authorization hereunder, you acknowledge and agree that the authorisation you hereby grant to Longbridge may, to the extent necessary to fulfil the purposes of Longbridge Developers, be further shared with Third-Party Terminals.
**2.3 Purpose of Sharing**
The data shared pursuant to your selections above will be used exclusively to enable the functionality of the Longbridge Developers. No data will be shared for any other purpose without your separate consent.
**2.4 Data Protection and Compliance**
All data collection, storage, and processing activities are conducted in accordance with the Personal Data (Privacy) Ordinance ("**PDPO**") and other applicable data protection regulations. Longbridge will only retain your data for as long as is necessary to fulfil the purposes set out in this Authorisation, or as required by applicable law. You have the right to withdraw your consent, access your data, and request correction of inaccurate data, in each case in accordance with the PDPO. You may withdraw this Authorisation at any time by updating your settings within the Longbridge platform. Withdrawal will take effect prospectively and will not affect instructions already submitted or executed prior to the effective date of withdrawal.
**3. Instructions Transmitted via Third-Party AI Terminals**
**3.1 Nature and Effect of Instructions via Third-Party AI Terminals(when applicable)**
You acknowledge and agree that when you issue instructions through Third-Party AI Terminals, which instructions shall be transmitted to and executed by Longbridge Securities:
Longbridge acts solely as the developer of the Longbridge Developers. Longbridge and Longbridge Securities do not control, review, endorse, or assume any responsibility or liability for the content, instructions, recommendations, or outputs generated by any Third-Party AI Terminal, including any trading decisions or outcomes arising therefrom. The Third-Party AI Terminal with which you interact is the responsible party for the AI services provided to you and you remain solely responsible for independently evaluating and verifying any information or recommendations provided by Third-Party AI Terminal before taking any action.
The Third-Party AI Terminal transmits instructions on your behalf to Longbridge Securities for execution, but does not itself initiate, modify, interpret, or exercise any discretion over any instruction. Each instruction transmitted via Third-Party AI Terminal must be initiated by you through an explicit and deliberate user action. No instruction will be automatically generated, triggered, or executed without your input and confirmation.
No Third-Party AI Terminal has constituted/ currently constitutes /will constitute an agent, representative, investment adviser, or decision-making entity of any Longbridge group entity or of you personally.
Longbridge Securities executes instructions strictly in accordance with your authorisation, on an execution-only basis, without providing investment advice or exercising discretion.
**By granting this Authorisation, you expressly permit the Third-Party AI Terminal you deploy to submit order instructions to Longbridge Securities on your behalf. Such instructions, once confirmed and transmitted, shall be treated as your own instructions to Longbridge Securities and shall be binding upon execution. Each instruction originates from, and is solely attributable to, you as the account holder. You agree that Longbridge Securities is entitled to act on such instructions without further verification of your identity beyond the authentication carried out at login.**
**4. Risk Acknowledgement**
You acknowledge and accept the following risks:
The value of investments may rise or fall and past performance is not indicative of future results.
Instructions transmitted via Third-Party AI Terminal on behalf of you to Longbridge are binding upon execution. Longbridge shall not be liable for any losses arising from instructions that you authorise, including instructions transmitted through any Third-Party AI Terminal.
You are solely responsible for reviewing and verifying the accuracy of all instructions before they are submitted, regardless of the interface used.
Third-Party AI Terminal may make errors in understanding or transmitting instructions. You should always confirm the details of any instruction before authorising it.
Third-Party AI Terminal, as the entities responsible for AI terminal services, are obligated to comply with the PDPO and all other applicable Hong Kong laws in connection with the collection and processing of your data. You acknowledge that Longbridge does not control Third-Party AI Terminal's data practices and that you should review the privacy policies of any third-party AI terminal before use.
**5.** **Risk Warning --- Connecting Your Securities Account**
Linking your brokerage or securities account to Third-Party Terminal grants the AI the ability to access account data and, depending on permissions, to place, modify, or cancel orders on your behalf. **This may result in partial or total loss of your assets.** By enabling this connection, you acknowledge and accept the following risks:
**AI errors.** Third-Party Terminal may misinterpret instructions, hallucinate data, select the wrong ticker, quantity, price, or order side, or execute trades that do not match your intent.
**Prompt injection attacks.** Malicious content hidden in emails, documents, websites, files, or other data sources may hijack the AI into executing unauthorized trades or transferring assets without your knowledge.
**Rogue or compromised Third-Party Terminal servers.** Third-Party Terminal servers may not be audited. A malicious or breached server may intercept credentials, manipulate market data, or trigger unauthorized actions.
**Scope creep in multi‑step workflows.** Agentic AI may take broader actions than you intended when chaining tools, documents, or accounts.
**Credential and session risks.** API keys, OAuth tokens, or session credentials used to authenticate the MCP connection may be leaked, reused, or abused.
**Market risk amplified by automation.** Even technically correct orders may incur losses due to slippage, volatility, or timing, and errors may be executed faster than you can intervene.
**Limited audit trail.** AI agent actions may not be fully captured by your broker's or employer's standard monitoring systems, making detection and recovery of unauthorized trades difficult.
**Legal and regulatory exposure.** Trades executed by an AI agent on your account are generally treated as *your* trades. You remain fully responsible for all resulting losses, taxes, margin calls, and regulatory consequences.
**6. General Terms**
This Authorisation is governed by, and construed in accordance with, the laws of Hong Kong. Any dispute arising out of or in connection with this Authorisation shall be subject to the exclusive jurisdiction of the Hong Kong courts.
This Authorisation supplements, but does not replace, the terms and conditions of Longbridge Platform, service rules including the Privacy Policy and other relevant terms or agreements. Please read carefully and thoroughly understand the foregoing documents and the contents of this Authorisation so as to make an informed authorization.
Longbridge reserves the right to amend this Authorisation form from time to time. Material changes will be notified to you in advance and, where required by applicable law, will require your re-confirmation.
If any provision of this Authorisation is found to be invalid or unenforceable, the remaining provisions shall continue in full force and effect.
---
# User Data Authorisation and Acknowledgement — SG
URL: https://open.longbridge.com/docs/legal/user-data-authorization-sg.md
Please read this Authorisation carefully before proceeding. **By completing and submitting this Authorisation, you acknowledge and confirm that you have read, understood, and agree to be bound by all terms set out below in connection with the Longbridge Developers.**
**1. Background**
Longbridge AI Technology Pte. Ltd. and its affiliates (collectively, "**Longbridge**") provide programmatic interfaces through which market data, account functionalities, and related services are encapsulated and made available to users in the form of Command-Line Interface tools, Model Context Protocol integrations, and other developer tools and services (collectively, "**Longbridge Developers**").
You may access and invoke the relevant interfaces based on your own needs and integrate them with third-party AI terminals or applications you select (including, without limitation, OpenClaw, Claude Code, Cursor, and similar tools) ("**Third-Party AI Terminals**"). Upon installation and successful connection, users may interact with the Longbridge Platform and/or their platform or securities accounts (where applicable) through such third-party terminals or applications.
This Authorisation governs: (a) the sharing of your selected account data among the relevant Longbridge group entities and with relevant Third-Party AI Terminals ; and (b) the terms on which instructions you issue through Third-Party AI Terminals are treated as your own instructions for the purpose of executing securities transactions.
**2. Data Sharing Authorisation and Purpose of Sharing**
**2.1 Authorised Data Scope**
The categories of data covered by this Authorisation are displayed below and/or under "Quotes Permission" section on the OAuth authorisation page, and are subject to your selection. Unless otherwise specified, data related to securities trading will generally be shared by Long Bridge Securities Pte. Ltd. ("**Longbridge Securities**"), while other data will be shared by Longbridge Platform (as defined in the Longbridge Platform Terms and Conditions), to Longbridge.
The data categories that may be available are organized into the following capability groups, with access granted on a feature-by-feature basis depending on the functionality selected on the relevant page. The specific set of available tools and their read / create / update / delete permissions may be added, adjusted or retired from time to time as Longbridge Developers evolves; the latest inventory is as published at [https://open.longbridge.com/docs/mcp](https://open.longbridge.com/docs/mcp) and on the OAuth authorization page:
1. **Real-time Market Data** --- Real-time market quotes and order-book data across markets.
2. **Fundamentals & Research** --- Company fundamentals and research data.
3. **Derivatives** --- Data relating to options, warrants and other derivatives.
4. **Account & Portfolio** --- Access to account, cash and position data, and the maintenance of portfolio constructs such as watchlists.
5. **Trading** --- Securities trade execution and the management of the order lifecycle.
6. **Automation** --- Management of automated tasks triggered by conditions you have pre-set.
The specific functionality, coverage and read / write permissions within the categories above may be adjusted or expanded from time to time. Any newly added data capability category will be presented as a separately selectable item on the OAuth authorization page before being shared with any Third-Party AI Terminal, and the corresponding data will only be shared after you have actively selected it and completed the authorization.
**2.2 Further Sharing with Third-Party AI Terminals**
By granting authorisation hereunder, you acknowledge and agree that the authorisation you hereby grant to Longbridge may, to the extent necessary to fulfil the purposes of Longbridge Developers and strictly in accordance with the PDPA, be further shared with Third-Party AI Terminals that you deploy. Each such Third-Party AI Terminals shall be responsible for the AI services they provide to you, and shall be independently responsible for their compliance with applicable laws and regulations, including the PDPA.
You acknowledge that Longbridge does not control Third-Party AI Terminals' data practices and that you should review the privacy policies of any Third-Party AI Terminals before use.
**2.3 Purpose of Sharing**
The data shared pursuant to your selections above will be used exclusively to enable the functionality of the Longbridge Developer. No data will be shared for any other purpose without your separate consent.
**2.4 Data Protection, Access Control and Compliance**
All data collection, storage, and processing activities are conducted in accordance with the Personal Data Protection Act 2012 of Singapore ("**PDPA**") and other applicable data protection regulations. Longbridge will only retain your data for as long as is necessary to fulfil the purposes set out in this Authorisation, or as required by applicable laws. You have the right to withdraw your consent, access your data, and request correction of inaccurate data, in each case in accordance with the PDPA. You may withdraw this Authorisation at any time by updating your settings within the Longbridge platform. Withdrawal will take effect prospectively and will not affect instructions already submitted or executed prior to the effective date of withdrawal. You may revoke or disconnect Third-Party AI Terminal access at any time through the platform settings or other designated methods made available by Longbridge. Certain access or functionality may be suspended, restricted, or terminated where reasonably necessary for security, system protection, operational, compliance, or risk management purposes.
**3. Nature and Effect of Instructions via Third-Party AI Terminals(when applicable)**
You acknowledge and agree that when you issue instructions through Third-Party AI Terminals, which instructions shall be transmitted to and executed by Longbridge Securities:
Longbridge acts solely as the developer of the Longbridge Developers. Longbridge does not control, review, endorse, or assume any responsibility or liability for the content, instructions, recommendations, or outputs generated by any Third-Party AI Terminal, including any trading decisions or outcomes arising therefrom. The Third-Party AI Terminal you selectis the responsible party for the AI services provided to you and you remain solely responsible for independently evaluating and verifying any information or recommendations provided by Third-Party AI Terminal before taking any action.
The Third-Party AI Terminal transmits instructions on your behalf to Longbridge Securities for execution, but does not itself initiate, modify, interpret, or exercise any discretion over any instruction. Each instruction transmitted via Third-Party AI Terminal must be initiated by you through an explicit and deliberate user action. No instruction will be automatically generated, triggered, or executed without your input and confirmation.
No Third-Party AI Terminal has constituted/ currently constitutes /will constitute an agent, representative, investment adviser, or decision-making entity of any Longbridge group entity or of you personally.
Securities services and brokerage functions referred to in this Authorisation are provided by Longbridge Securities, a capital markets services licence holder regulated by the Monetary Authority of Singapore.
Longbridge Securities executes instructions strictly in accordance with your authorisation, on an execution-only basis, without providing investment advice or exercising discretion.
**By granting this Authorisation, you expressly permit the Third-Party AI Terminal you select to submit trading instructions to Longbridge Securities on your behalf. Such instructions, once confirmed and transmitted, shall be treated as your own instructions to Longbridge Securities and shall be binding upon execution. Each instruction originates from, and is solely attributable to, you as the account holder. You agree that Longbridge Securities is entitled to act on such instructions without further verification of your identity beyond the authentication carried out at login.**
**4. Risk Acknowledgement**
You acknowledge and accept the following risks:
The value of investments may rise or fall and past performance is not indicative of future results.
Instructions transmitted via Third-Party AI Terminal on behalf of you to Longbridge are binding upon execution. Longbridge shall not be liable for any losses arising from instructions that you authorise, including instructions transmitted through any Third-Party AI Terminal.
You are solely responsible for reviewing and verifying the accuracy of all instructions before they are submitted, regardless of the interface used.
Third-Party AI Terminal may make errors in understanding or transmitting instructions. You should always confirm the details of any instruction before authorising it.
Third-Party Terminals, as the entities responsible for AI terminal services, are obligated to comply with the PDPA and all other applicable Singapore laws in connection with the collection and processing of your data. You acknowledge that Longbridge does not control Third-Party Terminals' data practices and that you should review the privacy policies of any third-party AI terminal before use.
**5. General Terms**
This Authorisation is governed by, and construed in accordance with, the laws of Singapore. Any dispute arising out of or in connection with this Authorisation shall be subject to the exclusive jurisdiction of the Singapore courts.
This Authorisation supplements, but does not replace, the [Longbridge Platform Terms and Conditions](https://support.longbridge.sg/topics/us-trade/user-agreement?locale=en) , the [Privacy Policy](https://support.longbridge.sg/topics/Other/privacy-policy?locale=en) and other relevant terms or agreements. Please read carefully and understand thoroughly the foregoing documents and the contents of this Statement so as to make an informed authorization.
Longbridge reserves the right to amend this Authorisation form from time to time. Material changes will be notified to you in advance and, where required by applicable law, will require your re-confirmation.
If any provision of this Authorisation is found to be invalid or unenforceable, the remaining provisions shall continue in full force and effect.
---
# LLMs Components
URL: https://open.longbridge.com/docs/llm.md
# LLMs Components
We provide several components for LLMs (Large Language Models) that allow you to easily access and analyze financial data, [real-time market data](https://longbridge.com/markets), and even enable AI to place orders.
Yes, you can use our LLM components through the Longbridge Developers. Start today!
## LLMs Text
The OpenAPI documentation follows the [LLMs Text](https://llmstxt.org/) standard, providing [llms.txt](https://open.longbridge.com/llms.txt) and Markdown files for each document. Based on this LLMs Text, you can provide AI with a complete dictionary of Longbridge Developers documentation as a reference for AI-assisted development, enabling AI to generate more accurate code.
- [https://open.longbridge.com/llms.txt](https://open.longbridge.com/llms.txt) - Approximately 2104 tokens.
Each of our documents is also available in Markdown format. When accessing them, simply add the `.md` suffix to the URL.
For example:
-
-
## Longbridge.com Markdown Access (AI-friendly)
In addition to OpenAPI docs, pages on [https://longbridge.com](https://longbridge.com) are also AI-friendly for markdown retrieval.
You can get markdown content in either way:
1. Add `.md` suffix to page URL
2. Send request header: `Accept: text/markdown`
Examples:
- [https://longbridge.com/en/topics.md](https://longbridge.com/en/topics.md)
- `curl -H "Accept: text/markdown" https://longbridge.com/quote/TSLA.US`
This is useful for LLM crawlers, RAG indexing, and tool-based content ingestion while keeping page structure clean.
### Demo
### Using in Cursor
Open Cursor, open the command palette (`Command + Shift + P`), search for and select **Add New Custom Docs** and enter the Longbridge Developers LLMs Text address in the dialog box:
```
https://open.longbridge.com/llms.txt
```
Once added successfully, the Cursor Settings will look like this:
Next, in an AI conversation, you can select the Docs you just added under the `docs` menu of **@Add Context**. This allows the AI to use these documents as context in subsequent conversations.
---
# Dividend Calendar
URL: https://open.longbridge.com/docs/market/calendar/dividend-calendar.md
Get upcoming and past dividend events including ex-date, pay date, and dividend amount.
longbridge finance-calendar dividend
longbridge finance-calendar dividend --filter positions
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| start | string | YES | Start date, YYYY-MM-DD |
| end | string | YES | End date, YYYY-MM-DD |
| market | string | NO | Market filter: `US`, `HK`, `SH`, `SZ`. Omit for all. |
| count | integer | NO | Max events per page; server default when omitted |
| offset | integer | NO | Number of events to skip from the start of the window |
| next | CalendarPageDirection | NO | Page direction from the `next_date` cursor: `Later` or `Earlier` |
## Request Example
```python
from longbridge.openapi import CalendarContext, CalendarCategory, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = CalendarContext(config)
resp = ctx.finance_calendar(CalendarCategory.Dividend, "2024-01-01", "2024-03-31")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncCalendarContext, CalendarCategory, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncCalendarContext.create(config)
resp = await ctx.finance_calendar(CalendarCategory.Dividend, "2024-01-01", "2024-03-31")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, CalendarContext, CalendarCategory, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = CalendarContext.new(config)
const resp = await ctx.financeCalendar(CalendarCategory.Dividend, '2024-01-01', '2024-03-31')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.calendar.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
CalendarContext ctx = CalendarContext.create(config)) {
var resp = ctx.financeCalendar(CalendarCategory.Dividend, "2024-01-01", "2024-03-31", null).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, calendar::{CalendarContext, CalendarCategory}, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = CalendarContext::new(config);
let resp = ctx.finance_calendar(CalendarCategory::Dividend, "2024-01-01", "2024-03-31", None, None, None, None).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::calendar;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
CalendarContext ctx = CalendarContext::create(config);
ctx.finance_calendar(CalendarCategory::Dividend, "2024-01-01", "2024-03-31", "", std::nullopt, std::nullopt, std::nullopt, [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/calendar"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := calendar.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.FinanceCalendar(context.Background(), "Dividend", "2024-01-01", "2024-03-31", nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"date": "2024-01-01",
"list": [
{
"date": "2024-01-15",
"count": 1,
"infos": [
{
"id": "12345",
"symbol": "AAPL.US",
"market": "US",
"counter_name": "Apple Inc.",
"event_type": "",
"activity_type": "",
"date": "2024-01-15",
"datetime": "",
"content": "",
"star": 0,
"currency": "",
"icon": "",
"chart_uid": "",
"date_type": "",
"financial_market_time": "",
"data_kv": []
}
]
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [CalendarEventsResponse](#CalendarEventsResponse) |
| 400 | Bad request | None |
## Schemas
### CalendarEventsResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| date | string | false | Response date |
| list | object[] | true | List of calendar date groups, see [CalendarDateGroup](#CalendarDateGroup) |
### CalendarDateGroup
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| date | string | true | Date |
| count | integer | false | Number of events on this date |
| infos | object[] | true | List of calendar events, see [CalendarEventInfo](#CalendarEventInfo) |
### CalendarEventInfo
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | string | false | Event ID |
| symbol | string | false | Security symbol |
| market | string | false | Market |
| counter_name | string | false | Security name |
| event_type | string | false | Event type |
| activity_type | string | false | Activity type |
| date | string | false | Event date |
| datetime | string | false | Event datetime |
| date_type | string | false | Date type |
| content | string | false | Event content description |
| currency | string | false | Currency |
| star | integer | false | Importance rating (1-3) |
| icon | string | false | Icon URL |
| chart_uid | string | false | Chart identifier |
| financial_market_time | string | false | Financial market time |
| data_kv | object[] | false | Key-value data pairs |
---
# Earnings Calendar
URL: https://open.longbridge.com/docs/market/calendar/earnings-calendar.md
Browse upcoming earnings reports and recent results, with EPS and revenue estimates.
longbridge finance-calendar report
longbridge finance-calendar report --market US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| start | string | YES | Start date, YYYY-MM-DD |
| end | string | YES | End date, YYYY-MM-DD |
| market | string | NO | Market filter: `US`, `HK`, `SH`, `SZ`. Omit for all. |
| count | integer | NO | Max events per page; server default when omitted |
| offset | integer | NO | Number of events to skip from the start of the window |
| next | CalendarPageDirection | NO | Page direction from the `next_date` cursor: `Later` or `Earlier` |
## Request Example
```python
from longbridge.openapi import CalendarContext, CalendarCategory, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = CalendarContext(config)
resp = ctx.finance_calendar(CalendarCategory.Report, "2024-01-01", "2024-03-31")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncCalendarContext, CalendarCategory, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncCalendarContext.create(config)
resp = await ctx.finance_calendar(CalendarCategory.Report, "2024-01-01", "2024-03-31")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, CalendarContext, CalendarCategory, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = CalendarContext.new(config)
const resp = await ctx.financeCalendar(CalendarCategory.Report, '2024-01-01', '2024-03-31')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.calendar.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
CalendarContext ctx = CalendarContext.create(config)) {
var resp = ctx.financeCalendar(CalendarCategory.Report, "2024-01-01", "2024-03-31", null).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, calendar::{CalendarContext, CalendarCategory}, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = CalendarContext::new(config);
let resp = ctx.finance_calendar(CalendarCategory::Report, "2024-01-01", "2024-03-31", None, None, None, None).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::calendar;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
CalendarContext ctx = CalendarContext::create(config);
ctx.finance_calendar(CalendarCategory::Report, "2024-01-01", "2024-03-31", "", std::nullopt, std::nullopt, std::nullopt, [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/calendar"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := calendar.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.FinanceCalendar(context.Background(), "Report", "2024-01-01", "2024-03-31", nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"date": "2024-01-01",
"list": [
{
"date": "2024-01-15",
"count": 1,
"infos": [
{
"id": "12345",
"symbol": "AAPL.US",
"market": "US",
"counter_name": "Apple Inc.",
"event_type": "",
"activity_type": "",
"date": "2024-01-15",
"datetime": "",
"content": "",
"star": 0,
"currency": "",
"icon": "",
"chart_uid": "",
"date_type": "",
"financial_market_time": "",
"data_kv": []
}
]
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [CalendarEventsResponse](#CalendarEventsResponse) |
| 400 | Bad request | None |
## Schemas
### CalendarEventsResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| date | string | false | Response date |
| list | object[] | true | List of calendar date groups, see [CalendarDateGroup](#CalendarDateGroup) |
### CalendarDateGroup
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| date | string | true | Date |
| count | integer | false | Number of events on this date |
| infos | object[] | true | List of calendar events, see [CalendarEventInfo](#CalendarEventInfo) |
### CalendarEventInfo
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | string | false | Event ID |
| symbol | string | false | Security symbol |
| market | string | false | Market |
| counter_name | string | false | Security name |
| event_type | string | false | Event type |
| activity_type | string | false | Activity type |
| date | string | false | Event date |
| datetime | string | false | Event datetime |
| date_type | string | false | Date type |
| content | string | false | Event content description |
| currency | string | false | Currency |
| star | integer | false | Importance rating (1-3) |
| icon | string | false | Icon URL |
| chart_uid | string | false | Chart identifier |
| financial_market_time | string | false | Financial market time |
| data_kv | object[] | false | Key-value data pairs |
---
# IPO Calendar
URL: https://open.longbridge.com/docs/market/calendar/ipo-calendar.md
Get upcoming and recent IPO listings with expected offer price and listing date.
longbridge finance-calendar ipo
longbridge finance-calendar ipo --market US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| start | string | YES | Start date, YYYY-MM-DD |
| end | string | YES | End date, YYYY-MM-DD |
| market | string | NO | Market filter: `US`, `HK`, `SH`, `SZ`. Omit for all. |
| count | integer | NO | Max events per page; server default when omitted |
| offset | integer | NO | Number of events to skip from the start of the window |
| next | CalendarPageDirection | NO | Page direction from the `next_date` cursor: `Later` or `Earlier` |
## Request Example
```python
from longbridge.openapi import CalendarContext, CalendarCategory, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = CalendarContext(config)
resp = ctx.finance_calendar(CalendarCategory.Ipo, "2024-01-01", "2024-03-31")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncCalendarContext, CalendarCategory, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncCalendarContext.create(config)
resp = await ctx.finance_calendar(CalendarCategory.Ipo, "2024-01-01", "2024-03-31")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, CalendarContext, CalendarCategory, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = CalendarContext.new(config)
const resp = await ctx.financeCalendar(CalendarCategory.Ipo, '2024-01-01', '2024-03-31')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.calendar.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
CalendarContext ctx = CalendarContext.create(config)) {
var resp = ctx.financeCalendar(CalendarCategory.Ipo, "2024-01-01", "2024-03-31", null).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, calendar::{CalendarContext, CalendarCategory}, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = CalendarContext::new(config);
let resp = ctx.finance_calendar(CalendarCategory::Ipo, "2024-01-01", "2024-03-31", None, None, None, None).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::calendar;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
CalendarContext ctx = CalendarContext::create(config);
ctx.finance_calendar(CalendarCategory::Ipo, "2024-01-01", "2024-03-31", "", std::nullopt, std::nullopt, std::nullopt, [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/calendar"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := calendar.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.FinanceCalendar(context.Background(), "Ipo", "2024-01-01", "2024-03-31", nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"date": "2024-01-01",
"list": [
{
"date": "2024-01-15",
"count": 1,
"infos": [
{
"id": "12345",
"symbol": "AAPL.US",
"market": "US",
"counter_name": "Apple Inc.",
"event_type": "",
"activity_type": "",
"date": "2024-01-15",
"datetime": "",
"content": "",
"star": 0,
"currency": "",
"icon": "",
"chart_uid": "",
"date_type": "",
"financial_market_time": "",
"data_kv": []
}
]
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [CalendarEventsResponse](#CalendarEventsResponse) |
| 400 | Bad request | None |
## Schemas
### CalendarEventsResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| date | string | false | Response date |
| list | object[] | true | List of calendar date groups, see [CalendarDateGroup](#CalendarDateGroup) |
### CalendarDateGroup
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| date | string | true | Date |
| count | integer | false | Number of events on this date |
| infos | object[] | true | List of calendar events, see [CalendarEventInfo](#CalendarEventInfo) |
### CalendarEventInfo
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | string | false | Event ID |
| symbol | string | false | Security symbol |
| market | string | false | Market |
| counter_name | string | false | Security name |
| event_type | string | false | Event type |
| activity_type | string | false | Activity type |
| date | string | false | Event date |
| datetime | string | false | Event datetime |
| date_type | string | false | Date type |
| content | string | false | Event content description |
| currency | string | false | Currency |
| star | integer | false | Importance rating (1-3) |
| icon | string | false | Icon URL |
| chart_uid | string | false | Chart identifier |
| financial_market_time | string | false | Financial market time |
| data_kv | object[] | false | Key-value data pairs |
---
# Macro Calendar
URL: https://open.longbridge.com/docs/market/calendar/macro-calendar.md
Get upcoming [macroeconomic data](https://longbridge.com/calendar/macrodata) release events such as CPI, GDP, and Fed meetings.
longbridge finance-calendar macrodata
longbridge finance-calendar macrodata --market US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| start | string | YES | Start date, YYYY-MM-DD |
| end | string | YES | End date, YYYY-MM-DD |
| market | string | NO | Market filter: `US`, `HK`, `SH`, `SZ`. Omit for all. |
| count | integer | NO | Max events per page; server default when omitted |
| offset | integer | NO | Number of events to skip from the start of the window |
| next | CalendarPageDirection | NO | Page direction from the `next_date` cursor: `Later` or `Earlier` |
## Request Example
```python
from longbridge.openapi import CalendarContext, CalendarCategory, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = CalendarContext(config)
resp = ctx.finance_calendar(CalendarCategory.MacroData, "2024-01-01", "2024-03-31")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncCalendarContext, CalendarCategory, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncCalendarContext.create(config)
resp = await ctx.finance_calendar(CalendarCategory.MacroData, "2024-01-01", "2024-03-31")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, CalendarContext, CalendarCategory, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = CalendarContext.new(config)
const resp = await ctx.financeCalendar(CalendarCategory.MacroData, '2024-01-01', '2024-03-31')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.calendar.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
CalendarContext ctx = CalendarContext.create(config)) {
var resp = ctx.financeCalendar(CalendarCategory.MacroData, "2024-01-01", "2024-03-31", null).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, calendar::{CalendarContext, CalendarCategory}, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = CalendarContext::new(config);
let resp = ctx.finance_calendar(CalendarCategory::MacroData, "2024-01-01", "2024-03-31", None, None, None, None).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::calendar;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
CalendarContext ctx = CalendarContext::create(config);
ctx.finance_calendar(CalendarCategory::MacroData, "2024-01-01", "2024-03-31", "", std::nullopt, std::nullopt, std::nullopt, [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/calendar"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := calendar.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.FinanceCalendar(context.Background(), "MacroData", "2024-01-01", "2024-03-31", nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"date": "2024-01-01",
"list": [
{
"date": "2024-01-15",
"count": 1,
"infos": [
{
"id": "12345",
"symbol": "",
"market": "US",
"counter_name": "",
"event_type": "",
"activity_type": "",
"date": "2024-01-15",
"datetime": "",
"content": "US Core PPI MoM",
"star": 0,
"currency": "",
"icon": "",
"chart_uid": "",
"date_type": "",
"financial_market_time": "",
"data_kv": []
}
]
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [CalendarEventsResponse](#CalendarEventsResponse) |
| 400 | Bad request | None |
## Schemas
### CalendarEventsResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| date | string | false | Response date |
| list | object[] | true | List of calendar date groups, see [CalendarDateGroup](#CalendarDateGroup) |
### CalendarDateGroup
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| date | string | true | Date |
| count | integer | false | Number of events on this date |
| infos | object[] | true | List of calendar events, see [CalendarEventInfo](#CalendarEventInfo) |
### CalendarEventInfo
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | string | false | Event ID |
| symbol | string | false | Security symbol |
| market | string | false | Market |
| counter_name | string | false | Security name |
| event_type | string | false | Event type |
| activity_type | string | false | Activity type |
| date | string | false | Event date |
| datetime | string | false | Event datetime |
| date_type | string | false | Date type |
| content | string | false | Event content description |
| currency | string | false | Currency |
| star | integer | false | Importance rating (1-3) |
| icon | string | false | Icon URL |
| chart_uid | string | false | Chart identifier |
| financial_market_time | string | false | Financial market time |
| data_kv | object[] | false | Key-value data pairs |
---
# Meeting Calendar
URL: https://open.longbridge.com/docs/market/calendar/meeting-calendar.md
Browse upcoming shareholder meetings and company events.
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| start | string | YES | Start date, YYYY-MM-DD |
| end | string | YES | End date, YYYY-MM-DD |
| market | string | NO | Market filter: `US`, `HK`, `SH`, `SZ`. Omit for all. |
| count | integer | NO | Max events per page; server default when omitted |
| offset | integer | NO | Number of events to skip from the start of the window |
| next | CalendarPageDirection | NO | Page direction from the `next_date` cursor: `Later` or `Earlier` |
## Request Example
```python
from longbridge.openapi import CalendarContext, CalendarCategory, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = CalendarContext(config)
resp = ctx.finance_calendar(CalendarCategory.Meeting, "2024-01-01", "2024-03-31")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncCalendarContext, CalendarCategory, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncCalendarContext.create(config)
resp = await ctx.finance_calendar(CalendarCategory.Meeting, "2024-01-01", "2024-03-31")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, CalendarContext, CalendarCategory, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Open:', url))
const config = Config.fromOAuth(oauth)
const ctx = CalendarContext.new(config)
const resp = await ctx.financeCalendar(CalendarCategory.Meeting, '2024-01-01', '2024-03-31')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.calendar.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open: " + url)).get();
Config config = Config.fromOAuth(oauth);
CalendarContext ctx = CalendarContext.create(config)) {
var resp = ctx.financeCalendar(CalendarCategory.Meeting, "2024-01-01", "2024-03-31", null).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, calendar::{CalendarContext, CalendarCategory}, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = CalendarContext::new(config);
let resp = ctx.finance_calendar(CalendarCategory::Meeting, "2024-01-01", "2024-03-31", None, None, None, None).await?;
println!("{:?}", resp);
Ok(())
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/calendar"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
)
func main() {
o := oauth.New("your-client-id").OnOpenURL(func(url string) { fmt.Println("Open:", url) })
if err := o.Build(context.Background()); err != nil { log.Fatal(err) }
conf, _ := config.New(config.WithOAuthClient(o))
c, _ := calendar.NewFromCfg(conf)
defer c.Close()
resp, err := c.FinanceCalendar(context.Background(), "Meeting", "2024-01-01", "2024-03-31", nil)
if err != nil { log.Fatal(err) }
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | CalendarEventsResponse |
| 400 | Bad request | None |
---
# Merge Calendar
URL: https://open.longbridge.com/docs/market/calendar/merge-calendar.md
Browse upcoming M&A and merger events.
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| start | string | YES | Start date, YYYY-MM-DD |
| end | string | YES | End date, YYYY-MM-DD |
| market | string | NO | Market filter: `US`, `HK`, `SH`, `SZ`. Omit for all. |
| count | integer | NO | Max events per page; server default when omitted |
| offset | integer | NO | Number of events to skip from the start of the window |
| next | CalendarPageDirection | NO | Page direction from the `next_date` cursor: `Later` or `Earlier` |
## Request Example
```python
from longbridge.openapi import CalendarContext, CalendarCategory, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = CalendarContext(config)
resp = ctx.finance_calendar(CalendarCategory.Merge, "2024-01-01", "2024-03-31")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncCalendarContext, CalendarCategory, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncCalendarContext.create(config)
resp = await ctx.finance_calendar(CalendarCategory.Merge, "2024-01-01", "2024-03-31")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, CalendarContext, CalendarCategory, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => console.log('Open:', url))
const config = Config.fromOAuth(oauth)
const ctx = CalendarContext.new(config)
const resp = await ctx.financeCalendar(CalendarCategory.Merge, '2024-01-01', '2024-03-31')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.calendar.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open: " + url)).get();
Config config = Config.fromOAuth(oauth);
CalendarContext ctx = CalendarContext.create(config)) {
var resp = ctx.financeCalendar(CalendarCategory.Merge, "2024-01-01", "2024-03-31", null).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, calendar::{CalendarContext, CalendarCategory}, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = CalendarContext::new(config);
let resp = ctx.finance_calendar(CalendarCategory::Merge, "2024-01-01", "2024-03-31", None, None, None, None).await?;
println!("{:?}", resp);
Ok(())
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/calendar"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
)
func main() {
o := oauth.New("your-client-id").OnOpenURL(func(url string) { fmt.Println("Open:", url) })
if err := o.Build(context.Background()); err != nil { log.Fatal(err) }
conf, _ := config.New(config.WithOAuthClient(o))
c, _ := calendar.NewFromCfg(conf)
defer c.Close()
resp, err := c.FinanceCalendar(context.Background(), "Merge", "2024-01-01", "2024-03-31", nil)
if err != nil { log.Fatal(err) }
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | CalendarEventsResponse |
| 400 | Bad request | None |
---
# Split Calendar
URL: https://open.longbridge.com/docs/market/calendar/split-calendar.md
Get upcoming and historical stock split and reverse split events.
longbridge finance-calendar split
longbridge finance-calendar split --market HK
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| start | string | YES | Start date, YYYY-MM-DD |
| end | string | YES | End date, YYYY-MM-DD |
| market | string | NO | Market filter: `US`, `HK`, `SH`, `SZ`. Omit for all. |
| count | integer | NO | Max events per page; server default when omitted |
| offset | integer | NO | Number of events to skip from the start of the window |
| next | CalendarPageDirection | NO | Page direction from the `next_date` cursor: `Later` or `Earlier` |
## Request Example
```python
from longbridge.openapi import CalendarContext, CalendarCategory, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = CalendarContext(config)
resp = ctx.finance_calendar(CalendarCategory.Split, "2024-01-01", "2024-03-31")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncCalendarContext, CalendarCategory, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncCalendarContext.create(config)
resp = await ctx.finance_calendar(CalendarCategory.Split, "2024-01-01", "2024-03-31")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, CalendarContext, CalendarCategory, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = CalendarContext.new(config)
const resp = await ctx.financeCalendar(CalendarCategory.Split, '2024-01-01', '2024-03-31')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.calendar.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
CalendarContext ctx = CalendarContext.create(config)) {
var resp = ctx.financeCalendar(CalendarCategory.Split, "2024-01-01", "2024-03-31", null).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, calendar::{CalendarContext, CalendarCategory}, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = CalendarContext::new(config);
let resp = ctx.finance_calendar(CalendarCategory::Split, "2024-01-01", "2024-03-31", None, None, None, None).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::calendar;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
CalendarContext ctx = CalendarContext::create(config);
ctx.finance_calendar(CalendarCategory::Split, "2024-01-01", "2024-03-31", "", std::nullopt, std::nullopt, std::nullopt, [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/calendar"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := calendar.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.FinanceCalendar(context.Background(), "Split", "2024-01-01", "2024-03-31", nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"date": "2024-01-01",
"list": [
{
"date": "2024-01-15",
"count": 1,
"infos": [
{
"id": "12345",
"symbol": "AAPL.US",
"market": "US",
"counter_name": "Apple Inc.",
"event_type": "",
"activity_type": "",
"date": "2024-01-15",
"datetime": "",
"content": "",
"star": 0,
"currency": "",
"icon": "",
"chart_uid": "",
"date_type": "",
"financial_market_time": "",
"data_kv": []
}
]
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [CalendarEventsResponse](#CalendarEventsResponse) |
| 400 | Bad request | None |
## Schemas
### CalendarEventsResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| date | string | false | Response date |
| list | object[] | true | List of calendar date groups, see [CalendarDateGroup](#CalendarDateGroup) |
### CalendarDateGroup
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| date | string | true | Date |
| count | integer | false | Number of events on this date |
| infos | object[] | true | List of calendar events, see [CalendarEventInfo](#CalendarEventInfo) |
### CalendarEventInfo
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | string | false | Event ID |
| symbol | string | false | Security symbol |
| market | string | false | Market |
| counter_name | string | false | Security name |
| event_type | string | false | Event type |
| activity_type | string | false | Activity type |
| date | string | false | Event date |
| datetime | string | false | Event datetime |
| date_type | string | false | Date type |
| content | string | false | Event content description |
| currency | string | false | Currency |
| star | integer | false | Importance rating (1-3) |
| icon | string | false | Icon URL |
| chart_uid | string | false | Chart identifier |
| financial_market_time | string | false | Financial market time |
| data_kv | object[] | false | Key-value data pairs |
---
# Historical Temperature
URL: https://open.longbridge.com/docs/market/history-market-temperature.md
This interface is used to get historical market temperature.
# HK temperature Q1 2025
longbridge market-temp HK --history --start 2025-01-01 --end 2025-03-31
# US temperature Jan 2025
longbridge market-temp US --history --start 2025-01-01 --end 2025-01-31
# CN A-share temperature H1 2025
longbridge market-temp CN --history --start 2025-01-01 --end 2025-06-30
## Request
HTTP Method GET
HTTP URL /v1/quote/history_market_temperature
### Parameters
| Name | Type | Required | Description |
| ---------- | ------ | -------- | ------------------------------------------- |
| market | string | YES | Market, currently supports US, HK, SG, CN |
| start_date | string | YES | Start date, minimum to 2016, e.g.: 20240101 |
| end_date | string | YES | End date, e.g.: 20250101 |
### Request Example
```python
import datetime
from longbridge.openapi import QuoteContext, Config, Market, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.history_market_temperature(Market.US, datetime.date(2024, 1, 1), datetime.date(2025, 1, 1))
print(resp)
```
```python
import asyncio
import datetime
from longbridge.openapi import AsyncQuoteContext, Config, Market, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.history_market_temperature(Market.US, datetime.date(2024, 1, 1), datetime.date(2025, 1, 1))
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth, Market, NaiveDate } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.historyMarketTemperature(Market.US, new NaiveDate(2024, 1, 1), new NaiveDate(2024, 1, 31))
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
import java.time.LocalDate;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
HistoryMarketTemperatureResponse resp = ctx.getHistoryMarketTemperature(Market.US, LocalDate.of(2024, 1, 1), LocalDate.of(2024, 1, 31)).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config, Market};
use time::macros::date;
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.history_market_temperature(Market::US, date!(2024 - 01 - 01), date!(2024 - 01 - 31)).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.history_market_temperature(Market::US, Date{2024, 1, 1}, Date{2024, 1, 31}, [](auto res) {
if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; }
std::cout << "records: " << res->records.size() << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
// History market temperature: use HTTP client for GET /v1/quote/history-market-temperature
_ = qctx
fmt.Println("See openapi-go for HTTP quote APIs")
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"data": {
"type": "month"
"list": [
{
"timestamp": 1580486400,
"temperature": 36,
"valuation": 12,
"sentiment": 46
},
{
"timestamp": 1582992000,
"temperature": 36,
"valuation": 12,
"sentiment": 46
}
]
}
}
```
#### Response Status
| Status | Description | Schema |
| ------ | --------------- | ------------------------------------------------------------------------ |
| 200 | Success | [HistoryMarketTemperatureResponse](#history_market_temperature_response) |
| 400 | Parameter Error | None |
## Schemas
### HistoryMarketTemperatureResponse
| Name | Type | Required | Description |
| ------------ | -------- | -------- | --------------------------------------------------------------- |
| list | object[] | true | List |
| ∟timestamp | integer | true | Timestamp |
| ∟temperature | integer | true | Temperature |
| ∟valuation | integer | true | Valuation |
| ∟sentiment | integer | true | Sentiment |
| type | string | true | Data granularity
day: daily; week: weekly; month: monthly |
## Error Codes
| Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | --------------------- | ----------------------------------------- |
| 2601500 | Server Internal Error | Please retry or contact technical support |
---
# Market Status
URL: https://open.longbridge.com/docs/market/market-status.md
Get the current open/close status for each exchange.
longbridge market-status
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| market | string | NO | Market code: `US`, `HK`, `SH`, `SZ`, `SG`. Omit for all markets. |
## Request Example
```python
from longbridge.openapi import MarketContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = MarketContext(config)
resp = ctx.market_status("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncMarketContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncMarketContext.create(config)
resp = await ctx.market_status("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, MarketContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = MarketContext.new(config)
const resp = await ctx.market_status('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.market.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
MarketContext ctx = MarketContext.create(config)) {
var resp = ctx.getMarketStatus("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, market::MarketContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = MarketContext::new(config);
let resp = ctx.market_status("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::market;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
MarketContext ctx = MarketContext::create(config);
ctx.market_status("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/market"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := market.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.MarketStatus(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"market_time": [
{
"market": "US",
"delay_sub_status": 0,
"delay_timestamp": "0",
"delay_trade_status": 0
},
{
"market": "HK",
"delay_sub_status": 0,
"delay_timestamp": "0",
"delay_trade_status": 0
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [MarketStatusResponse](#MarketStatusResponse) |
| 400 | Bad request | None |
## Schemas
### MarketStatusResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| market_time | object[] | true | List of market status items |
| ∟ market | string | true | Market: `US`, `HK`, `CN`, `SG`, `Crypto` |
| ∟ delay_sub_status | integer | false | Delayed subscription status |
| ∟ delay_timestamp | string | false | Delay timestamp |
| ∟ delay_trade_status | integer | false | Delayed trading status |
---
# Market Temperature
URL: https://open.longbridge.com/docs/market/market-temperature.md
Get Current Market Temperature
# HK market sentiment temperature
longbridge market-temp HK
# US market sentiment temperature
longbridge market-temp US
# China A-share market temperature
longbridge market-temp CN
## Request
HTTP Method GET
HTTP URL /v1/quote/market_temperature
### Parameters
| Name | Type | Required | Description |
| ------ | ------ | -------- | ----------------------------------------- |
| market | string | YES | Market, currently supports US, HK, SG, CN |
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, Market, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.market_temperature(Market.US)
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, Market, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.market_temperature(Market.US)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth, Market } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.marketTemperature(Market.US)
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id")
.build(url -> System.out.println("Open to authorize: " + url))
.get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
MarketTemperature resp = ctx.getMarketTemperature(Market.US).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config, Market};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.market_temperature(Market::US).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.market_temperature(Market::US, [](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
std::cout << "temperature: " << res->temperature << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
// Market temperature API: use HTTP client to call GET /v1/quote/market-temperature
_ = qctx
fmt.Println("See openapi-go for HTTP quote APIs")
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"data": {
"temperature": 50,
"description": "Temperature is moderate, maintaining stability",
"valuation": 23,
"sentiment": 78,
"updated_at": 1744616612
}
}
```
#### Response Status
| Status | Description | Schema |
| ------ | --------------- | --------------------------------------------------------- |
| 200 | Success | [MarketTemperatureResponse](#market_temperature_response) |
| 400 | Parameter Error | None |
## Schemas
### MarketTemperatureResponse
| Name | Type | Required | Description |
| ----------- | ------- | -------- | ----------------------- |
| temperature | integer | true | Temperature value |
| description | string | true | Temperature description |
| valuation | integer | true | Market valuation |
| sentiment | integer | true | Market sentiment |
| updated_at | integer | true | Update time |
## Error Codes
| Business Error Code | Description | Troubleshooting |
| ------------------- | --------------------- | ----------------------------------------- |
| 2601500 | Server Internal Error | Please retry or contact technical support |
---
# Rank Categories
URL: https://open.longbridge.com/docs/market/rank-categories.md
Get the tag category configuration for the popularity leaderboard. `second_tags[].key` can be passed to `rank_list`.
longbridge rank
## Parameters
> **SDK method parameters.**
This method takes no parameters.
## Request Example
```python
from longbridge.openapi import MarketContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = MarketContext(config)
resp = ctx.rank_categories()
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncMarketContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncMarketContext.create(config)
resp = await ctx.rank_categories()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, MarketContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = MarketContext.new(config)
const resp = await ctx.rankCategories()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.market.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
MarketContext ctx = MarketContext.create(config)) {
var resp = ctx.getRankCategories().get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, market::MarketContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = MarketContext::new(config);
let resp = ctx.rank_categories().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::market;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
MarketContext ctx = MarketContext::create(config);
ctx.rank_categories([](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/market"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := market.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.RankCategories(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"first_tags": [
{
"key": "ib_hot",
"name": "Hotness Rank",
"second_tags": [
{ "key": "ib_hot_all-us", "name": "US Total Hotness", "market": "US" },
{ "key": "ib_hot_all-hk", "name": "HK Total Hotness", "market": "HK" },
{ "key": "ib_hot_all-cn", "name": "A-share Total Hotness", "market": "CN" }
]
},
{
"key": "ib_change",
"name": "Price Change Rank",
"second_tags": [
{ "key": "ib_change_top-us", "name": "US Top Gainers", "market": "US" },
{ "key": "ib_change_top-hk", "name": "HK Top Gainers", "market": "HK" }
]
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [RankCategoriesResponse](#RankCategoriesResponse) |
| 400 | Bad request | None |
## Schemas
### RankCategoriesResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| first_tags | object[] | false | Top-level category list |
| ∟ key | string | false | Top-level category key |
| ∟ name | string | false | Top-level category name |
| ∟ second_tags | object[] | false | Second-level category list |
| ∟ ∟ key | string | false | Second-level category key; pass to `rank_list` as the `key` parameter |
| ∟ ∟ name | string | false | Second-level category name |
| ∟ ∟ market | string | false | Associated market: `US`, `HK`, `CN`, `SG` |
---
# Popularity Leaderboard
URL: https://open.longbridge.com/docs/market/rank-list.md
Get the stock ranking for a given leaderboard tag key. The key comes from `rank_categories` `second_tags[].key`, e.g. `hot_all-us` (US total hotness).
longbridge rank --key hot_all-us
longbridge rank --key hot_all-hk
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| key | string | YES | Leaderboard tag key from `rank_categories` `second_tags[].key` |
| need_article | boolean | NO | Whether to return associated articles, default `false` |
## Request Example
```python
from longbridge.openapi import MarketContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = MarketContext(config)
resp = ctx.rank_list("hot_all-us")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncMarketContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncMarketContext.create(config)
resp = await ctx.rank_list("hot_all-us", need_article=False)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, MarketContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = MarketContext.new(config)
const resp = await ctx.rankList('hot_all-us', false)
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.market.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
MarketContext ctx = MarketContext.create(config)) {
RankListOptions opts = new RankListOptions();
opts.key = "hot_all-us";
opts.needArticle = false;
var resp = ctx.getRankList(opts).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, market::MarketContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = MarketContext::new(config);
let resp = ctx.rank_list("hot_all-us", false).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::market;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
MarketContext ctx = MarketContext::create(config);
ctx.rank_list("hot_all-us", false, [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/market"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := market.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.RankList(context.Background(), "hot_all-us", false)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"bmp": false,
"lists": [
{
"code": "MU",
"symbol": "MU.US",
"name": "Micron Technology",
"last_done": "698.740",
"chg": "0.0252",
"change": "17.200",
"inflow": "-347041642",
"market_cap": "787992890796",
"industry": "Semiconductor Manufacturers",
"pre_post_price": "726.600",
"pre_post_chg": "0.0399",
"amplitude": "0.1082",
"five_day_chg": "-0.0885",
"turnover_rate": "0.0550",
"volume_rate": "1.11",
"pb_ttm": "32.68"
}
]
}
}
```
> Note: The response contains many additional fields; the above are the main ones.
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [RankListResponse](#RankListResponse) |
| 400 | Bad request | None |
## Schemas
### RankListResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| bmp | boolean | false | Whether the response is a market preview (before open) |
| lists | object[] | false | Leaderboard stock list |
| ∟ code | string | false | Ticker code (e.g. `MU`) |
| ∟ symbol | string | false | Symbol in `CODE.MARKET` format (e.g. `MU.US`) |
| ∟ name | string | false | Security name |
| ∟ last_done | string | false | Latest trade price |
| ∟ chg | string | false | Price change ratio as decimal (e.g. `0.0252` = 2.52%) |
| ∟ change | string | false | Absolute price change (e.g. `17.200`) |
| ∟ inflow | string | false | Net capital inflow (in the market's currency) |
| ∟ market_cap | string | false | Market capitalisation |
| ∟ industry | string | false | Industry classification |
| ∟ pre_post_price | string | false | Pre/post-market price |
| ∟ pre_post_chg | string | false | Pre/post-market price change ratio (decimal) |
| ∟ amplitude | string | false | Amplitude / intraday range ratio (decimal) |
| ∟ five_day_chg | string | false | 5-day price change ratio (decimal) |
| ∟ turnover_rate | string | false | Turnover rate (decimal) |
| ∟ volume_rate | string | false | Volume ratio (vs average) |
| ∟ pb_ttm | string | false | Price-to-book ratio (TTM) |
> Note: The response contains many additional fields; the above are the main ones.
---
# Top Movers
URL: https://open.longbridge.com/docs/market/top-movers.md
Get stocks whose price movement exceeds the 20-trading-day standard deviation, with automatically correlated news to explain the move.
longbridge top-movers
longbridge top-movers --market HK --sort time
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| markets | string[] | NO | Market list: `HK`, `US`, `CN`, `SG`; returns all markets if omitted |
| sort | integer | NO | Sort order: `0`=time (newest first), `1`=price change, `2`=hotness (default) |
| date | string | NO | Target date in `YYYY-MM-DD` format; returns latest data if omitted |
| limit | integer | NO | Number of results to return, default 20 |
## Request Example
```python
from longbridge.openapi import MarketContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = MarketContext(config)
resp = ctx.top_movers(markets=["HK", "US"], sort=2, limit=20)
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncMarketContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncMarketContext.create(config)
resp = await ctx.top_movers(markets=["HK", "US"], sort=2, limit=20)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, MarketContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = MarketContext.new(config)
const resp = await ctx.topMovers({ markets: ['HK', 'US'], sort: 2, limit: 20 })
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.market.*;
import java.util.Arrays;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
MarketContext ctx = MarketContext.create(config)) {
var resp = ctx.getTopMovers(new TopMoversOptions() {{ markets = new String[]{"HK", "US"}; sort = 2; limit = 20; }}).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, market::MarketContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = MarketContext::new(config);
let resp = ctx.top_movers(Some(vec!["HK", "US"]), Some(2), None, Some(20)).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::market;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
MarketContext ctx = MarketContext::create(config);
ctx.top_movers({"HK", "US"}, 2, "", 20, [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/market"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := market.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.TopMovers(context.Background(), []string{"HK", "US"}, 2, "", 20)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"events": [
{
"stock": {
"code": "TSLA",
"symbol": "TSLA.US",
"name": "Tesla, Inc.",
"change": "-0.0388",
"last_done": "404.110",
"market": "US",
"labels": ["Automobile Manufacturers"],
"logo": "https://assets.lbkrs.com/ticker/ST/US/TSLA.png",
"trade_status": 0
},
"timestamp": "1779202097",
"alert_reason": "Volatility exceeds 20-day avg",
"alert_type": 11,
"post": null
}
],
"next_params": {
"visited": ["11098290", "11098478", "11099705"]
}
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [TopMoversResponse](#TopMoversResponse) |
| 400 | Bad request | None |
## Schemas
### TopMoversResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| events | object[] | false | List of moving stocks |
| ∟ stock | object | false | Basic stock information |
| ∟ ∟ code | string | false | Ticker code (e.g. `TSLA`) |
| ∟ ∟ symbol | string | false | Symbol (e.g. `TSLA.US`) |
| ∟ ∟ name | string | false | Security name |
| ∟ ∟ change | string | false | Price change ratio (e.g. `-0.0388`) |
| ∟ ∟ last_done | string | false | Latest trade price |
| ∟ ∟ market | string | false | Market: `US`, `HK`, `CN`, `SG` |
| ∟ ∟ labels | string[] | false | Industry / theme tags |
| ∟ ∟ logo | string | false | Logo image URL |
| ∟ ∟ trade_status | integer | false | Trading status code |
| ∟ timestamp | string | false | Event time (Unix seconds as string) |
| ∟ alert_reason | string | false | Description of the move reason |
| ∟ alert_type | integer | false | Move type code |
| ∟ post | object | false | Associated news article (complex object with `title`, `description_html`, `published_at` and other fields; `null` when no article is linked) |
| next_params | object | false | Pagination cursor object; pass to the next request to get the next page |
---
# Trading Days
URL: https://open.longbridge.com/docs/market/trade-days.md
This API is used to obtain the trading days of the market.
# upcoming HK trading days
longbridge trading days HK
# upcoming US trading days
longbridge trading days US
# upcoming A-share trading days
longbridge trading days CN
:::info
[Business Command](/docs/socket/biz_command): `9`
:::
## Request
### Parameters
| Name | Type | Required | Description |
| ------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| market | string | Yes | Market
**Optional value:**
`US` - US market
`HK` - HK market
`CN` - CN market
`SG` - SG market |
| beg_day | string | Yes | begin day, in `YYMMDD` format, for example: `20220401` |
| end_day | string | Yes | begin day, in `YYMMDD` format, for example: `20220420`
**Check rules:**
The interval cannot be greater than one month
Only supports query data of the most recent year |
### Protobuf
```protobuf
message MarketTradeDayRequest {
string market = 1;
string beg_day = 2;
string end_day = 3;
}
```
### Request Example
```python
from datetime import date
from longbridge.openapi import QuoteContext, Config, Market, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.trading_days(Market.HK, date(2022, 1, 1), date(2022, 2, 1))
print(resp)
```
```python
import asyncio
from datetime import date
from longbridge.openapi import AsyncQuoteContext, Config, Market, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.trading_days(Market.HK, date(2022, 1, 1), date(2022, 2, 1))
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth, Market, NaiveDate } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.tradingDays(Market.HK, new NaiveDate(2022, 1, 1), new NaiveDate(2022, 2, 1))
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
import java.time.LocalDate;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id")
.build(url -> System.out.println("Open to authorize: " + url))
.get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
MarketTradingDays resp = ctx.getTradingDays(Market.HK, LocalDate.of(2022, 1, 1), LocalDate.of(2022, 2, 1)).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config, Market};
use time::macros::date;
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.trading_days(Market::HK, date!(2022 - 01 - 01), date!(2022 - 02 - 01)).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.trading_days(Market::HK, Date{2022, 1, 1}, Date{2022, 2, 1}, [](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
std::cout << "trade_days: " << res->trade_day.size() << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
openapi "github.com/longbridge/openapi-go"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
begin := time.Date(2022, 1, 1, 0, 0, 0, 0, time.UTC)
end := time.Date(2022, 2, 1, 0, 0, 0, 0, time.UTC)
days, err := qctx.TradingDays(context.Background(), openapi.MarketHK, &begin, &end)
if err != nil {
log.Fatal(err)
}
fmt.Println("trade_days:", len(days.TradeDay))
}
```
## Response
### Response Properties
| Name | Type | Description |
| -------------- | -------- | ------------------------------------- |
| trade_day | string[] | Trading days, in `YYMMDD` format |
| half_trade_day | string[] | Half trading days, in `YYMMDD` format |
### Protobuf
```protobuf
message MarketTradeDayResponse {
repeated string trade_day = 1;
repeated string half_trade_day = 2;
}
```
### Response JSON Example
```json
{
"trade_day": [
"20220120",
"20220121",
"20220124",
"20220125",
"20220126",
"20220127",
"20220128",
"20220204",
"20220207",
"20220208",
"20220209",
"20220210"
],
"half_trade_day": ["20220131"]
}
```
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | -------------------------- | ------------------------------------------------------------------ |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
| 7 | 301600 | Invalue request parameters | Please check the request parameter: `market`, `beg_day`, `end_day` |
---
# Trading Sessions
URL: https://open.longbridge.com/docs/market/trade-session.md
This API is used to obtain the daily trading hours of each market.
# trading session schedule for all markets (US, HK, CN, SG)
longbridge trading session
:::info
[Business Command](/docs/socket/biz_command): `8`
:::
## Request
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.trading_session()
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.trading_session()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.tradingSession()
for (const obj of resp) {
console.log(obj.toString())
}
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id")
.build(url -> System.out.println("Open to authorize: " + url))
.get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
MarketTradingSession[] resp = ctx.getTradingSession().get();
for (MarketTradingSession obj : resp) {
System.out.println(obj);
}
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.trading_session().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.trading_session([](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
for (const auto& s : *res) {
std::cout << s.market << " " << s.trade_sessions.size() << std::endl;
}
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
sessions, err := qctx.TradingSession(context.Background())
if err != nil {
log.Fatal(err)
}
for _, s := range sessions {
fmt.Println(s.Market, len(s.TradeSessions))
}
}
```
## Response
### Response Properties
| Name | Type | Description |
| -------------------- | -------- | ----------------------------------------------------------------------------------------------- |
| market_trade_session | object[] | Trading session data |
| ∟ market | string | Market
`US` - US market
`HK` - HK market
`CN` - CN market
`SG` - SG market |
| ∟ trade_session | object[] | Trading session |
| ∟∟ beg_time | int32 | Being trading time, in `hhmm` format, for example: `900` |
| ∟∟ end_time | int32 | End trading time, in `hhmm` format, for example: `1400` |
| ∟∟ trade_session | int32 | Trading session, see [TradeSession](/docs/quote/objects#tradesession---trading-session) |
### Protobuf
```protobuf
message MarketTradePeriodResponse {
repeated MarketTradePeriod market_trade_session = 1;
}
message MarketTradePeriod {
string market = 1;
repeated TradePeriod trade_session = 2;
}
message TradePeriod {
int32 beg_time = 1;
int32 end_time = 2;
TradeSession trade_session = 3;
}
```
### Response JSON Example
```json
{
"market_trade_session": [
{
"market": "US",
"trade_session": [
{
"beg_time": 930,
"end_time": 1600
},
{
"beg_time": 400,
"end_time": 930,
"trade_session": 1
},
{
"beg_time": 1600,
"end_time": 2000,
"trade_session": 2
}
]
},
{
"market": "HK",
"trade_session": [
{
"beg_time": 930,
"end_time": 1200
},
{
"beg_time": 1300,
"end_time": 1600
}
]
},
{
"market": "CN",
"trade_session": [
{
"beg_time": 930,
"end_time": 1130
},
{
"beg_time": 1300,
"end_time": 1457
}
]
},
{
"market": "SG",
"trade_session": [
{
"beg_time": 900,
"end_time": 1200
},
{
"beg_time": 1300,
"end_time": 1700
}
]
}
]
}
```
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
---
# Unusual Items
URL: https://open.longbridge.com/docs/market/unusual-items.md
Detect unusual market movements — price spikes, volume surges, and other abnormal trading activity.
longbridge anomaly --market US
longbridge anomaly --market HK
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| market | string | YES | Market code: `US`, `HK`, `SH`, `SZ`, `SG` |
## Request Example
```python
from longbridge.openapi import MarketContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = MarketContext(config)
resp = ctx.unusual_items("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncMarketContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncMarketContext.create(config)
resp = await ctx.unusual_items("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, MarketContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = MarketContext.new(config)
const resp = await ctx.unusual_items('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.market.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
MarketContext ctx = MarketContext.create(config)) {
var resp = ctx.getUnusualItems("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, market::MarketContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = MarketContext::new(config);
let resp = ctx.unusual_items("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::market;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
MarketContext ctx = MarketContext::create(config);
ctx.unusual_items("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/market"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := market.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.UnusualItems(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"all_off": false,
"changes": [
{
"symbol": "TSLA.US",
"name": "Tesla Inc.",
"alert_name": "Block Trade",
"alert_time": 1778198400000,
"emotion": 1,
"change_values": [
"+5.2%"
]
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [AnomalyResponse](#AnomalyResponse) |
| 400 | Bad request | None |
## Schemas
### AnomalyResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| all_off | boolean | false | Whether anomaly alerts are globally disabled |
| changes | object[] | false | List of market anomaly events |
| ∟ symbol | string | true | Security symbol |
| ∟ name | string | false | Security name |
| ∟ alert_name | string | false | Anomaly type name |
| ∟ alert_time | integer | false | Anomaly time (Unix timestamp, ms) |
| ∟ emotion | integer | false | Sentiment: `1`=positive/up, `2`=negative/down |
| ∟ change_values | string[] | false | Change value strings |
---
# Authorization
URL: https://open.longbridge.com/docs/mcp/authorization.md
# Authorization
Longbridge MCP uses standard OAuth 2.1. You never need to paste API keys or tokens into the client.
In ChatGPT, the authorization happens when you add Longbridge from Plugins. In other MCP clients, the first tool call usually starts the browser authorization flow.
## OAuth authorization flow
```
AI client Browser Longbridge
| | |
|--- initiate MCP ------->| |
| |--- redirect to auth ------>|
| |<-- show login & consent ---|
| |--- sign in & approve ------>|
|<-- return credentials --| |
|--- call tools with credentials ----------------------->|
```
**Steps:**
1. **Initiate connection** — Adding the Longbridge MCP config and calling a tool for the first time triggers the authorization flow
2. **Browser redirect** — The client opens a browser tab with the Longbridge login and consent page
3. **Sign in and approve** — Log in with your Longbridge account and review and accept the requested permission scopes (see [OAuth Scopes](/docs/getting-started#oauth-scopes)). Longbridge US accounts currently have market data tools only
4. **Session established** — After approval, the client receives credentials and MCP tools become available
5. **Credential maintenance** — Credentials are refreshed automatically per OAuth policy. You can remove the authorization in your Longbridge account security settings so it can no longer be renewed; tokens already issued remain valid until they expire
## Client compatibility
Longbridge MCP requires clients that fully implement **MCP OAuth 2.1**. Clients with incomplete support will fail during the authorization flow.
Known issue: early versions of Cherry Studio do not support the full OAuth flow. Please upgrade to the latest release.
If another client fails to connect, check its version and MCP support documentation.
:::tip Client can't open the browser?
If your client has incomplete OAuth support or cannot launch a browser, use an [Agent Auth Code](/docs/agent-auth) instead: generate a one-time code at [https://open.longbridge.com/connect](https://open.longbridge.com/connect), connect to the dedicated endpoint `https://mcp.longbridge.com/agent`, and have the agent redeem it via the `authenticate` tool.
:::
---
# Security Best Practices
URL: https://open.longbridge.com/docs/mcp/best-practices.md
# Security Best Practices
## Security recommendations
- **Least privilege**: Only approve the scopes required for your current task; avoid over-granting
- **Trading confirmation**: Every order tool runs as a dry run first and needs your explicit confirmation before anything is sent (see [How order confirmation works](/docs/mcp/trading#how-order-confirmation-works)); still, tell the AI to ask before executing
- **Credential handling**: OAuth credentials are managed by your client; avoid copying them into untrusted environments
- **Regular review**: Periodically check and revoke unused authorizations in your [Longbridge account](https://longbridge.com/hk/download) security settings (removing an authorization stops renewal; tokens already issued remain valid until they expire)
## Recommended usage pattern
1. **Start with read-only tools**: Begin with [market data](https://longbridge.com/markets), account overview, and position queries to learn tool behavior at low risk
2. **Practice on paper**: Authorize with a paper trading account to rehearse order flows without real money
3. **Gradually enable trading**: Enable order placement only after verifying scope configuration and your own risk controls
4. **Add guardrails in prompts**: For example, "keep each trade under X", "always confirm with me before placing an order"
---
# Longbridge MCP
URL: https://open.longbridge.com/docs/mcp.md
# Longbridge MCP Service
Longbridge provides a hosted MCP (Model Context Protocol) service that lets you use [Longbridge market data](https://longbridge.com/markets) and account capabilities directly from ChatGPT, Claude, AI coding assistants, and other chat tools — without managing API keys manually.
:::tip MCP endpoint
- Global: `https://mcp.longbridge.com`
- Mainland China: `https://mcp.longbridge.cn` (faster access)
:::
## Available capabilities
Longbridge MCP exposes 190+ tools across six capability areas. Your client discovers them automatically on connect — no manual configuration.
| Capability | Coverage |
| --------------------------- | -------------------------------------------------------------------------------------------------- |
| **[Real-time market data](https://longbridge.com/markets)** | Quotes, candlesticks, depth, broker queues, trades, intraday capital flow |
| **Fundamentals & research** | Company profiles, [dividends](https://longbridge.com/calendar/dividend), valuations, executive holdings, A/H premium, macroeconomic indicators |
| **Derivatives** | Option chains, warrant filters, issuers, warrant quotes |
| **Account & portfolio** | Balances, positions, cash flow, watchlists and groups |
| **Trading** | Place / modify / cancel orders, multi-leg options, estimate max purchase quantity |
| **Automation** | Price alerts, scheduled DCA (dollar-cost averaging) plans, grid trading |
Actual tool availability depends on your region, account level, and granted OAuth scopes. See [Tools](/docs/mcp/tools) for the full list.
## Prerequisites
- An active [Longbridge account](https://longbridge.com/hk/download) with onboarding completed, or a paper trading account
- An AI client that supports MCP OAuth 2.1 (see [Client compatibility](/docs/mcp/authorization#client-compatibility))
## Get started
1. [Connect your AI client](/docs/mcp/setup) — ChatGPT, Claude, Claude Code, Codex, Cursor, and more
2. [Authorize with your Longbridge account](/docs/mcp/authorization) — standard OAuth 2.1, no API keys to paste
3. [Trade stocks and options with AI](/docs/mcp/trading) — research, build, and place orders in natural language
4. Review the [security best practices](/docs/mcp/best-practices) before enabling trading
---
# Connect Your Client
URL: https://open.longbridge.com/docs/mcp/setup.md
# Connect Your Client
ChatGPT is the recommended starting point because Longbridge is available directly in ChatGPT Plugins. For other MCP clients, configuration format may vary across client versions; treat your client's official MCP documentation as the source of truth.
All clients connect to the same endpoint — `https://mcp.longbridge.com` (or `https://mcp.longbridge.cn` for faster access from Mainland China; see [Overview](/docs/mcp)).
:::tip Which clients can trade?
The ChatGPT App and the Claude directory connector are read-only: they cover market data, research, and account queries but not order placement. To place, modify, or cancel orders, connect a client directly to the MCP endpoint — Claude Code, Codex, Cursor, Zed, and others. See [Trade with AI](/docs/mcp/trading).
:::
## ChatGPT
Longbridge is available as an official ChatGPT App.
On ChatGPT web, desktop, or mobile:
1. Open **Plugins**
2. Search for `longbridge`, or open the [Longbridge ChatGPT App](https://chatgpt.com/plugins/longbridge) directly
3. Select **Longbridge** and complete the authorization login


After authorization, prefix every message with `@longbridge` to send it to Longbridge MCP — for example: `@longbridge check my today's orders`. Without this prefix, ChatGPT will not route your question to Longbridge.
:::warning Trading features unavailable in ChatGPT
Due to ChatGPT platform policies, the Longbridge ChatGPT App does not include order placement and other trading tools. To use trading features, switch to Claude Code, Cursor, or another MCP client.
:::
## Claude
Longbridge is available as an official connector in Claude's directory.
On [Claude](https://claude.ai) web or Claude Desktop:
1. Click **Customize** → **Connectors**, then click the **Add** button
2. Select **Browser Connectors** from the dropdown and search for `longbridge`
3. Select **Longbridge** and complete the authorization login
Or open the [Longbridge connector](https://claude.ai/directory/longbridge) directly.
## Claude Code
Run the following command in your terminal:
```bash
claude mcp add --transport http longbridge https://mcp.longbridge.com
```
Then open the `claude` terminal interface, type `/mcp`, select `longbridge`, and choose **Authenticate** to complete the OAuth authorization flow.
## Codex
Run the following command in your terminal:
```bash
codex mcp add longbridge --url https://mcp.longbridge.com
```
Then follow the OAuth authorization flow in Codex when prompted.
### Codex Desktop
1. Click **Settings** (bottom right) → **MCP Servers** → **Add Server**
2. In the "Connect to a custom MCP" screen, fill in:
- Name: `longbridge`
- Type: **Streamable HTTP**
- URL: `https://mcp.longbridge.com`
- Leave all other fields empty
3. Click **Save**
4. Back in the MCP Servers list, click **Authenticate** on the `longbridge` entry to complete OAuth authorization
## Gemini CLI
Run the following command in your terminal:
```bash
gemini mcp add --transport http longbridge https://mcp.longbridge.com -s user
```
Then start `gemini` and run `/mcp` to confirm `longbridge` is connected, authorizing in the browser if prompted.
To edit the config by hand instead, add this under `mcpServers` in `~/.gemini/settings.json` — note the key is `httpUrl`, not `url` (Gemini CLI treats `url` as an SSE endpoint, and the connection will fail):
```json
{
"mcpServers": {
"longbridge": {
"httpUrl": "https://mcp.longbridge.com"
}
}
}
```
## opencode
Run the following command in your terminal:
```bash
opencode mcp add longbridge --url https://mcp.longbridge.com --global
```
Run `opencode mcp list` to confirm it registered. To edit the config by hand instead, add this to `opencode.json`:
```json
{
"mcp": {
"servers": {
"longbridge": {
"type": "remote",
"url": "https://mcp.longbridge.com"
}
}
}
}
```
## OpenClaw
Run the following command in your terminal:
```bash
openclaw mcp add longbridge --url https://mcp.longbridge.com --transport streamable-http
```
Run `openclaw mcp doctor longbridge --probe` to verify the connection. You can also add it from the Control UI under **Settings** → **MCP**, choosing **Streamable HTTP** and entering the URL.
## Warp
1. Open **Settings** → **Agents** → **MCP servers**
2. Click **+ Add** and choose **Streamable HTTP or SSE Server (URL)**
3. Enter `https://mcp.longbridge.com` and save, then complete the OAuth authorization
## Grok
Open [Grok Connectors](https://grok.com/connectors) and add a custom MCP server:
1. In the left sidebar, go to **Skills and Connectors** → **Connectors** → **New Connector** → **Custom**
2. Fill in:
- Name: `Longbridge`
- Server URL: `https://mcp.longbridge.com`
3. Click **Add Connector** and follow the Longbridge OAuth 2 authorization flow to complete the setup


## Cursor
Settings → MCP Servers → Add Remote MCP Server, then enter `https://mcp.longbridge.com`.
## Zed
Add the following to your `settings.json` under the `context_servers` key (key name is customizable):
```json
{
"mcpServers": {
"longbridge": {
"url": "https://mcp.longbridge.com"
}
}
}
```
## Cherry Studio
Settings → MCP Servers → Add, then enter `https://mcp.longbridge.com`.
## Manus
In Manus, open the **Plugins** window, click the **Create** button on the right side, and select **Import MCP by JSON** from the menu. Paste the following JSON to complete the import:
```json
{
"mcpServers": {
"longbridge": {
"url": "https://mcp.longbridge.com"
}
}
}
```

## Next steps
- Learn how the [OAuth authorization flow](/docs/mcp/authorization) works, or use an Agent Auth Code if your client can't open a browser
- Browse all [available tools](/docs/mcp/tools)
---
# Tools
URL: https://open.longbridge.com/docs/mcp/tools.md
# Tools
Longbridge MCP exposes 190+ tools. Your client discovers them automatically on connect, and the AI picks the right tool for each request — you don't need to call tools by name.
Actual tool availability depends on your region, account level, and granted OAuth scopes; Longbridge US accounts currently have market data tools only. Trading tools are not available in the ChatGPT App or the Claude directory connector; see [Connect Your Client](/docs/mcp/setup).
## Available tools
---
# Trade Stocks and Options with AI
URL: https://open.longbridge.com/docs/mcp/trading.md
# Trade Stocks and Options with AI
Connect Claude Code, Codex, Cursor, or another MCP client to your Longbridge account and you can research markets, review your portfolio, analyze option chains, and place orders for US and Hong Kong stocks, ETFs, options, and funds — all in natural language.
This guide walks through the full workflow, from connecting your client to placing your first order.
## Can AI trade stocks through Longbridge?
Yes. Longbridge MCP turns natural-language instructions into real brokerage orders. Before preparing a trade, the AI can check your buying power, positions, real-time quotes, and open orders. Supported order features include:
- **Order types**: limit and market orders, limit/market-if-touched, and trailing stops by amount or percentage. Hong Kong stocks also support enhanced limit, at-auction, and odd-lot orders
- **Trading sessions**: regular hours, US pre-market and after-hours, and the US overnight session
- **Take-profit and stop-loss**: attach a take-profit, a stop-loss, or both (bracket) to an order
- **Order management**: modify the price or quantity of an open order, or cancel it
- **Validity**: Day, Good-Til-Canceled, and Good-Til-Date orders
Every order goes through a [two-step confirmation](#how-order-confirmation-works) — nothing is sent to the exchange until you approve the exact order.
## What can the AI do with your Longbridge account?
Once authorized, the AI can use [190+ tools](/docs/mcp/tools) on your behalf, including:
- Real-time quotes, candlesticks, order book depth, and capital flow for US, HK, and A-share markets
- Account balances, positions, P&L analysis, orders, executions, and statements
- Fundamentals, valuations, analyst ratings, news, and filings
- Option chains, option quotes with implied volatility and Greeks, and put/call volume
- Stock orders with attached take-profit / stop-loss
- Multi-leg option strategies submitted as a single order
- Fund orders, scheduled DCA (dollar-cost averaging) plans, grid trading, and price alerts
Access is limited to the markets, products, and permissions enabled on your account and to the OAuth scopes you grant.
## Connect your AI client to Longbridge
You need:
- A [Longbridge account](https://longbridge.com/hk/download) with onboarding completed, or a paper trading account
- An MCP client that supports trading — Claude Code, Codex, Cursor, Zed, or another client connected directly to `https://mcp.longbridge.com`
:::warning ChatGPT and the Claude connector are read-only
The Longbridge ChatGPT App and the Claude directory connector do not include trading tools. Use them for research and account queries; use a directly connected client for placing orders.
:::
### Step 1: Add the Longbridge MCP server
For example, in Claude Code:
```bash
claude mcp add --transport http longbridge https://mcp.longbridge.com
```
For other clients, see [Connect Your Client](/docs/mcp/setup).
### Step 2: Authorize with your Longbridge account
In Claude Code, type `/mcp`, select `longbridge`, and choose **Authenticate**. Your browser opens the Longbridge login page — sign in and approve the requested permissions. No API keys or tokens are ever pasted into the chat. See [Authorization](/docs/mcp/authorization) for details.
### Step 3: Verify the connection
Ask the AI something that reads your account:
```text
Show my Longbridge account balance and buying power.
```
If it returns your cash and buying power, you're connected.
## Research markets and your portfolio
Because the AI combines conversation with live market and account data, you can ask follow-up questions without switching apps.
```text
Show me my current positions, today's P&L, and which holding moved the most.
```
```text
Compare the current price, P/E, and today's performance of NVDA.US, AMD.US, and 700.HK.
```
```text
Summarize the latest news and analyst rating changes for TSLA.US.
```
The AI can also pull your open orders, order history, executions, cash flow, and monthly statements.
## Trade stocks and ETFs
Describe the order you want; the AI prepares it and shows you a preview before anything is sent.
```text
Buy 10 shares of AAPL.US with a limit price of $200, good for today.
```
```text
Buy 100 shares of QQQ.US at market, with a take-profit at $560 and a stop-loss at $480.
```
```text
Show my open orders and cancel the TSLA.US limit order.
```
For extended-hours trading, ask for it explicitly:
```text
Prepare a limit order to buy 5 shares of NVDA.US at $170 that can fill in pre-market and after-hours. Show me the order details before submitting.
```
Not sure how much you can afford? Ask first:
```text
How many shares of MSFT.US can I buy at $420 with my current buying power?
```
## How order confirmation works
Every tool that places, modifies, or cancels an order runs as a **dry run** by default:
1. The AI calls the order tool without executing. Longbridge validates the order and returns a preview with a three-digit **confirmation code** — nothing reaches the exchange.
2. The AI shows you the preview: symbol, side, quantity, price, order type, and session.
3. Only after you explicitly confirm does the AI call the tool again with the confirmation code, and the order is sent.
The confirmation code is single-use, expires in 10 minutes, and is bound to that exact order — if any field changes, a new preview is required. This protects you from orders placed by mistake or from a misread instruction.
## Trade options and analyze option chains
The AI can browse expirations and strikes, then pull quotes with implied volatility and Greeks for the contracts you care about.
```text
Show me the AAPL.US option chain for contracts expiring next Friday, calls only, strikes within 5% of the current price.
```
```text
Show me the delta, gamma, theta, and implied volatility of the AAPL.US $250 call expiring next Friday.
```
```text
What is today's put/call volume ratio for NVDA.US, and which contracts are most active?
```
When you're ready, single-leg option orders follow the same preview-and-confirm flow as stock orders.
## Build multi-leg option strategies
Longbridge supports native multi-leg orders, so all legs of a strategy are submitted as one order and fill together at a single net price. Supported strategies include:
- Vertical call and put spreads
- Straddles and strangles
- Calendar call and put spreads
- Covered calls, covered puts, and collars
```text
Build a bull call spread on SPY.US expiring in two weeks: buy the $580 call and sell the $590 call. Show me the legs, net debit, and max profit and loss before placing it.
```
Available strategies depend on your account's options trading level.
## Beyond stocks and options
The same connection also covers:
- **Funds**: browse funds, review performance and holdings, and place fund subscription or redemption orders
- **DCA plans**: create, pause, resume, or update scheduled recurring investments
- **Grid trading**: set up grid orders that buy and sell automatically within a price range
- **Price alerts**: get notified when a stock crosses a price or moves by a percentage
```text
Set up a monthly DCA plan to invest $500 in VOO.US on the 1st of each month.
```
```text
Alert me when NVDA.US falls below $160.
```
## Practice with a paper account
Not ready to trade with real money? Authorize Longbridge MCP with a paper trading account and rehearse the entire workflow — research, order building, confirmation, and cancellation — with simulated funds. When you authorize with your live account, orders are real brokerage orders.
## Why connect your AI to Longbridge?
- **Research to execution in one conversation**: market data, fundamentals, portfolio context, order building, preview, and execution without switching apps
- **Multi-market coverage**: US and Hong Kong stocks, ETFs, options, warrants, and funds from one account
- **Built-in safeguards**: every order requires an explicit confirmation of the exact order, and you control which permissions the AI receives
- **No API keys**: standard OAuth 2.1 sign-in, revocable at any time from your account security settings
## FAQ
### Can AI trade stocks with Longbridge?
Yes. Clients connected directly to the Longbridge MCP server — such as Claude Code, Codex, and Cursor — can place, modify, and cancel stock and ETF orders in US and Hong Kong markets.
### Can AI trade options with Longbridge?
Yes, including single-leg orders and multi-leg strategies, subject to your account's options trading level.
### Can I trade in ChatGPT or the Claude app?
Not currently. The Longbridge ChatGPT App and the Claude directory connector are read-only and cover research and account queries. Use a client connected directly to `https://mcp.longbridge.com` for trading.
### Will the AI place orders without asking me?
No. Order tools run as a dry run by default and return a preview. The order is only sent after you explicitly confirm that exact order.
### Does trading through AI use real money?
When authorized with your live account, yes — orders are real brokerage orders. You can authorize with a paper trading account to practice with simulated funds.
### Can I trade in pre-market and after-hours?
Yes. Ask the AI to allow the order to fill outside regular trading hours. US orders can also target the overnight session, depending on the security.
### Do I need to write code?
No. You connect your client once, sign in with your Longbridge account, and use natural-language prompts. Developers who prefer code can use the [OpenAPI SDKs](/docs) or the [Longbridge CLI](/docs/cli).
:::warning Disclaimer
The example prompts on this page are for educational purposes only and do not constitute investment advice. Investing involves risk, including the possible loss of principal. Options trading entails significant risk and is not appropriate for all investors. Always review each order preview carefully before confirming.
:::
---
# Troubleshooting
URL: https://open.longbridge.com/docs/mcp/troubleshooting.md
# Troubleshooting
## OAuth sign-in failed
- Confirm your Longbridge account is in good standing and identity verification is complete
- Remove the existing MCP configuration from the client and re-add it to trigger a fresh authorization
- Check whether the requested scopes are supported for your account type
- If your client can't open a browser, use an [Agent Auth Code](/docs/agent-auth) instead
## Connected but some tools are missing
- Client limits: the ChatGPT App and the Claude directory connector do not include trading tools
- Account or regional restrictions: certain markets or features may be limited by account level or region
- Scope changes: if tool capabilities have been updated, re-authorize to receive the new scopes
## Permission denied on trading actions
- Verify trading permissions and market eligibility on your account
- Confirm that the current MCP session's OAuth scopes include trading-related permissions
- Error `403308` (`Target API's scope is not in authorized scopes`) means the session was not granted the scope the tool needs, such as `account.read`, `trade.read` or `trade.write`: remove and re-add the MCP configuration and grant that scope. It can also appear when the account has no securities account or trading permission for the market involved. See [OAuth Scopes](/docs/getting-started#oauth-scopes)
---
# General
URL: https://open.longbridge.com/docs/qa/general.md
## Q1: Do I need to open a live account to call Longbridge Developers?
It depends on the account region. For Longbridge HK / SG accounts, the platform provides a **paper account** — you can develop and debug quote and trading interfaces without opening a real securities account. The **paper account** supports real-time quotes for HK, US, and A-share markets, as well as basic trading functionality for HK and US stocks and ETFs, making it suitable for API integration and feature verification.
That said, the paper account differs from the live environment in areas such as order matching and cash rules. If you want to experience the platform's full capabilities, we recommend opening a live account as well.
## Q2: How to open a paper account for debugging?
Please visit [Development Center](https://open.longbridge.com/dashboard/) to enable the paper account and obtain the corresponding App Key & Secret and Access Token.
To test against a paper account, call the API with that paper account's own Access Token or OAuth authorization, because the credential determines whether a request reaches the paper or the live account.
## Q3: Are the trading permissions for simulation debugging the same as for real accounts?
Quote is the same, trading might be different.
Paper accounts and live accounts share the same App Key & Secret, but have different Access Tokens. Quote permissions are associated with the App Key & Secret, while trading permissions are associated with the Access Token. Therefore, under paper accounts and live accounts, quote permissions are the same, but trading permissions are associated with the securities account and may differ.
## Q4: Which markets and types of securities are supported for quote and trading in paper account debugging?
Paper accounts are available for Longbridge HK / SG accounts only.
Market: Paper accounts support real-time market data for Hong Kong stocks, US stocks, and A-share markets. For advanced market data such as full US market data and Hong Kong Level2 data, they can be purchased through the online market store and accessed via OpenAPI.
Trading: Paper accounts support trading of Hong Kong and US stocks, ETFs, Hong Kong warrants, and US options.
For live accounts, HK stocks, A-shares, and HK warrants are available to Longbridge HK / SG accounts.
## Q5: Interface call frequency limits
Please visit [Rate Limit](/docs#rate-limit) for specific descriptions.
## Q6: How are interface call frequency limits applied in the case of multiple accounts?
If a customer holds multiple securities accounts, such as intraday financing or other sub-accounts, the trading interface call frequency limits are calculated and controlled based on different securities accounts, while quote interface calls are not affected by multiple accounts and are uniformly limited.
## Q7: Are there additional charges for trading operations through Longbridge Developers?
We do not charge additional fees for accessing market queries, trading, etc., via OpenAPI. For account-related fees such as trading commissions, platform fees, and market permissions, please refer to the information provided by the app and the official website.
## Q8: How to disable the permission table output in the console after the SDK connects to the server?
You can set the environment variable `LONGBRIDGE_PRINT_QUOTE_PACKAGES` to `false` (or legacy `LONGPORT_PRINT_QUOTE_PACKAGES`), or set `enable_print_quote_packages` to `false` when creating the `Config` object in the code to disable the permission table output in the console.
## Q9: I don't know how to code. How can I access stock data from the Longbridge Developers platform?
The platform offers two ways to access stock data without writing any code:
**CLI (Command-line Tool)**
Install the [Longbridge CLI](/docs/cli) and query market data with simple commands — no programming required:
longbridge quote AAPL.US TSLA.US
longbridge static NVDA.US
**MCP (AI Tool Integration)**
If you use AI tools like ChatGPT, Claude, or Cursor, connect the [Longbridge MCP service](/docs/mcp). In ChatGPT, search `longbridge` in Plugins or open the [Longbridge ChatGPT App](https://chatgpt.com/plugins/longbridge) directly to authorize; in other clients, complete MCP setup and then ask in plain language so the AI can query market data on your behalf.
Both methods require a Longbridge account.
---
# Quote Releated
URL: https://open.longbridge.com/docs/qa/broker.md
## Q1: How to calculate the subscription quote, is it one or more subscriptions if I both subscribe depth and broker with the same security?
The subscription quote is only calculated according to the security dimension, only one subscription will be calculted if you subscribe muilty quote type with one security.
## Q2: What is the specific limit logic for request frequency limit?
Use the token bucket to limit request and control the request rate. No more than 10 calls in 1 second, and no more than 5 concurrent requests.
## Q3: What is the available subscribing securities and corresponding symbol formats?
The security code uses the `ticker.region` format, `ticker` represents the code — for example, Tesla is `TSLA.US`. Available subscribing securities are as follows.
Market
Symbol
Ticker
Region
HK Market
Securities (including equities, ETFs, Warrants, CBBCs)
The official code of the security on the exchange
HK
Hang Seng Index
HSI
HK
Hang Seng China Enterprises Index
HSCEI
HK
Hang Seng TECH Index
HSTECH
HK
US Market
Securities (including stocks, ETFs)
The official code of the security on the exchange
US
Nasdsaq Index
.IXIC
US
Dow Jones Industrial Average
.DJI
US
CN Market
Securities (including stocks, ETFs)
The official code of the security on the exchange
SH or SZ
Index
The official code of the security on the exchange
SH or SZ
## Q4: What is the quote authority of OpenAPI? How to buy quote cards?
- Quote Authority
In accordance with the rules of the exchange, the authority of OpenAPI are independent, and are not shared with App, PC, or Web permissions. For example, the Hong Kong stock Level 2 authority you have on the App cannot be used on the OpenAPI side. Longbridge also presents basic market rights to OpenAPI users. If you need a higher-level market, you can activate the high-level quote authority by purchasing a market card through on-line Quote Store of brokers or Longbridge.
- How to buy quote cards
Longbridge users can choose the market cards they want to buy through the "Quote Store" in the Longbridge App.
## Q5: Quote Change By Date Time
- US Market: 09:20:00 EDT/EST
- HK Market: 08:50:00 CST
- CN Market: 09:00:00 CST
- SG Market: 08:20:00 CST
## Q6: How to enable Overnight quote
- **Overnight quotes are included free in US LV1.** No quote card purchase is required.
- Overnight quotes are currently **only available for US stocks**. Hong Kong stocks do not support overnight quotes.
- After obtaining the overnight quote permission, you still need to actively enable it by filling in the key `need_over_night_quote`, value `true` in the `metadata` field of the authentication interface.
```protobuf
message AuthRequest {
string token = 1;
map metadata = 2;
}
message ReconnectRequest {
string session_id = 1;
map metadata = 2;
}
```
- After turning on the night trading quotations, both the pull and push interfaces will be able to obtain the night trading quotations during the night trading period.
## Q7: Enable Overnight quote in OpenAPI SDK
- Create `Config` from environment variables
Set environment variable `LONGBRIDGE_ENABLE_OVERNIGHT` to `true` (legacy `LONGPORT_ENABLE_OVERNIGHT` also supported)
- Create `Config` object from constructor
```python
config = Config(app_key="your_app_key", app_secret="your_app_secret", access_token="your_access_token", enable_overnight=True)
```
---
# Trade
URL: https://open.longbridge.com/docs/qa/trade.md
## Q1: What types of orders are supported?
Both paper and live accounts support regular Limit orders, Market orders, and Conditional orders (such as Buy if touched, Sell if touched, etc.), but do not currently support Attached orders. Grid orders are supported via the [Grid Trading](/docs/trade/grid/overview) API.
## Q2: What are the trading hours for paper accounts?
This applies to Longbridge HK / SG paper accounts only.
Trading hours for paper accounts for Hong Kong stocks are the same as in the real environment. Trading pre & post market is not supported for U.S. stocks in the paper environment, only regular trading hours are supported.
## Q3: How can I trade overnight sessions for U.S. stocks?
To place orders for overnight trading, you can specify overnight trading by passing the OVERNIGHT value to the `outside_rth` parameter in the order placement API.
## Q4: What are the trading rules for paper accounts?
This applies to Longbridge HK / SG paper accounts only.
Paper accounts support trading in Hong Kong and U.S. stocks, ETFs, Hong Kong warrants, and U.S. options. Pre & post market trading is not supported in paper accounts.
Trades in the paper environment are matched based on the bid-ask spread from the real market. If the buy order price is higher than or equal to the ask price and the sell order price is lower than or equal to the bid price, a trade can be executed. Market orders are matched by default.
## Q5: How can I reset the funds in my paper account?
Manual resetting of demo funds is not supported at the moment. If needed, please contact your customer service or account manager for offline processing.
## Q6: After placing orders through the OpenAPI, how can I view them?
After placing orders via the OpenAPI, you can view them through any of the following:
- **Order inquiry API**: Call the API to query real-time order status
- **WebSocket push**: Subscribe to trade push events to receive order updates in real time
- **CLI**: Use the [Longbridge CLI](/docs/cli) to query from the command line, e.g. `longbridge orders`
- **App / PC**: View orders and their statuses directly in the terminal products
## Q7: How can I know if my account has sufficient funds for trading?
You can use the trading API `/v1/trade/estimate/buy_limit` to estimate the available cash & margin buying power, and short selling quantity in your account. Due to the complexity of risk control requirements, it's not recommended to calculate the tradable quantity manually.
## Q8: What does it mean when the order placement API returns "User authentication failed"?
This error usually indicates that the user does not have permission for the corresponding trading operation, such as options trading or short selling U.S. stocks. You can complete the permission opening process guided by the order placement in the app. After obtaining the necessary permissions, you can continue trading or performing other operations through OpenAPI.
## Q9: Does U.S. options trading support pre-market trading?
Pre-market options trading is not currently supported. We are planning to add this feature, including multi-leg options, which will be released together. We will update the documentation once it becomes available.
## Q10: How do I close a position?
There is no dedicated close-position API, and the order request has no open/close flag. Closing is a regular order in the opposite direction:
1. Call `stock_positions` for the symbol and read `available_quantity` (not `quantity`). If it is `0`, there is nothing to close.
2. A positive value is a long position: submit a `Sell` order. A negative value is a short position: submit a `Buy` order. Use the absolute value as the quantity.
3. Use a market order (`MO`) during regular hours. US pre-market and after-hours do not accept market orders, so submit a limit order (`LO`) at the latest price with `outside_rth` set to `ANY_TIME`. Pass a unique `client_request_id` so a retry cannot close the position twice.
Submitting more than `available_quantity` opens a position in the opposite direction. See [Close a position](/docs/trade/order/close_position) for a complete, runnable example in each SDK language.
## Q11: Why does a fractional U.S. stock order return error code 603200?
Fractional U.S. stock orders (for example, a quantity of `0.05`) are supported during regular trading hours only, and must set `outside_rth` to `RTH_ONLY`. If `outside_rth` is omitted or set to `ANY_TIME`, the order is rejected with HTTP 500 and error code `603200`. The `cancel` / `evaluate` fields in that response come from an in-app prompt; no assessment is needed. Set `outside_rth` to `RTH_ONLY` and submit again.
---
# Calc Index
URL: https://open.longbridge.com/docs/quote/pull/calc-index.md
This API is used to obtain the calculate indexes of securities.
# PE, PB, EPS and other indexes
longbridge calc-index TSLA.US NVDA.US
# select specific indexes
longbridge calc-index AAPL.US --index pe,pb,eps,turnover_rate
# market cap indexes
longbridge calc-index TSLA.US --index pe,total_market_value
:::info
[Business Command](../../socket/biz_command): `26`
:::
## Request
### Parameters
| Name | Type | Required | Description |
| ---------- | -------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| symbols | string[] | Yes | Security code list, in `ticker.region` format, for example: `[700.HK]`
**Check rules:**
The maximum number of symbols in each request is `500` |
| calc_index | init32[] | Yes | Calc indexes, for example: `[1,2,3]`, see [CalcIndex](../objects#calcindex---calculate-index) |
### Protobuf
```protobuf
message SecurityCalcQuoteRequest {
repeated string symbols = 1;
repeated CalcIndex calc_index = 2;
}
```
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, CalcIndex, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.calc_indexes(["700.HK", "AAPL.US"], [CalcIndex.LastDone, CalcIndex.ChangeRate])
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, CalcIndex, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.calc_indexes(["700.HK", "AAPL.US"], [CalcIndex.LastDone, CalcIndex.ChangeRate])
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth, CalcIndex } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.calcIndexes(['700.HK', 'AAPL.US'], [CalcIndex.LastDone, CalcIndex.ChangeRate])
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id")
.build(url -> System.out.println("Open to authorize: " + url))
.get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
SecurityCalcIndex[] resp = ctx.getCalcIndexes(
new String[] { "700.HK", "AAPL.US" },
new CalcIndex[] { CalcIndex.LastDone, CalcIndex.ChangeRate }
).get();
for (SecurityCalcIndex o : resp) System.out.println(o);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config, quote::CalcIndex};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.calc_indexes(
vec!["700.HK".to_string(), "AAPL.US".to_string()],
vec![CalcIndex::LastDone, CalcIndex::ChangeRate],
).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.calc_indexes(symbols, indexes, [](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
for (const auto& o : *res) std::cout << o.symbol << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
indexes, err := qctx.CalcIndex(context.Background(), []string{"700.HK", "AAPL.US"}, []quote.CalcIndex{quote.CalcIndexLastDone, quote.CalcIndexChangeRate})
if err != nil {
log.Fatal(err)
}
for _, o := range indexes {
fmt.Println(o.Symbol)
}
}
```
## Response
### Response Properties
| Name | Type | Description |
| -------------------------- | -------- | ----------------------------------------------------------------------------------------- |
| security_calc_index | object[] | Security Index Data |
| ∟ symbol | string | Security code |
| ∟ last_done | string | Latest price |
| ∟ change_val | string | Change value |
| ∟ change_rate | string | Change ratio (This field is a ratio field, not include symbol `%`) |
| ∟ volume | int64 | Volume |
| ∟ turnover | string | Turnover |
| ∟ ytd_change_rate | string | Year-to-date change ratio (This field is a ratio field, not include symbol `%`) |
| ∟ turnover_rate | string | Turnover rate (This field is a ratio field, not include symbol `%`) |
| ∟ total_market_value | string | Total market value |
| ∟ capital_flow | string | Capital flow |
| ∟ amplitude | string | Amplitude (This field is a ratio field, not include symbol `%`) |
| ∟ volume_ratio | string | Volume ratio |
| ∟ pe_ttm_ratio | string | PE (TTM) |
| ∟ pb_ratio | string | PB |
| ∟ dividend_ratio_ttm | string | Dividend ratio (TTM) |
| ∟ five_day_change_rate | string | Five days change ratio (This field is a ratio field, not include symbol `%`) |
| ∟ ten_day_change_rate | string | Ten days change ratio (This field is a ratio field, not include symbol `%`) |
| ∟ half_year_change_rate | string | Half year change ratio (This field is a ratio field, not include symbol `%`) |
| ∟ five_minutes_change_rate | string | Five minutes change ratio (This field is a ratio field, not include symbol `%`) |
| ∟ expiry_date | string | Expirt date |
| ∟ strike_price | string | Strike price |
| ∟ upper_strike_price | string | Upper bound price |
| ∟ lower_strike_price | string | Lower bound price |
| ∟ outstanding_qty | int64 | Outstanding quantity |
| ∟ outstanding_ratio | string | Outstanding ratio (This field is a ratio field, not include symbol `%`) |
| ∟ premium | string | Premium (This field is a ratio field, not include symbol `%`) |
| ∟ itm_otm | string | In/out of the bound (This field is a ratio field, not include symbol `%`) |
| ∟ implied_volatility | string | Implied volatility (This field is a ratio field, not include symbol `%`) |
| ∟ warrant_delta | string | Warrant delta |
| ∟ call_price | string | Call price |
| ∟ to_call_price | string | Price interval from the call price (This field is a ratio field, not include symbol `%`) |
| ∟ effective_leverage | string | Effective leverage |
| ∟ leverage_ratio | string | Leverage ratio |
| ∟ conversion_ratio | string | Conversion ratio |
| ∟ balance_point | string | Breakeven point |
| ∟ open_interest | int64 | Open interest |
| ∟ delta | string | Delta. Measures the expected change in option price for a $1 move in the underlying asset price. |
| ∟ gamma | string | Gamma. Measures the expected change in Delta for a $1 move in the underlying asset price. |
| ∟ theta | string | Theta. Measures the expected change in option price as one day passes; the raw value has been divided by 365 to convert to a daily value, representing the impact of one day's time decay on the option price. |
| ∟ vega | string | Vega. Measures the expected change in option price when implied volatility (IV) moves by 1 (i.e., 100%); divides the raw value by 100 to get the expected price change per 1% move in IV. |
| ∟ rho | string | Rho. Measures the expected change in option price when the risk-free interest rate moves by 1 (i.e., 100%); divides the raw value by 100 to get the expected price change per 1% move in the interest rate. |
### Protobuf
```protobuf
message SecurityCalcIndex {
string symbol = 1;
string last_done = 2;
string change_val = 3;
string change_rate = 4;
int64 volume = 5;
string turnover = 6;
string ytd_change_rate = 7;
string turnover_rate = 8;
string total_market_value = 9;
string capital_flow = 10;
string amplitude = 11;
string volume_ratio = 12;
string pe_ttm_ratio = 13;
string pb_ratio = 14;
string dividend_ratio_ttm = 15;
string five_day_change_rate = 16;
string ten_day_change_rate = 17;
string half_year_change_rate = 18;
string five_minutes_change_rate = 19;
string expiry_date = 20;
string strike_price = 21;
string upper_strike_price = 22;
string lower_strike_price = 23;
int64 outstanding_qty = 24;
string outstanding_ratio = 25;
string premium = 26;
string itm_otm = 27;
string implied_volatility = 28;
string warrant_delta = 29;
string call_price = 30;
string to_call_price = 31;
string effective_leverage = 32;
string leverage_ratio = 33;
string conversion_ratio = 34;
string balance_point = 35;
int64 open_interest = 36;
string delta = 37;
string gamma = 38;
string theta = 39;
string vega = 40;
string rho = 41;
}
message SecurityCalcQuoteResponse {
repeated SecurityCalcIndex security_calc_index = 1;
}
```
### Response JSON Example
```json
{
"securityCalcIndex": [
{
"symbol": "AAPL.US",
"lastDone": "131.880",
"changeVal": "-5.2500",
"changeRate": "-3.83",
"volume": "122207099",
"turnover": "16269088361.000",
"ytdChangeRate": "-25.63",
"turnoverRate": "0.76",
"totalMarketValue": "2134501670280.00",
"capitalFlow": "14664053535.556",
"amplitude": "2.74",
"volumeRatio": "3.22",
"peTtmRatio": "21.26",
"pbRatio": "31.71",
"dividendRatioTtm": "0.64",
"fiveDayChangeRate": "-9.76",
"tenDayChangeRate": "-11.87",
"halfYearChangeRate": "-7.01",
"fiveMinutesChangeRate": "0.00"
},
{
"symbol": "69672.HK",
"lastDone": "0.010",
"changeRate": "0.00",
"expiryDate": "20221024",
"strikePrice": "379.880",
"outstandingQty": "6090000",
"outstandingRatio": "7.61",
"premium": "0.67",
"itmOtm": "0.65",
"callPrice": "375.880",
"toCallPrice": "-100.00",
"leverageRatio": "75.48",
"balancePoint": "374.880"
},
{
"symbol": "AAPL220617C137000.US",
"lastDone": "1.17",
"changeVal": "-2.04",
"changeRate": "-63.55",
"volume": "23499",
"turnover": "3903660.00",
"expiryDate": "20220617",
"strikePrice": "137.00",
"premium": "11709.40",
"impliedVolatility": "43.54",
"openInterest": "5210",
"delta": "0.263",
"gamma": "0.043",
"theta": "-1.266",
"vega": "5.660",
"rho": "0.580"
},
{
"symbol": "HSI.HK",
"lastDone": "21119.650",
"changeVal": "52.070",
"changeRate": "0.25",
"volume": "96449546281",
"turnover": "96449546281.000",
"ytdChangeRate": "-9.74",
"amplitude": "1.86",
"volumeRatio": "0.59",
"fiveDayChangeRate": "-1.91",
"tenDayChangeRate": "-0.02",
"halfYearChangeRate": "-11.83",
"fiveMinutesChangeRate": "0.00"
}
]
}
```
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
| 7 | 301607 | Too many request symbols | Reduce the number of symbols in a request |
---
# Capital Distribution
URL: https://open.longbridge.com/docs/quote/pull/capital-distribution.md
This API is used to obtain the daily capital distribution of security.
# capital distribution snapshot for Tesla (large/medium/small)
longbridge capital TSLA.US
# capital distribution snapshot for Apple
longbridge capital AAPL.US
# capital distribution snapshot for NVDA
longbridge capital NVDA.US
:::info
[Business Command](../../socket/biz_command): `25`
:::
## Request
### Parameters
| Name | Type | Required | Description |
| ------ | ------ | -------- | --------------------------------------------------------------- |
| symbol | string | Yes | Security code, in `ticker.region` format, for example: `700.HK` |
### Protobuf
```protobuf
message SecurityRequest {
string symbol = 1;
}
```
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.capital_distribution("700.HK")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.capital_distribution("700.HK")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.capitalDistribution('700.HK')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id")
.build(url -> System.out.println("Open to authorize: " + url))
.get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
CapitalDistributionResponse resp = ctx.getCapitalDistribution("700.HK").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.capital_distribution("700.HK").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.capital_distribution("700.HK", [](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
std::cout << "capital_distribution: " << res->symbol << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
dist, err := qctx.CapitalDistribution(context.Background(), "700.HK")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", dist)
}
```
## Response
### Response Properties
| Name | Type | Description |
| ----------- | -------- | -------------------- |
| symbol | string | Security code |
| timestamp | int64 | Data update time |
| capital_in | object[] | Inflow capital data |
| ∟ large | string | large order |
| ∟ medium | string | medium order |
| ∟ small | string | small order |
| capital_out | object[] | Outflow capital data |
| ∟ large | string | large order |
| ∟ medium | string | medium order |
| ∟ small | string | small order |
### Protobuf
```protobuf
message CapitalDistributionResponse {
message CapitalDistribution {
string large = 1;
string medium = 2;
string small = 3;
}
string symbol = 1;
int64 timestamp = 2;
CapitalDistribution capital_in = 3;
CapitalDistribution capital_out = 4;
}
```
### Response JSON Example
```json
{
"symbol": "700.HK",
"timestamp": "1655107800",
"capital_in": {
"large": "935389700.000",
"medium": "2056032380.000",
"small": "828715920.000"
},
"capital_out": {
"large": "1175331560.000",
"medium": "2271829740.000",
"small": "751648940.000"
}
}
```
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
| 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct |
| 7 | 301603 | No quotes | Security no quote |
| 7 | 301604 | No access | No access to security quote |
---
# Capital Flow
URL: https://open.longbridge.com/docs/quote/pull/capital-flow-intraday.md
This API is used to obtain the daily capital flow intraday of security.
# intraday capital flow time series for Tesla
longbridge capital TSLA.US --flow
# intraday capital flow time series for Apple
longbridge capital AAPL.US --flow
# intraday capital flow time series for NVDA
longbridge capital NVDA.US --flow
:::info
[Business Command](../../socket/biz_command): `24`
:::
## Request
### Parameters
| Name | Type | Required | Description |
| ------ | ------ | -------- | --------------------------------------------------------------- |
| symbol | string | Yes | Security code, in `ticker.region` format, for example: `700.HK` |
### Protobuf
```protobuf
message CapitalFlowIntradayRequest {
string symbol = 1;
}
```
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.capital_flow("700.HK")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.capital_flow("700.HK")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.capitalFlow('700.HK')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id")
.build(url -> System.out.println("Open to authorize: " + url))
.get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
CapitalFlowLine[] resp = ctx.getCapitalFlow("700.HK").get();
for (CapitalFlowLine line : resp) System.out.println(line);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.capital_flow("700.HK").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.capital_flow("700.HK", [](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
std::cout << "capital_flow lines: " << res->size() << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
lines, err := qctx.CapitalFlow(context.Background(), "700.HK")
if err != nil {
log.Fatal(err)
}
fmt.Println("capital_flow lines:", len(lines))
}
```
## Response
### Response Properties
| Name | Type | Description |
| ------------------ | -------- | ------------------------------ |
| symbol | string | Security code |
| capital_flow_lines | object[] | Capital flow data |
| ∟ inflow | string | Inflow capital data |
| ∟ timestamp | int64 | Start time stamp of the minute |
### Protobuf
```protobuf
message CapitalFlowIntradayResponse {
message CapitalFlowLine {
string inflow = 1;
int64 timestamp = 2;
}
string symbol = 1;
repeated CapitalFlowLine capital_flow_lines = 2;
}
```
### Response JSON Example
```json
{
"symbol": "700.HK",
"capital_flow_lines": [
{ "inflow": "-310255860.000", "timestamp": "1655106960" },
{ "inflow": "-314011220.000", "timestamp": "1655107020" },
{ "inflow": "-314011220.000", "timestamp": "1655107080" },
{ "inflow": "-314011220.000", "timestamp": "1655107140" },
{ "inflow": "-314011220.000", "timestamp": "1655107200" }
]
}
```
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
| 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct |
| 7 | 301603 | No quotes | Security no quote |
| 7 | 301604 | No access | No access to security quote |
---
# Filings
URL: https://open.longbridge.com/docs/quote/pull/filings.md
Get the filings list for a specified security.
# regulatory filings for Apple
longbridge filing list AAPL.US
# regulatory filings for Tesla
longbridge filing list TSLA.US
# regulatory filings for NVDA
longbridge filing list NVDA.US
## Request
HTTP Method GET
HTTP URL /v1/quote/filings
### Query Parameters
| Name | Type | Required | Description |
| ------ | ------ | -------- | -------------------------------------------------------- |
| symbol | string | YES | Stock symbol, use `ticker.region` format, e.g. `AAPL.US` |
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.filings("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.filings("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.filings('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
FilingItem[] resp = ctx.getFilings("AAPL.US").get();
for (FilingItem item : resp) System.out.println(item);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.filings("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.filings("AAPL.US", [](auto res) {
if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; }
std::cout << "filings: " << res->size() << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
items, err := qctx.Filings(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Println("filings:", len(items))
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"items": [
{
"id": "627391979864985729",
"title": "Apple | (4) Statement of changes in beneficial ownership",
"description": "",
"file_name": "4 - Apple Inc. (0000320193) (Issuer)",
"file_urls": [
"https://www.sec.gov/Archives/edgar/data/320193/000178052526000005/xslF345X05/wk-form4_1773786674.xml"
],
"publish_at": "1773786677"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------- | ------------------------------------------- |
| 200 | Success | [filings_response](#schemafilings_response) |
| 500 | Internal error | None |
## Schemas
### filings_response
| Name | Type | Required | Description |
| ------------- | -------- | -------- | -------------------------------------- |
| items | object[] | true | Filings list |
| ∟ id | string | true | Filing ID |
| ∟ title | string | true | Title |
| ∟ description | string | true | Summary |
| ∟ file_name | string | true | File name |
| ∟ file_urls | string[] | true | List of file URLs |
| ∟ publish_at | string | true | Publish time, Unix timestamp (seconds) |
---
# Short Positions (US & HK)
URL: https://open.longbridge.com/docs/quote/pull/short-positions.md
# Short Positions (US & HK)
Get short interest data for US or HK securities. Market is auto-detected from the symbol suffix: `.HK` → HKEX short position data (daily); others → US FINRA short interest data (bi-monthly).
longbridge short-positions TSLA.US
longbridge short-positions 700.HK
longbridge short-positions AAPL.US --count 50
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ------ | ------- | -------- | ----------------------------------------------------------------- |
| symbol | string | YES | Security symbol, e.g. `TSLA.US` or `700.HK` |
| count | integer | NO | Number of records to return (1–100, default: 20) |
## Request Example
longbridge short-positions TSLA.US
longbridge short-positions 700.HK
longbridge short-positions AAPL.US --count 50
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
# US example
resp = ctx.short_positions("TSLA.US", 20)
print(resp)
# HK example
resp = ctx.short_positions("700.HK", 20)
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
# US example
resp = await ctx.short_positions("TSLA.US", 20)
print(resp)
# HK example
resp = await ctx.short_positions("700.HK", 20)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.shortPositions('TSLA.US', 20)
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
var resp = ctx.getShortPositions("TSLA.US", 20).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.short_positions("TSLA.US", 20).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::quote;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
QuoteContext ctx = QuoteContext::create(config);
ctx.short_positions("TSLA.US", 20, [](auto resp) {
if (resp) std::cout << resp->size() << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
resp, err := qctx.ShortPositions(context.Background(), "TSLA.US", 20)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": [
{
"timestamp": "2022-03-15T04:00:00Z",
"current_shares_short": "111286790",
"avg_daily_share_volume": "95077016",
"days_to_cover": "1.17",
"rate": "0.0068",
"close": ""
}
]
}
```
```json
{
"code": 0,
"message": "success",
"data": [
{
"timestamp": "2024-06-13T16:00:00Z",
"amount": "53677721",
"balance": "20386798436",
"cost": "379.800",
"rate": "0.0057"
}
]
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | See schemas below |
| 400 | Bad request | None |
## Schemas
### US Response (`.US` symbols)
| Name | Type | Required | Description |
| ------------------------ | -------- | -------- | ---------------------------------------------- |
| data | object[] | false | Short position records |
| ∟ timestamp | string | false | Settlement date (RFC 3339, e.g. `2022-03-15T04:00:00Z`) |
| ∟ current_shares_short | string | false | Number of shares sold short |
| ∟ avg_daily_share_volume | string | false | Average daily share volume |
| ∟ days_to_cover | string | false | Days to cover (short shares ÷ avg daily vol) |
| ∟ rate | string | false | Short ratio |
| ∟ close | string | false | Closing price for the day |
### HK Response (`.HK` symbols)
| Name | Type | Required | Description |
| ----------- | -------- | -------- | ----------------------------------------- |
| data | object[] | false | Short position records |
| ∟ timestamp | string | false | Trade date (RFC 3339, e.g. `2022-03-15T04:00:00Z`) |
| ∟ amount | string | false | Short selling amount (HKD) |
| ∟ balance | string | false | Short position balance |
| ∟ cost | string | false | Closing price for the day |
| ∟ rate | string | false | Short ratio |
---
# Daily Short Sale Volume
URL: https://open.longbridge.com/docs/quote/pull/short-trades.md
Get daily short sale volume data for a security. Supports US stocks (FINRA/NASDAQ) and HK stocks (HKEX). US data is updated bi-weekly; HK data is updated each trading day.
longbridge short-trades TSLA.US
longbridge short-trades 700.HK --count 30
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ------ | ------- | -------- | --------------------------------------------------------------- |
| symbol | string | YES | Security symbol; supports US (e.g. `TSLA.US`) and HK (e.g. `700.HK`) |
| count | integer | NO | Number of records to return (1–100, default 20) |
## Request Example
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.short_trades("TSLA.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.short_trades("TSLA.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.shortTrades('TSLA.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
var resp = ctx.getShortTrades("TSLA.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.short_trades("TSLA.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::quote;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
QuoteContext ctx = QuoteContext::create(config);
ctx.short_trades("TSLA.US", [](auto resp) {
if (resp) std::cout << resp->size() << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
resp, err := qctx.ShortTrades(context.Background(), "TSLA.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
US stocks (`.US` suffix):
```json
{
"code": 0,
"message": "success",
"data": [
{
"timestamp": "2026-05-15T04:00:00Z",
"nus_amount": "5748485",
"ny_amount": "0",
"total_amount": "15778974",
"rate": "0.3643",
"close": "300.230"
}
]
}
```
HK stocks (`.HK` suffix):
```json
{
"code": 0,
"message": "success",
"data": [
{
"timestamp": "2026-05-17T16:00:00Z",
"amount": "2926000",
"balance": "1318056100.00",
"total_amount": "29497076",
"rate": "0.0992",
"close": "449.2"
}
]
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [ShortTradesResponse](#ShortTradesResponse) |
| 400 | Bad request | None |
## Schemas
### US Response (`.US` symbols)
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| data | object[] | false | Daily short trade volume records |
| ∟ timestamp | string | false | Trading date (RFC 3339, e.g. `2026-05-15T04:00:00Z`) |
| ∟ nus_amount | string | false | NASDAQ short sale volume (shares) |
| ∟ ny_amount | string | false | NYSE short sale volume (shares) |
| ∟ total_amount | string | false | Total trading volume for the day |
| ∟ rate | string | false | Short ratio (short volume ÷ total volume) |
| ∟ close | string | false | Closing price |
### HK Response (`.HK` symbols)
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| data | object[] | false | Daily short trade volume records |
| ∟ timestamp | string | false | Trading date (RFC 3339, e.g. `2026-05-15T04:00:00Z`) |
| ∟ amount | string | false | Short sale turnover amount (HKD) |
| ∟ balance | string | false | Short position balance |
| ∟ total_amount | string | false | Total trading turnover for the day |
| ∟ rate | string | false | Short ratio (short turnover ÷ total turnover) |
| ∟ close | string | false | Closing price |
---
# Definition
URL: https://open.longbridge.com/docs/quote/objects.md
## TradeStatus - Security Status
Security Status
| ID | Description |
| --- | ------------------- |
| 0 | Normal |
| 1 | Suspension |
| 2 | Delisted |
| 3 | Fuse |
| 4 | Papare List |
| 5 | Code Moved |
| 6 | To Be Opened |
| 7 | Split Stock Halts |
| 8 | Expired |
| 9 | Warrant To BeListed |
| 10 | Suspend |
### Protobuf
```protobuf
enum TradeStatus {
NORMAL = 0;
HALTED = 1;
DELISTED = 2;
FUSE = 3;
PREPARE_LIST = 4;
CODE_MOVED = 5;
TO_BE_OPENED = 6;
SPLIT_STOCK_HALTS = 7;
EXPIRED = 8;
WARRANT_PREPARE_LIST = 9;
SUSPEND_TRADE = 10;
}
```
## TradeSession - Trading Session
Trading Session
| ID | Description |
| --- | ----------------- |
| 0 | Trading |
| 1 | Pre-Tradeing |
| 2 | Post-Tradeing |
| 3 | OverNight-Trading |
### Protobuf
```protobuf
enum TradeSession {
NORMAL_TRADE = 0;
PRE_TRADE = 1;
POST_TRADE = 2;
}
```
## Period - Candlestick Period
| ID | Description |
| ---- | ------------------ |
| 1 | One Minute |
| 2 | Two Minutes |
| 3 | Three Minutes |
| 5 | Five Minutes |
| 10 | Ten Minutes |
| 15 | Fifteen Minutes |
| 20 | Twenty Minutes |
| 30 | Thirty Minutes |
| 45 | Forty-five Minutes |
| 60 | Sixty Minutes |
| 120 | Two Hours |
| 180 | Three Hours |
| 240 | Four Hours |
| 1000 | One Days |
| 2000 | One Week |
| 3000 | One Month |
| 3500 | One Quarter |
| 4000 | One Year |
### Protobuf
```protobuf
enum Period {
UNKNOWN_PERIOD = 0;
ONE_MINUTE = 1;
FIVE_MINUTE = 5;
FIFTEEN_MINUTE = 15;
THIRTY_MINUTE = 30;
SIXTY_MINUTE = 60;
DAY = 1000;
WEEK = 2000;
MONTH = 3000;
YEAR = 4000;
}
```
## AdjustType - Candlestick Adjustment Type
| ID | Description |
| --- | -------------- |
| 0 | Actual |
| 1 | Adjust forward |
### Protobuf
```protobuf
enum AdjustType {
NO_ADJUST = 0;
FORWARD_ADJUST = 1;
}
```
## SubType - Quote Type Of Subscription
| ID | Description |
| --- | ----------- |
| 1 | Quote |
| 2 | Depth |
| 3 | Broker |
| 4 | Trade |
### Protobuf
```protobuf
enum SubType {
UNKNOWN_TYPE = 0;
QUOTE = 1;
DEPTH = 2;
BROKERS = 3;
TRADE = 4;
}
```
## CalcIndex - Calculate Index
| ID | Description | Applicable Security Type |
| --- | ---------------------------------- | ------------------------ |
| 1 | Latest price | All |
| 2 | Change value | All |
| 3 | Change ratio | All |
| 4 | Volume | All |
| 5 | Turnover | All |
| 6 | Year-to-date change ratio | Except Option, Warrant |
| 7 | Turnover rate | Except Option, Warrant |
| 8 | Total market value | Except Option, Warrant |
| 9 | Capital flow | Except Option, Warrant |
| 10 | Amplitude | Except Option, Warrant |
| 11 | Volume ratio | Except Option, Warrant |
| 12 | PE (TTM) | Except Option, Warrant |
| 13 | PB | Except Option, Warrant |
| 14 | Dividend ratio (TTM) | Except Option, Warrant |
| 15 | Five days change ratio | Except Option, Warrant |
| 16 | Ten days change ratio | Except Option, Warrant |
| 17 | Half year change ratio | Except Option, Warrant |
| 18 | Five minutes change ratio | Except Option, Warrant |
| 19 | Expiry date | Only Option, Warrant |
| 20 | Strike Price | Only Option, Warrant |
| 21 | Upper bound price | Only Warrant |
| 22 | Lower bound price | Only Warrant |
| 23 | Outstanding quantity | Only Warrant |
| 24 | Outstanding ratio | Only Warrant |
| 25 | Premium | Only Option, Warrant |
| 26 | In/out of the bound | Only Warrant |
| 27 | Implied volatility | Only Option, Warrant |
| 28 | Warrant delta | Only Warrant |
| 29 | Call price | Only Warrant |
| 30 | Price interval from the call price | Only Warrant |
| 31 | Effective leverage | Only Warrant |
| 32 | Leverage ratio | Only Warrant |
| 33 | Conversion ratio | Only Warrant |
| 34 | Breakeven point | Only Warrant |
| 35 | Open interest | Only Option |
| 36 | Delta | Only Option |
| 37 | Gamma | Only Option |
| 38 | Theta | Only Option |
| 39 | Vega | Only Option |
| 40 | Rho | Only Option |
### Protobuf
```protobuf
enum CalcIndex {
CALCINDEX_UNKNOWN = 0;
CALCINDEX_LAST_DONE = 1;
CALCINDEX_CHANGE_VAL = 2;
CALCINDEX_CHANGE_RATE = 3;
CALCINDEX_VOLUME = 4;
CALCINDEX_TURNOVER = 5;
CALCINDEX_YTD_CHANGE_RATE = 6;
CALCINDEX_TURNOVER_RATE = 7;
CALCINDEX_TOTAL_MARKET_VALUE = 8;
CALCINDEX_CAPITAL_FLOW = 9;
CALCINDEX_AMPLITUDE = 10;
CALCINDEX_VOLUME_RATIO = 11;
CALCINDEX_PE_TTM_RATIO = 12;
CALCINDEX_PB_RATIO = 13;
CALCINDEX_DIVIDEND_RATIO_TTM = 14;
CALCINDEX_FIVE_DAY_CHANGE_RATE = 15;
CALCINDEX_TEN_DAY_CHANGE_RATE = 16;
CALCINDEX_HALF_YEAR_CHANGE_RATE = 17;
CALCINDEX_FIVE_MINUTES_CHANGE_RATE = 18;
CALCINDEX_EXPIRY_DATE = 19;
CALCINDEX_STRIKE_PRICE = 20;
CALCINDEX_UPPER_STRIKE_PRICE = 21;
CALCINDEX_LOWER_STRIKE_PRICE = 22;
CALCINDEX_OUTSTANDING_QTY = 23;
CALCINDEX_OUTSTANDING_RATIO = 24;
CALCINDEX_PREMIUM = 25;
CALCINDEX_ITM_OTM = 26;
CALCINDEX_IMPLIED_VOLATILITY = 27;
CALCINDEX_WARRANT_DELTA = 28;
CALCINDEX_CALL_PRICE = 29;
CALCINDEX_TO_CALL_PRICE = 30;
CALCINDEX_EFFECTIVE_LEVERAGE = 31;
CALCINDEX_LEVERAGE_RATIO = 32;
CALCINDEX_CONVERSION_RATIO = 33;
CALCINDEX_BALANCE_POINT = 34;
CALCINDEX_OPEN_INTEREST = 35;
CALCINDEX_DELTA = 36;
CALCINDEX_GAMMA = 37;
CALCINDEX_THETA = 38;
CALCINDEX_VEGA = 39;
CALCINDEX_RHO = 40;
}
```
## Board - Security Board
| Board | Description |
| ---------------- | --------------------------------------------- |
| USMain | US Main Board |
| USPink | US Pink Board |
| USDJI | Dow Jones Industrial Average |
| USNSDQ | Nasdsaq Index |
| USSector | US Industry Board |
| USOption | US Option |
| USOptionS | US Sepecial Option (market closed at 4:15 pm) |
| HKEquity | Hong Kong Equity Securities |
| HKPreIPO | HK PreIPO Security |
| HKWarrant | HK Warrant |
| HKHS | Hang Seng Index |
| HKSector | HK Industry Board |
| SHMainConnect | SH Main Board(Connect) |
| SHMainNonConnect | SH Main Board(Non Connect) |
| SHSTAR | SH Science and Technology Innovation Board |
| CNIX | CN Index |
| CNSector | CN Industry Board |
| SZMainConnect | SZ Main Board(Connect) |
| SZMainNonConnect | SZ Main Board(Non Connect) |
| SZGEMConnect | SZ Gem Board(Connect) |
| SZGEMNonConnect | SZ Gem Board(Non Connect) |
| SGMain | SG Main Board |
| STI | Singapore Straits Index |
| SGSector | SG Industry Board |
---
# Volume
URL: https://open.longbridge.com/docs/quote/pull/option-volume.md
Get real-time call/put volume snapshot for today.
longbridge option volume AAPL.US
longbridge option volume TSLA.US
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ------ | ------ | -------- | ---------------------------------------------- |
| symbol | string | YES | US stock symbol, e.g. `AAPL.US`, `TSLA.US` |
## Request Example
longbridge option volume AAPL.US
longbridge option volume TSLA.US
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.option_volume("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.option_volume("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.optionVolume('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
var resp = ctx.getOptionVolume("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.option_volume("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::quote;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
QuoteContext ctx = QuoteContext::create(config);
ctx.option_volume("AAPL.US", [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
resp, err := qctx.OptionVolume(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"symbol": "AAPL.US",
"call_volume": 284512,
"put_volume": 195830
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [option_volume_rsp](#option_volume_rsp) |
| 400 | Bad request | None |
## Schemas
### option_volume_rsp
| Name | Type | Required | Description |
| ----------- | ------ | -------- | --------------------------- |
| symbol | string | true | Security symbol |
| call_volume | int64 | true | Total call volume for today |
| put_volume | int64 | true | Total put volume for today |
---
# Daily Volume
URL: https://open.longbridge.com/docs/quote/pull/option-volume-daily.md
Get historical daily call/put volume and open interest data for a US stock's options.
longbridge option volume daily AAPL.US
longbridge option volume daily TSLA.US --count 60
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| --------- | ------- | -------- | ------------------------------------------------------------------------- |
| symbol | string | YES | Underlying US stock symbol, e.g. `AAPL.US`, `TSLA.US` |
| timestamp | integer | NO | Start Unix timestamp (seconds); `0` returns the most recent (default `0`) |
| count | integer | NO | Number of trading days to return (default `30`) |
> The Go SDK takes a `start` / `end` date range (`time.Time`) instead of `timestamp` / `count`.
## Request Example
longbridge option volume daily AAPL.US
longbridge option volume daily TSLA.US --count 60
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.option_volume_daily("AAPL.US", count=30)
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.option_volume_daily("AAPL.US", count=30)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.optionVolumeDaily('AAPL.US', 0, 30)
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
OptionVolumeDailyOptions opts = new OptionVolumeDailyOptions();
opts.symbol = "AAPL.US";
opts.count = 30;
var resp = ctx.getOptionVolumeDaily(opts).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.option_volume_daily("AAPL.US", 0, 30).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::quote;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
QuoteContext ctx = QuoteContext::create(config);
ctx.option_volume_daily("AAPL.US", 0, 30, [](auto resp) {
if (resp) std::cout << resp->size() << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
end := time.Now()
start := end.AddDate(0, 0, -30)
resp, err := qctx.OptionVolumeDaily(context.Background(), "AAPL.US", start, end)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"symbol": "AAPL.US",
"stats": [
{
"symbol": "AAPL.US",
"date": "2026-05-07",
"call_volume": 284512,
"put_volume": 195830,
"call_open_interest": 1824500,
"put_open_interest": 1532100,
"total_volume": 480342,
"total_open_interest": 3356600,
"pc_vol": 0.6886,
"pc_oi": 0.8398
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [option_volume_daily_rsp](#option_volume_daily_rsp) |
| 400 | Bad request | None |
## Schemas
### option_volume_daily_rsp
| Name | Type | Required | Description |
| ---------------------- | -------- | -------- | ------------------------------ |
| symbol | string | true | Security symbol |
| stats | object[] | true | Daily volume records |
| ∟ symbol | string | true | Security symbol |
| ∟ date | string | true | Date in `YYYY-MM-DD` format |
| ∟ call_volume | int64 | true | Call volume on that day |
| ∟ put_volume | int64 | true | Put volume on that day |
| ∟ call_open_interest | int64 | true | Call open interest |
| ∟ put_open_interest | int64 | true | Put open interest |
| ∟ total_volume | int64 | true | Total options volume |
| ∟ total_open_interest | int64 | true | Total options open interest |
| ∟ pc_vol | float | true | Put/call volume ratio |
| ∟ pc_oi | float | true | Put/call open interest ratio |
---
# Option Quotes
URL: https://open.longbridge.com/docs/quote/pull/option-quote.md
This API is used to obtain the real-time quotes of US stock options, including the option-specific data.
# AAPL call option $250 strike expiry 2026-04-17
longbridge option quote AAPL260417C250000.US
# TSLA put option $350 strike expiry 2026-04-18
longbridge option quote TSLA260418P350000.US
:::info
[Business Command](../../socket/biz_command): `12`
:::
## Request
### Parameters
| Name | Type | Required | Description |
| ------ | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| symbol | string[] | Yes | Security code list. obtain the symbol of the options through the [optionchain](./optionchain-date-strike.md) API, for example: `[BABA230120C160000.US]`
**Check rules:**
The maximum number of symbols in each request is `500` |
### Protobuf
```protobuf
message MultiSecurityRequest {
repeated string symbol = 1;
}
```
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.option_quote(["AAPL230317P160000.US"])
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.option_quote(["AAPL230317P160000.US"])
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.optionQuote(['AAPL230317P160000.US'])
for (const obj of resp) {
console.log(obj.toString())
}
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id")
.build(url -> System.out.println("Open to authorize: " + url))
.get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
OptionQuote[] resp = ctx.getOptionQuote(new String[] { "AAPL230317P160000.US" }).get();
for (OptionQuote obj : resp) {
System.out.println(obj);
}
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.option_quote(["AAPL230317P160000.US"]).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
std::vector symbols = {"AAPL230317C160000.US"};
ctx.option_quote(symbols, [](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
for (const auto& q : *res) {
std::cout << q.symbol << " " << (double)q.last_done << std::endl;
}
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
quotes, err := qctx.OptionQuote(context.Background(), []string{"AAPL230317C160000.US"})
if err != nil {
log.Fatal(err)
}
for _, q := range quotes {
fmt.Println(q.Symbol, q.LastDone)
}
}
```
## Response
### Response Properties
| Name | Type | Description |
| ------------------------ | -------- | ------------------------------------------------------------------------------------ |
| secu_quote | object[] | Options quote |
| ∟ symbol | string | Security code |
| ∟ last_done | string | Latest price |
| ∟ prev_close | string | Yesterday's close |
| ∟ open | string | Open |
| ∟ high | string | High |
| ∟ low | string | Low |
| ∟ timestamp | int64 | Time of latest price |
| ∟ volume | int64 | Volume |
| ∟ turnover | string | Turnover |
| ∟ trade_status | int32 | Security trading status, see [TradeStatus](../objects#tradestatus---security-status) |
| ∟ option_extend | object | Option extend quote |
| ∟∟ implied_volatility | string | Implied volatility |
| ∟∟ open_interest | int64 | Number of open positions |
| ∟∟ expiry_date | string | Exprity date, in `YYMMDD` format |
| ∟∟ strike_price | string | Strike price |
| ∟∟ contract_multiplier | string | Contract multiplier |
| ∟∟ contract_type | string | Option type
**Optional value:**
`A` - American
`U` - Europe |
| ∟∟ contract_size | string | Contract size |
| ∟∟ direction | string | Direction
**Optional value:**
`P` - put
`C` - call |
| ∟∟ historical_volatility | string | Underlying security historical volatility of the optionn |
| ∟∟ underlying_symbol | string | Underlying security symbol of the option |
### Protobuf
```protobuf
message OptionQuoteResponse {
repeated OptionQuote secu_quote = 1;
}
message OptionQuote {
string symbol = 1;
string last_done = 2;
string prev_close = 3;
string open = 4;
string high = 5;
string low = 6;
int64 timestamp = 7;
int64 volume = 8;
string turnover = 9;
TradeStatus trade_status = 10;
OptionExtend option_extend = 11;
}
message OptionExtend {
string implied_volatility = 1;
int64 open_interest = 2;
string expiry_date = 3;
string strike_price = 4;
string contract_multiplier = 5;
string contract_type = 6;
string contract_size = 7;
string direction = 8;
string historical_volatility = 9;
string underlying_symbol = 10;
}
```
### Response JSON Example
```json
{
"secu_quote": [
{
"symbol": "AAPL220429P162500.US",
"last_done": "7.78",
"prev_close": "4.13",
"open": "4.43",
"high": "7.80",
"low": "4.43",
"timestamp": 1651003200,
"volume": 3082,
"turnover": "1813434.00",
"option_extend": {
"implied_volatility": "0.592",
"open_interest": 11463,
"expiry_date": "20220429",
"strike_price": "162.50",
"contract_multiplier": "100",
"contract_type": "A",
"contract_size": "100",
"direction": "P",
"historical_volatility": "0.2750",
"underlying_symbol": "AAPL.US"
}
},
{
"symbol": "AAPL220429C150000.US",
"last_done": "9.25",
"prev_close": "13.87",
"open": "13.80",
"high": "13.80",
"low": "9.15",
"timestamp": 1651003200,
"volume": 413,
"turnover": "436835.00",
"option_extend": {
"implied_volatility": "0.702",
"open_interest": 800,
"expiry_date": "20220429",
"strike_price": "150.00",
"contract_multiplier": "100",
"contract_type": "A",
"contract_size": "100",
"direction": "C",
"historical_volatility": "0.2750",
"underlying_symbol": "AAPL.US"
}
}
]
}
```
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
| 7 | 301607 | Too many request symbols | Reduce the number of symbols in a request |
---
# Expiry Dates
URL: https://open.longbridge.com/docs/quote/pull/optionchain-date.md
This API is used to obtain the the list of expiration dates of option chain
# list all expiry dates for AAPL options
longbridge option chain AAPL.US
# list all expiry dates for TSLA options
longbridge option chain TSLA.US
:::info
[Business Command](../../socket/biz_command): `20`
:::
## Request
### Parameters
| Name | Type | Required | Description |
| ------ | ------ | -------- | -------------------------------------------------------------- |
| symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` |
### Protobuf
```protobuf
message SecurityRequest {
string symbol = 1;
}
```
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.option_chain_expiry_date_list("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.option_chain_expiry_date_list("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.optionChainExpiryDateList('AAPL.US')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id")
.build(url -> System.out.println("Open to authorize: " + url))
.get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
LocalDate[] resp = ctx.getOptionChainExpiryDateList("AAPL.US").get();
for (LocalDate d : resp) System.out.println(d);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.option_chain_expiry_date_list("AAPL.US").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.option_chain_expiry_date_list("AAPL.US", [](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
for (const auto& d : *res) std::cout << d.year << "-" << (int)d.month << "-" << (int)d.day << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
dates, err := qctx.OptionChainExpiryDateList(context.Background(), "AAPL.US")
if err != nil {
log.Fatal(err)
}
for _, d := range dates {
fmt.Println(d.Format("2006-01-02"))
}
}
```
## Response
### Response Properties
| Name | Type | Description |
| ----------- | -------- | -------------------------------------------------- |
| expiry_date | string[] | option chain expiry dates list, in `YYMMDD` format |
### Protobuf
```protobuf
message OptionChainDateListResponse {
repeated string expiry_date = 1;
}
```
### Response JSON Example
```json
{
"expiry_date": [
"20220422",
"20220429",
"20220506",
"20220513",
"20220520",
"20220527",
"20220603",
"20220617",
"20220715",
"20220819",
"20220916",
"20221021",
"20221118",
"20230120",
"20230317",
"20230616",
"20230915",
"20240119",
"20240621"
]
}
```
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
| 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct |
---
# Option Chain
URL: https://open.longbridge.com/docs/quote/pull/optionchain-date-strike.md
This API is used to obtain a list of option securities by the option chain expiry date.
# AAPL strike prices for 2026-04-17 expiry
longbridge option chain AAPL.US --date 2026-04-17
# TSLA strike prices for 2026-04-17 expiry
longbridge option chain TSLA.US --date 2026-04-17
:::info
[Business Command](../../socket/biz_command): `21`
:::
## Request
### Parameters
| Name | Type | Required | Description |
| ----------- | ------ | -------- | ---------------------------------------------------------------------------------------------------------------------------- |
| symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` |
| expiry_date | string | Yes | Option expiry date, in `YYMMDD` format, for example: `20220429`, obtained by [Option Expiry Date](./optionchain-date) API |
### Protobuf
```protobuf
message OptionChainDateStrikeInfoRequest {
string symbol = 1;
string expiry_date = 2;
}
```
### Request Example
```python
from datetime import date
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.option_chain_info_by_date("AAPL.US", date(2023, 1, 20))
print(resp)
```
```python
import asyncio
from datetime import date
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.option_chain_info_by_date("AAPL.US", date(2023, 1, 20))
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth, NaiveDate } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.optionChainInfoByDate('AAPL.US', new NaiveDate(2023, 1, 20))
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
import java.time.LocalDate;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id")
.build(url -> System.out.println("Open to authorize: " + url))
.get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
StrikePriceInfo[] resp = ctx.getOptionChainInfoByDate("AAPL.US", LocalDate.of(2023, 1, 20)).get();
for (StrikePriceInfo o : resp) System.out.println(o);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
use time::macros::date;
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.option_chain_info_by_date("AAPL.US", date!(2023 - 01 - 20)).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.option_chain_info_by_date("AAPL.US", Date{2023, 1, 20}, [](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
for (const auto& o : *res) std::cout << o.price << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
expiry := time.Date(2023, 1, 20, 0, 0, 0, 0, time.UTC)
list, err := qctx.OptionChainInfoByDate(context.Background(), "AAPL.US", &expiry)
if err != nil {
log.Fatal(err)
}
for _, o := range list {
fmt.Println(o.Price)
}
}
```
## Response
### Response Properties
| Name | Type | Description |
| ----------------- | -------- | ---------------------------- |
| strike_price_info | object[] | Option security info |
| ∟ price | string | Strike price |
| ∟ call_symbol | string | Security code of call option |
| ∟ put_symbol | string | Security code of put option |
| ∟ standard | bool | Is standard |
### Protobuf
```protobuf
message OptionChainDateStrikeInfoResponse {
repeated StrikePriceInfo strike_price_info = 1;
}
message StrikePriceInfo {
string price = 1;
string call_symbol = 2;
string put_symbol = 3;
bool standard = 4;
}
```
### Response JSON Example
```json
{
"strike_price_info": [
{
"price": "100",
"call_symbol": "AAPL220429C100000.US",
"put_symbol": "AAPL220429P100000.US",
"standard": true
},
{
"price": "105",
"call_symbol": "AAPL220429C105000.US",
"put_symbol": "AAPL220429P105000.US",
"standard": true
},
{
"price": "110",
"call_symbol": "AAPL220429C110000.US",
"put_symbol": "AAPL220429P110000.US",
"standard": true
},
{
"price": "115",
"call_symbol": "AAPL220429C115000.US",
"put_symbol": "AAPL220429P115000.US",
"standard": true
}
]
}
```
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | -------------------------- | ------------------------------------------------------------- |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
| 7 | 301600 | Invalue request parameters | Please check the request parameter: `symbol`, `expiry_date` |
---
# Overview
URL: https://open.longbridge.com/docs/quote/overview.md
# Quote API Overview
# list all market maker broker IDs and names (HK market)
longbridge participants
:::info
[Business Command](../../socket/biz_command): `16`
:::
## Request
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.participants()
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.participants()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.participants()
for (const obj of resp) {
console.log(obj.toString())
}
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id")
.build(url -> System.out.println("Open to authorize: " + url))
.get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
ParticipantInfo[] resp = ctx.getParticipants().get();
for (ParticipantInfo obj : resp) {
System.out.println(obj);
}
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.participants().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.participants([](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
for (const auto& p : *res) {
std::cout << p.broker_ids[0] << " " << p.name << std::endl;
}
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
participants, err := qctx.Participants(context.Background())
if err != nil {
log.Fatal(err)
}
for _, p := range participants {
fmt.Printf("%v %s\n", p.BrokerIds, p.ParticipantNameEn)
}
}
```
## Response
### Response Properties
| Name | Type | Description |
| -------------------------- | -------- | ------------------------ |
| participant_broker_numbers | object[] | participant data |
| ∟ broker_ids | int32[] | broker IDs |
| ∟ participant_name_cn | string | participant name (zh-CN) |
| ∟ participant_name_en | string | participant name (en) |
| ∟ participant_name_hk | string | participant name (zh-HK) |
### Protobuf
```protobuf
message ParticipantBrokerIdsResponse {
repeated ParticipantInfo participant_broker_numbers = 1;
}
message ParticipantInfo {
repeated int32 broker_ids = 1;
string participant_name_cn = 2;
string participant_name_en = 3;
string participant_name_hk = 4;
}
```
### Response JSON Example
```json
{
"participant_broker_numbers": [
{
"broker_ids": [7738, 7739],
"participant_name_cn": "华兴金融 (香港)",
"participant_name_en": "China Renaissance(HK)",
"participant_name_hk": "華興金融 (香港)"
},
{
"broker_ids": [6390, 6396, 6398, 6399],
"participant_name_cn": "国信 (香港)",
"participant_name_en": "Guosen(HK)",
"participant_name_hk": "國信 (香港)"
},
{
"broker_ids": [3168, 3169],
"participant_name_cn": "泰嘉",
"participant_name_en": "Tiger",
"participant_name_hk": "泰嘉"
}
]
}
```
## Error Code
| Proto Error Code | Business Error Code | Descrption | Troubleshooting Suggestions |
| ---------------- | ------------------- | ------------------ | ------------------------------------------------------------- |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
---
# Broker Queue
URL: https://open.longbridge.com/docs/quote/pull/brokers.md
:::warning Longbridge HK / SG accounts only
This method is available to Longbridge HK / SG accounts only. It works with any supported symbol, including US stocks.
:::
This API is used to obtain the real-time broker queue data of security.
# broker queue for Tencent (HK market only)
longbridge brokers 700.HK
# broker queue for Alibaba
longbridge brokers 9988.HK
:::info
[Business Command](../../socket/biz_command): `15`
:::
## Request
### Parameters
| Name | Type | Required | Description |
| ------ | ------ | -------- | --------------------------------------------------------------- |
| symbol | string | Yes | Security code, in `ticker.region` format, for example: `700.HK` |
### Protobuf
```protobuf
message SecurityRequest {
string symbol = 1;
}
```
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.brokers("700.HK")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.brokers("700.HK")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.brokers('700.HK')
console.log(resp.toString())
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id")
.build(url -> System.out.println("Open to authorize: " + url))
.get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
SecurityBrokers resp = ctx.getBrokers("700.HK").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.brokers("700.HK").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.brokers("700.HK", [](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
std::cout << "brokers: " << res->symbol << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
brokers, err := qctx.Brokers(context.Background(), "700.HK")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", brokers)
}
```
## Response
### Response Properties
| Name | Type | Description |
| ------------ | -------- | ------------------------------------------------------------------ |
| symbol | string | Security code |
| ask_brokers | object[] | Ask brokers |
| ∟ position | int32 | Position |
| ∟ broker_ids | int32[] | Broker IDs, obtained through the[Get Broker IDs ](./broker-ids)API |
| bid_brokers | object[] | Bid brokers |
| ∟ position | int32 | Postition |
| ∟ broker_ids | int32[] | Broker IDs, obtained through the[Get Broker IDs ](./broker-ids)API |
### Protobuf
```protobuf
message SecurityBrokersResponse {
string symbol = 1;
repeated Brokers ask_brokers = 2;
repeated Brokers bid_brokers = 3;
}
message Brokers {
int32 position = 1;
repeated int32 broker_ids = 2;
}
```
### Response JSON Example
```json
{
"symbol": "700.HK",
"ask_brokers": [
{
"position": 1,
"broker_ids": [7358, 9057, 9028, 7364]
},
{
"position": 2,
"broker_ids": [6968, 3448, 3348, 1049, 4973, 6997, 3448, 5465, 6997]
}
],
"bid_brokers": [
{
"position": 1,
"broker_ids": [6996, 5465, 8026, 8304, 4978]
},
{
"position": 2
}
]
}
```
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
| 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct |
| 7 | 301603 | No quotes | Security no quote |
| 7 | 301604 | No access | No access to security quote |
---
# Candlesticks
URL: https://open.longbridge.com/docs/quote/pull/candlestick.md
This API is used to obtain the candlestick data of security.
:::info
Note: This interface can only retrieve the last 1000 candlesticks. To obtain longer historical data, please visit the interface: Get Security History Candlesticks.
:::
# daily candlestick for Tesla (last 100 bars)
longbridge kline TSLA.US
# weekly candlestick for Apple
longbridge kline AAPL.US --period week
# last 20 daily bars for NVDA
longbridge kline NVDA.US --period day --count 20
:::info
[Business Command](../../socket/biz_command): `19`
:::
## Request
### Parameters
| Name | Type | Required | Description |
| ------------- | ------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` |
| period | int32 | Yes | Candlestick period, for example: `1000`, see [Period](../objects#period---candlestick-period) |
| count | int32 | Yes | Count of cancdlestick, for example: `100`
**Check rules:**
maximum count is `1000` |
| adjust_type | int32 | Yes | Adjustment type, for example: `0`, see [AdjustType](../objects#adjusttype---candlestick-adjustment-type) |
| trade_session | int32 | No | Trading session, 0: intraday, 100: All (pre, intraday, post, overnight)
Note: Overnight data is included free in US LV1, US stocks only; enable the `enable_overnight` parameter to receive it. |
### Protobuf
```protobuf
message SecurityCandlestickRequest {
string symbol = 1;
Period period = 2;
int32 count = 3;
AdjustType adjust_type = 4;
int32 trade_session = 5;
}
```
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, Period, AdjustType, TradeSessions, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
# Get intraday candlestick data for 700.HK
resp = ctx.candlesticks("700.HK", Period.Day, 10, AdjustType.NoAdjust)
print(resp)
# Get all candlestick data for 700.HK
resp = ctx.candlesticks("700.HK", Period.Day, 10, AdjustType.NoAdjust, trade_session=TradeSessions.All)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, Period, AdjustType, TradeSessions, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
# Get intraday candlestick data for 700.HK
resp = await ctx.candlesticks("700.HK", Period.Day, 10, AdjustType.NoAdjust)
print(resp)
# Get all candlestick data for 700.HK
resp = await ctx.candlesticks("700.HK", Period.Day, 10, AdjustType.NoAdjust, trade_session=TradeSessions.All)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth, Period, AdjustType, TradeSessions } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.candlesticks('700.HK', Period.Day, 10, AdjustType.NoAdjust, TradeSessions.Intraday)
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
Candlestick[] resp = ctx.getCandlesticks("700.HK", Period.Day, 10, AdjustType.NoAdjust, TradeSessions.Intraday).get();
for (Candlestick c : resp) System.out.println(c);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config, quote::{Period, AdjustType, TradeSessions}};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.candlesticks("700.HK", Period::Day, 10, AdjustType::NoAdjust, TradeSessions::Intraday).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.candlesticks("700.HK", Period::Day, 10, AdjustType::NoAdjust, TradeSessions::Intraday, [](auto res) {
if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; }
std::cout << "candlesticks: " << res->size() << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
sticks, err := qctx.Candlesticks(context.Background(), "700.HK", quote.PeriodDay, 10, quote.AdjustTypeNo)
if err != nil {
log.Fatal(err)
}
fmt.Println("candlesticks:", len(sticks))
}
```
## Response
### Response Properties
| Name | Type | Description |
| --------------- | -------- | ---------------------------------------------------------------------------- |
| symbol | string | Security code, for example: `AAPL.US` |
| candlesticks | object[] | Candlestick data |
| ∟ close | string | Close price |
| ∟ open | string | Open price |
| ∟ low | string | Low price |
| ∟ high | string | High price |
| ∟ volume | int64 | Volume |
| ∟ turnover | string | Turnover |
| ∟ timestamp | int64 | Timestamp |
| ∟ trade_session | int32 | Trade session, see [TradeSession](../objects#tradesession---trading-session) |
### Protobuf
```protobuf
message SecurityCandlestickResponse {
string symbol = 1;
repeated Candlestick candlesticks = 2;
}
message Candlestick {
string close = 1;
string open = 2;
string low = 3;
string high = 4;
int64 volume = 5;
string turnover = 6;
int64 timestamp = 7;
}
```
### Response JSON Example
```json
{
"symbol": "700.HK",
"candlesticks": [
{
"close": "362.000",
"open": "364.600",
"low": "361.600",
"high": "368.800",
"volume": 10853604,
"turnover": "3954556819.000",
"timestamp": 1650384000
},
{
"close": "348.000",
"open": "352.000",
"low": "343.000",
"high": "356.200",
"volume": 25738562,
"turnover": "8981529950.000",
"timestamp": 1650470400
},
{
"close": "340.600",
"open": "334.800",
"low": "334.200",
"high": "343.000",
"volume": 28031299,
"turnover": "9492674293.000",
"timestamp": 1650556800
},
{
"close": "327.400",
"open": "332.200",
"low": "325.200",
"high": "338.600",
"volume": 25788422,
"turnover": "8541441823.000",
"timestamp": 1650816000
},
{
"close": "335.800",
"open": "332.200",
"low": "330.600",
"high": "341.600",
"volume": 27288328,
"turnover": "9166022626.000",
"timestamp": 1650902400
}
]
}
```
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | ------------------------------ | ------------------------------------------------------------------------------ |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
| 7 | 301600 | Invalue request parameters | Please check the request parameter: `symbol`, `count`, `adjust_type`, `period` |
| 7 | 301603 | No quotes | Security no quote |
| 7 | 301604 | No access | No access to security quote |
| 7 | 301607 | Too many candlesticks requeted | Reduce the amount of candlestick in each request |
---
# Depth
URL: https://open.longbridge.com/docs/quote/pull/depth.md
This API is used to obtain the depth data of security.
# Level 2 order book for Tesla
longbridge depth TSLA.US
# Level 2 order book for Apple
longbridge depth AAPL.US
# Level 2 order book for Tencent (HK)
longbridge depth 700.HK
:::info
[Business Command](../../socket/biz_command): `14`
:::
## Request
### Parameters
| Name | Type | Required | Description |
| ------ | ------ | -------- | -------------------------------------------------------------- |
| symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` |
### Protobuf
```protobuf
message SecurityRequest {
string symbol = 1;
}
```
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.depth("700.HK")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.depth("700.HK")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.depth('700.HK')
console.log(resp.toString())
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id")
.build(url -> System.out.println("Open to authorize: " + url))
.get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
SecurityDepth resp = ctx.getDepth("700.HK").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.depth("700.HK").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.depth("700.HK", [](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
std::cout << "depth: " << res->symbol << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
depth, err := qctx.Depth(context.Background(), "700.HK")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", depth)
}
```
## Response
### Response Properties
| Name | Type | Description |
| ----------- | -------- | ---------------- |
| symbol | string | Security code |
| ask | object[] | Ask depth |
| ∟ position | int32 | Position |
| ∟ price | string | Price |
| ∟ volume | int64 | Volume |
| ∟ order_num | int64 | Number of orders |
| bid | object[] | Bid depth |
| ∟ position | int32 | Position |
| ∟ price | string | Price |
| ∟ volume | int64 | Volume |
| ∟ order_num | int64 | Number of orders |
### Protobuf
```protobuf
message SecurityDepthResponse {
string symbol = 1;
repeated Depth ask = 2;
repeated Depth bid = 3;
}
message Depth {
int32 position = 1;
string price = 2;
int64 volume = 3;
int64 order_num = 4;
}
```
### Response JSON Example
```json
{
"symbol": "700.HK",
"ask": [
{
"position": 1,
"price": "335.000",
"volume": 500,
"order_num": 1
},
{
"position": 2,
"price": "335.200",
"volume": 400,
"order_num": 1
},
{
"position": 3,
"price": "335.400",
"volume": 500,
"order_num": 2
},
{
"position": 4,
"price": "335.600",
"volume": 1200,
"order_num": 3
},
{
"position": 5,
"price": "335.800",
"volume": 14000,
"order_num": 8
}
],
"bid": [
{
"position": 1,
"price": "334.800",
"volume": 69400,
"order_num": 13
},
{
"position": 2,
"price": "334.600",
"volume": 266600,
"order_num": 27
},
{
"position": 3,
"price": "334.400",
"volume": 61300,
"order_num": 29
},
{
"position": 4,
"price": "334.200",
"volume": 125900,
"order_num": 31
},
{
"position": 5,
"price": "334.000",
"volume": 194600,
"order_num": 94
}
]
}
```
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
| 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct |
| 7 | 301603 | No quotes | Security no quote |
| 7 | 301604 | No access | No access to security quote |
---
# Historical Candlesticks
URL: https://open.longbridge.com/docs/quote/pull/history-candlestick.md
This API is used to obtain the history candlestick data of security.
# Q1 2025 daily bars
longbridge kline history TSLA.US --start 2025-01-01 --end 2025-03-31
# full year 2024 weekly bars
longbridge kline history AAPL.US --start 2024-01-01 --end 2024-12-31 --period week
# full year 2025 daily bars
longbridge kline history NVDA.US --start 2025-01-01 --end 2025-12-31
:::info
[Business Command](../../socket/biz_command): `27`
:::
## Request
### Parameters
| Name | Type | Required | Description |
| -------------- | ------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` |
| period | int32 | Yes | Candlestick period, for example: `1000`, see [Period](../objects#period---candlestick-period) |
| adjust_type | int32 | Yes | Adjustment type, for example: `0`, see [AdjustType](../objects#adjusttype---candlestick-adjustment-type) |
| query_type | int32 | Yes | Type of query
**Optional value:**
`1` - query by offset
`2` - query by date |
| date_request | object | No | Required when querying by date |
| ∟ start_date | string | No | Date of query begin, in `YYYYMMDD` format, for example: 20231016
**Parameter description:**
1. Leave both start_date and end_date blank: return the latest 1000 candlesticks;
2. Fill only start_date: return the candlesticks between start_date and the latest trading day. If there are more than 1000 candlesticks in this interval, the candlesticks close to start_date will be returned first;
3. Fill in only end_date: return end_date and the previous 1000 candlesticks;
4. Fill in both start_date and end_date: return candlesticks data within this interval. If there are more than 1000 candlesticks in the interval, the candlesticks close to end_date will be returned first. |
| ∟ end_date | string | No | Date of query end, in `YYYYMMDD` format, for example: 20231016 |
| offset_request | object | No | Required when querying by offset |
| ∟ direction | int32 | Yes | Query direction
**Optional value:**
`0` - query in the direction of historical data
`1` - query in the direction of latest data |
| ∟ date | string | No | Query date, in `YYYYMMDD` format, for example: 20231016. Default value: latest trading day of the underlying market. |
| ∟ minute | string | No | Query time, in `HHMM` format, for example: 09:35, only valid when querying minute-level data |
| ∟ count | int32 | No | Count of cancdlestick, valid range:`[1,1000]`. Default value: `10` |
| trade_session | int32 | No | Trading session, 0: intraday, 100: All (pre, intraday, post, overnight)
Note: Overnight data is included free in US LV1, US stocks only; enable the `enable_overnight` parameter to receive it. |
### Protobuf
```protobuf
message SecurityHistoryCandlestickRequest {
message OffsetQuery {
Direction direction = 1;
string date = 2;
string minute = 3;
int32 count = 4;
}
message DateQuery {
string start_date = 1;
string end_date = 2;
}
string symbol = 1;
Period period = 2;
AdjustType adjust_type = 3;
HistoryCandlestickQueryType query_type = 4;
OffsetQuery offset_request = 5;
DateQuery date_request = 6;
}
```
### Request Example
```python
from datetime import datetime, date
from longbridge.openapi import QuoteContext, Config, Period, AdjustType, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
# Query after 2023-01-01
resp = ctx.history_candlesticks_by_offset("700.HK", Period.Day, AdjustType.NoAdjust, True, 10, datetime(2023, 1, 1))
print(resp)
# Query before 2023-01-01
resp = ctx.history_candlesticks_by_offset("700.HK", Period.Day, AdjustType.NoAdjust, False, 10, datetime(2023, 1, 1))
print(resp)
# Query 2023-01-01 to 2023-02-01
resp = ctx.history_candlesticks_by_date("700.HK", Period.Day, AdjustType.NoAdjust, date(2023, 1, 1), date(2023, 2, 1))
print(resp)
```
```python
import asyncio
from datetime import datetime, date
from longbridge.openapi import AsyncQuoteContext, Config, Period, AdjustType, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
# Query after 2023-01-01
resp = await ctx.history_candlesticks_by_offset("700.HK", Period.Day, AdjustType.NoAdjust, True, 10, datetime(2023, 1, 1))
print(resp)
# Query before 2023-01-01
resp = await ctx.history_candlesticks_by_offset("700.HK", Period.Day, AdjustType.NoAdjust, False, 10, datetime(2023, 1, 1))
print(resp)
# Query 2023-01-01 to 2023-02-01
resp = await ctx.history_candlesticks_by_date("700.HK", Period.Day, AdjustType.NoAdjust, date(2023, 1, 1), date(2023, 2, 1))
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const {
Config,
QuoteContext,
OAuth,
Period,
AdjustType,
TradeSessions,
NaiveDatetime,
NaiveDate,
Time,
} = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const datetime = new NaiveDatetime(new NaiveDate(2023, 1, 1), new Time(0, 0, 0))
const resp = await ctx.historyCandlesticksByOffset(
'700.HK',
Period.Day,
AdjustType.NoAdjust,
true,
datetime,
10,
TradeSessions.Intraday
)
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
import java.time.LocalDateTime;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
Candlestick[] resp = ctx.getHistoryCandlesticksByOffset("700.HK", Period.Day, AdjustType.NoAdjust, true, LocalDateTime.of(2023, 1, 1, 0, 0), 10, TradeSessions.Intraday).get();
for (Candlestick c : resp) System.out.println(c);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config, quote::{Period, AdjustType, TradeSessions}};
use time::macros::datetime;
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let dt = datetime!(2023-01-01 00:00);
let resp = ctx.history_candlesticks_by_offset("700.HK", Period::Day, AdjustType::NoAdjust, true, Some(dt), 10, TradeSessions::Intraday).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.history_candlesticks_by_offset("700.HK", Period::Day, AdjustType::NoAdjust, true, std::nullopt, 10, TradeSessions::Intraday, [](auto res) {
if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; }
std::cout << "candlesticks: " << res->size() << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
dt := time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)
sticks, err := qctx.HistoryCandlesticksByOffset(context.Background(), "700.HK", quote.PeriodDay, quote.AdjustTypeNo, true, &dt, 10)
if err != nil {
log.Fatal(err)
}
fmt.Println("candlesticks:", len(sticks))
}
```
## Response
### Response Properties
| Name | Type | Description |
| --------------- | -------- | ---------------------------------------------------------------------------- |
| symbol | string | Security code, for example: `AAPL.US` |
| candlesticks | object[] | Candlestick data |
| ∟ close | string | Close price |
| ∟ open | string | Open price |
| ∟ low | string | Low price |
| ∟ high | string | High price |
| ∟ volume | int64 | Volume |
| ∟ turnover | string | Turnover |
| ∟ timestamp | int64 | Timestamp |
| ∟ trade_session | int32 | Trade session, see [TradeSession](../objects#tradesession---trading-session) |
### Protobuf
```protobuf
message SecurityCandlestickResponse {
string symbol = 1;
repeated Candlestick candlesticks = 2;
}
message Candlestick {
string close = 1;
string open = 2;
string low = 3;
string high = 4;
int64 volume = 5;
string turnover = 6;
int64 timestamp = 7;
}
```
### Response JSON Example
```json
{
"symbol": "700.HK",
"candlesticks": [
{
"close": "362.000",
"open": "364.600",
"low": "361.600",
"high": "368.800",
"volume": 10853604,
"turnover": "3954556819.000",
"timestamp": 1650384000
},
{
"close": "348.000",
"open": "352.000",
"low": "343.000",
"high": "356.200",
"volume": 25738562,
"turnover": "8981529950.000",
"timestamp": 1650470400
},
{
"close": "340.600",
"open": "334.800",
"low": "334.200",
"high": "343.000",
"volume": 28031299,
"turnover": "9492674293.000",
"timestamp": 1650556800
},
{
"close": "327.400",
"open": "332.200",
"low": "325.200",
"high": "338.600",
"volume": 25788422,
"turnover": "8541441823.000",
"timestamp": 1650816000
},
{
"close": "335.800",
"open": "332.200",
"low": "330.600",
"high": "341.600",
"volume": 27288328,
"turnover": "9166022626.000",
"timestamp": 1650902400
}
]
}
```
## Permission description
According to the user’s assets and transactions, the number of targets that different types of users can query historical data on each month is as follows:
- The quota is calculated based on the natural month. The quota is topped up at the beginning of each month. The remaining quota from the previous month will not be accumulated to this month. If you repeatedly request the historical K-line of the same target within a natural month, it will only be counted once.
- For newly deposited accounts, the limit will automatically take effect on the next trading day; when the account's total assets or number of transactions increase and reaches a higher level, the limit will take effect on the next trading day.
- Total assets: The total assets of the user's Hong Kong stocks, U.S. stocks, A-shares and other securities accounts are converted into Hong Kong dollars according to the exchange rate. Take the larger value of the user's total assets on the last trading day of the previous calendar month and the total assets on the most recent complete trading day.
- Number of transactions per month: The number of orders that the user has completed. Partial completion of one order, complete completion of multiple transactions, or all transactions at one time are counted as 1 transaction. Take the larger value of the user's number of transactions in the last natural month and the number of transactions in the current natural month.
User Type
The maximum number of targets that can be queried per month
User account opening
100
Total assets reach HKD 10,000
400
Total assets reach HKD 80,000
600
Total assets reach 400,000 HKD or the number of transactions per month is greater than 160
1000
Total assets reach 4 million HKD or the number of transactions per month is greater than 1,600
2000
Total assets reach 6 million HKD or the number of transactions per month is greater than 2,500
3000
## Description of historical candlesticks range
Market
Daily/Weekly/Monthly/Year period candlesticks
Minute candlesticks
Description
Hong Kong stocks
2004-06 to present
2008-11 to present
The available history length for minute candlesticks varies based on the user's total assets:
(1) Total assets < HKD 80,000: Up to 3 years of historical minute candlestick data is available. Calculated by calendar month — for example, if the current month is May 2026, data from May 2023 to present is accessible.
(2) Total assets ≥ HKD 80,000: Up to 8 years of historical minute candlestick data is available. Calculated by calendar month — for example, if the current month is May 2026, data from May 2018 to present is accessible. If less than 8 years of data exists, all available records from the earliest date will be returned.
For longer historical data coverage, please contact customer support.
U.S. stocks
2010-06 to present
2003-09 to present
A shares
1999-11 to present
2022-08 to present
U.S. stock options
-
-
U.S. stock options historical data is currently not supported, and data for longer periods will be released later
## Rate limite
:::caution
- The api can be requested up to 60 times every 30 seconds.
:::
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | -------------------------- | ----------------------------------------------------------------------------------------- |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
| 7 | 301600 | Invalue request parameters | Please check the request parameter: `symbol`, `count`, `adjust_type`, `period` |
| 7 | 301603 | No quotes | Security no quote |
| 7 | 301604 | No access | No access to security quote |
| 7 | 301607 | Permission limit | Exceeds the upper limit of the number of targets that can be queried in the current month |
---
# Intraday
URL: https://open.longbridge.com/docs/quote/pull/intraday.md
This API is used to obtain the intraday data of security.
# minute-by-minute intraday data for Tesla
longbridge intraday TSLA.US
# minute-by-minute intraday data for Apple
longbridge intraday AAPL.US
# minute-by-minute intraday data for Tencent
longbridge intraday 700.HK
:::info
[Business Command](../../socket/biz_command): `18`
:::
## Request
### Parameters
| Name | Type | Required | Description |
| ------ | ------ | -------- | -------------------------------------------------------------- |
| symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` |
### Protobuf
```protobuf
message SecurityIntradayRequest {
string symbol = 1;
}
```
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.intraday("700.HK")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.intraday("700.HK")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth, TradeSessions } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.intraday('700.HK', TradeSessions.Intraday)
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id")
.build(url -> System.out.println("Open to authorize: " + url))
.get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
IntradayLine[] resp = ctx.getIntraday("700.HK", TradeSessions.Intraday).get();
for (IntradayLine line : resp) System.out.println(line);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::{QuoteContext, TradeSessions}, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.intraday("700.HK", TradeSessions::Intraday).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.intraday("700.HK", TradeSessions::Intraday, [](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
std::cout << "intraday lines: " << res->size() << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
lines, err := qctx.Intraday(context.Background(), "700.HK")
if err != nil {
log.Fatal(err)
}
fmt.Println("intraday lines:", len(lines))
}
```
## Response
### Response Properties
| Name | Type | Description |
| ----------- | -------- | ------------------------------------- |
| symbol | string | Security code, for example: `AAPL.US` |
| lines | object[] | Intraday line data |
| ∟ price | string | Close price of the minute |
| ∟ timestamp | int64 | Start time stamp of the minute |
| ∟ volume | int64 | Volume |
| ∟ turnover | string | Turnover |
| ∟ avg_price | string | Average price |
### Protobuf
```
message SecurityIntradayResponse{
string symbol = 1;
repeated Line lines = 2;
}
message Line {
string price = 1;
int64 timestamp = 2;
int64 volume = 3;
string turnover = 4;
string avg_price = 5;
}
```
### Response JSON Example
```json
{
"symbol": "700.HK",
"lines": [
{
"price": "330.400",
"timestamp": 1651023000,
"volume": 375870,
"turnover": "123949699.000",
"avg_price": "329.767470"
},
{
"price": "331.200",
"timestamp": 1651023060,
"volume": 233095,
"turnover": "77269032.800",
"avg_price": "330.427416"
},
{
"price": "330.400",
"timestamp": 1651023120,
"volume": 192565,
"turnover": "63711556.000",
"avg_price": "330.530719"
},
{
"price": "330.800",
"timestamp": 1651023180,
"volume": 143397,
"turnover": "47471072.400",
"avg_price": "330.608989"
},
{
"price": "330.800",
"timestamp": 1651023240,
"volume": 141834,
"turnover": "46890605.600",
"avg_price": "330.608078"
}
]
}
```
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
| 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct |
| 7 | 301603 | No quotes | Security no quote |
| 7 | 301604 | No access | No access to security quote |
---
# Quotes
URL: https://open.longbridge.com/docs/quote/pull/quote.md
This API is used to obtain the real-time quotes of securities, and supports all types of securities. To view these real-time data streams aggregated into live indices, sector heatmaps, and macro market overviews, you can reference the [Longbridge Global Markets](https://longbridge.com/en/markets).
# real-time quote for Tesla
longbridge quote TSLA.US
# query multiple US stocks at once
longbridge quote AAPL.US NVDA.US
# mix US and HK stocks
longbridge quote TSLA.US 700.HK AAPL.US
:::info
[Business Command](../../socket/biz_command): `11`
:::
## Request
### Parameters
| Name | Type | Required | Description |
| ------ | -------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| symbol | string[] | Yes | Security code list, in `ticker.region` format, for example: `[700.HK]`
**Check rules:**
The maximum number of symbols in each request is `500` |
### Protobuf
```protobuf
message MultiSecurityRequest {
repeated string symbol = 1;
}
```
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.quote(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"])
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.quote(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"])
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.quote(['700.HK', 'AAPL.US', 'TSLA.US', 'NFLX.US'])
for (const obj of resp) {
console.log(obj.toString())
}
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id")
.build(url -> System.out.println("Open to authorize: " + url))
.get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
SecurityQuote[] resp = ctx.getQuote(new String[] { "700.HK", "AAPL.US", "TSLA.US", "NFLX.US" }).get();
for (SecurityQuote obj : resp) {
System.out.println(obj);
}
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.quote(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"]).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
std::vector symbols = {"700.HK", "AAPL.US", "TSLA.US", "NFLX.US"};
ctx.quote(symbols, [](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
for (const auto& it : *res) {
std::cout << it.symbol << " last_done=" << (double)it.last_done << std::endl;
}
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
quotes, err := qctx.Quote(context.Background(), []string{"700.HK", "AAPL.US", "TSLA.US", "NFLX.US"})
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", quotes[0])
}
```
## Response
### Response Properties
| Name | Type | Description |
| ------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| secu_quote | object[] | Securities quote |
| ∟ symbol | string | Security code |
| ∟ last_done | string | Latest price |
| ∟ prev_close | string | Yesterday's close |
| ∟ open | string | Open |
| ∟ high | string | High |
| ∟ low | string | Low |
| ∟ timestamp | int64 | Time of latest price |
| ∟ volume | int64 | Volume |
| ∟ turnover | string | Turnover |
| ∟ trade_status | int32 | Security trading status, see [TradeStatus](../objects#tradestatus---security-status) |
| ∟ pre_market_quote | object | Quote of US pre market |
| ∟∟ last_done | string | Latest price |
| ∟∟ timestamp | int64 | Time of latest price |
| ∟∟ volume | int64 | Volume |
| ∟∟ turnover | string | Turnover |
| ∟∟ high | string | High |
| ∟∟ low | string | Low |
| ∟∟ prev_close | string | Close of the last trade session |
| ∟ post_market_quote | object | Quote of US post market |
| ∟∟ last_done | string | Latest price |
| ∟∟ timestamp | int64 | Time of latest price |
| ∟∟ volume | int64 | Volume |
| ∟∟ turnover | string | Turnover |
| ∟∟ high | string | High |
| ∟∟ low | string | Low |
| ∟∟ prev_close | string | Close of the last trade session |
| ∟ over_night_quote | object | Quote of US overnight market
Note: Enable the `enable_overnight` parameter to receive it; returns null otherwise. (Overnight quotes are included free in US LV1, US stocks only.) |
| ∟∟ last_done | string | Latest price |
| ∟∟ timestamp | int64 | Time of latest price |
| ∟∟ volume | int64 | Volume |
| ∟∟ turnover | string | Turnover |
| ∟∟ high | string | High |
| ∟∟ low | string | Low |
| ∟∟ prev_close | string | Close of the last trade session |
### Protobuf
```protobuf
message SecurityQuoteResponse {
repeated SecurityQuote secu_quote = 1;
}
message SecurityQuote {
string symbol = 1;
string last_done = 2;
string prev_close = 3;
string open = 4;
string high = 5;
string low = 6;
int64 timestamp = 7;
int64 volume = 8;
string turnover = 9;
TradeStatus trade_status = 10;
PrePostQuote pre_market_quote = 11;
PrePostQuote post_market_quote = 12;
}
message PrePostQuote {
string last_done = 1;
int64 timestamp = 2;
int64 volume = 3;
string turnover = 4;
string high = 5;
string low = 6;
string prev_close = 7;
}
```
### Response JSON Example
```json
{
"secu_quote": [
{
"symbol": "700.HK",
"last_done": "338.000",
"prev_close": "334.800",
"open": "340.600",
"high": "340.600",
"low": "333.000",
"timestamp": 1651115955,
"volume": 7310881,
"turnover": "2461463161.000"
},
{
"symbol": "AAPL.US",
"last_done": "156.570",
"prev_close": "156.800",
"open": "155.910",
"high": "159.790",
"low": "155.380",
"timestamp": 1651089600,
"volume": 88063191,
"turnover": "13865092584.000",
"pre_market_quote": {
"last_done": "155.880",
"timestamp": 1651066201,
"volume": 1575504,
"turnover": "246653442.000",
"high": "158.400",
"low": "155.100",
"prev_close": "156.800"
},
"post_market_quote": {
"last_done": "158.770",
"timestamp": 1651103995,
"volume": 6188441,
"turnover": "970874184.759",
"high": "159.400",
"low": "156.400",
"prev_close": "156.570"
}
}
]
}
```
## API Restrictions
:::caution
- The HK stocks quotation beyond the 20th will be delayed if the quote level is BMP.
:::
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
| 7 | 301607 | Too many request symbols | Reduce the number of symbols in a request |
---
# Static Info
URL: https://open.longbridge.com/docs/quote/pull/static.md
This API is used to obtain the basic information of securities.
# static info for Tesla (name, lot size, shares, etc.)
longbridge static TSLA.US
# static info for multiple US stocks
longbridge static AAPL.US NVDA.US
# static info for US and HK stocks
longbridge static TSLA.US 700.HK
:::info
[Business Command](../../socket/biz_command): `10`
:::
## Request
### Parameters
| Name | Type | Required | Description |
| ------ | -------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| symbol | string[] | Yes | Security code list, in `ticker.region` format, for example: `[700.HK]`
**Check rules:**
The maximum number of symbols in each request is `500` |
### Protobuf
```protobuf
message MultiSecurityRequest {
repeated string symbol = 1;
}
```
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.static_info(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"])
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.static_info(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"])
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.staticInfo(['700.HK', 'AAPL.US', 'TSLA.US', 'NFLX.US'])
for (const obj of resp) {
console.log(obj.toString())
}
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id")
.build(url -> System.out.println("Open to authorize: " + url))
.get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
SecurityStaticInfo[] resp = ctx.getStaticInfo(new String[] { "700.HK", "AAPL.US", "TSLA.US", "NFLX.US" }).get();
for (SecurityStaticInfo obj : resp) {
System.out.println(obj);
}
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.static_info(["700.HK", "AAPL.US", "TSLA.US", "NFLX.US"]).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
std::vector symbols = {"700.HK", "AAPL.US", "TSLA.US", "NFLX.US"};
ctx.static_info(symbols, [](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
for (const auto& obj : *res) {
std::cout << obj.symbol << " " << obj.name_cn << " " << obj.name_en << std::endl;
}
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
infos, err := qctx.StaticInfo(context.Background(), []string{"700.HK", "AAPL.US", "TSLA.US", "NFLX.US"})
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", infos[0])
}
```
## Response
### Response Properties
| Name | Type | Description |
| -------------------- | -------- | ---------------------------------------------------------------------------------------------------- |
| secu_static_info | object[] | Securities Basic Information |
| ∟ symbol | string | Security code |
| ∟ name_cn | string | Security name (zh-CN) |
| ∟ name_en | string | Security name (en) |
| ∟ name_hk | string | Security name (zh-HK) |
| ∟ exchange | string | Exchange which the security belongs to |
| ∟ currency | string | Trading currency
**Optional value: **
`CNY`
`USD`
`SGD`
`HKD` |
| ∟ lot_size | int32 | Lot size |
| ∟ total_shares | int64 | Total shares |
| ∟ circulating_shares | int64 | Circulating shares |
| ∟ hk_shares | int64 | HK shares (only HK stocks) |
| ∟ eps | string | Earnings per share |
| ∟ eps_ttm | string | Earnings per share (TTM) |
| ∟ bps | string | Net assets per share |
| ∟ dividend_yield | string | Dividend yield |
| ∟ stock_derivatives | int32[] | Types of supported derivatives
**Optional value:**
`1` - Option
`2` - Warrant |
| ∟ board | string | The board to whitch the security belongs, see [Board](../objects#board---security-board) for details |
### Protobuf
```protobuf
message SecurityStaticInfoResponse {
repeated StaticInfo secu_static_info = 1;
}
message StaticInfo {
string symbol = 1;
string name_cn = 2;
string name_en = 3;
string name_hk = 4;
string listing_date = 5;
string exchange = 6;
string currency = 7;
int32 lot_size = 8;
int64 total_shares = 9;
int64 circulating_shares = 10;
int64 hk_shares = 11;
string eps = 12;
string eps_ttm = 13;
string bps = 14;
string dividend_yield = 15;
repeated int32 stock_derivatives = 16;
string board = 17;
}
```
### Response JSON Example
```json
{
"secu_static_info": [
{
"symbol": "700.HK",
"name_cn": "腾讯控股",
"name_en": "TENCENT",
"name_hk": "騰訊控股",
"exchange": "SEHK",
"currency": "HKD",
"lot_size": 100,
"total_shares": 9612464038,
"circulating_shares": 9612464038,
"hk_shares": 9612464038,
"eps": "28.4394",
"eps_ttm": "28.4394",
"bps": "103.40413",
"dividend_yield": "1.6",
"stock_derivatives": [2],
"board": "HKEquity"
},
{
"symbol": "AAPL.US",
"name_cn": "苹果",
"name_en": "Apple Inc.",
"exchange": "NASD",
"currency": "USD",
"lot_size": 1,
"total_shares": 1631944100,
"circulating_shares": 16302661350,
"eps": "5.669",
"eps_ttm": "6.0771",
"bps": "4.40197",
"dividend_yield": "0.85",
"stock_derivatives": [1],
"board": "USMain"
}
]
}
```
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
| 7 | 301607 | Too many request symbols | Reduce the number of symbols in a request |
---
# Trades
URL: https://open.longbridge.com/docs/quote/pull/trade.md
This API is used to obtain the trades data of security.
# recent tick-by-tick trades for Tesla
longbridge trades TSLA.US
# recent tick-by-tick trades for Apple
longbridge trades AAPL.US
# recent tick-by-tick trades for NVDA
longbridge trades NVDA.US
:::info
[Business Command](../../socket/biz_command): `17`
:::
## Request
### Parameters
| Name | Type | Required | Description |
| ------ | ------ | -------- | -------------------------------------------------------------------------------------------------------- |
| symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` |
| count | int32 | Yes | Count of trades
**Check rules:**
The maximum number of trades in each request is `1000` |
### Protobuf
```protobuf
message SecurityTradeRequest {
string symbol = 1;
int32 count = 2;
}
```
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.trades("700.HK", 10)
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.trades("700.HK", 10)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.trades('700.HK', 10)
for (const obj of resp) {
console.log(obj.toString())
}
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id")
.build(url -> System.out.println("Open to authorize: " + url))
.get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
Trade[] resp = ctx.getTrades("700.HK", 10).get();
for (Trade obj : resp) {
System.out.println(obj);
}
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.trades("700.HK", 10).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.trades("700.HK", 10, [](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
for (const auto& t : *res) {
std::cout << t.price << " " << t.quantity << std::endl;
}
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
trades, err := qctx.Trades(context.Background(), "700.HK", 10)
if err != nil {
log.Fatal(err)
}
for _, t := range trades {
fmt.Println(t.Price, t.Volume)
}
}
```
## Response
### Response Properties
| Name | Type | Description |
| --------------- | -------- | ------------------------------------------------------------------------------------------------ |
| symbol | string | Security code |
| trades | object[] | Trades data |
| ∟ price | string | Price |
| ∟ volume | int64 | Volume |
| ∟ timestamp | int64 | Time of trading |
| ∟ trade_type | string | [Trade type](#trade-type) |
| ∟ direction | int32 | Trade direction
**Optional value:**
`0` - neutral
`1` - down
`2` - up |
| ∟ trade_session | int32 | Trade session, see [TradeSession](../objects#tradesession---trading-session) |
#### Trade Type
HK
- `*` - Overseas trade
- `D` - Odd-lot trade
- `M` - Non-direct off-exchange trade
- `P` - Late trade (Off-exchange previous day)
- `U` - Auction trade
- `X` - Direct off-exchange trade
- `Y` - Automatch internalized
- ` ` - Automatch normal
US
- ` ` - Regular sale
- `A` - Acquisition
- `B` - Bunched trade
- `D` - Distribution
- `F` - Intermarket sweep
- `G` - Bunched sold trades
- `H` - Price variation trade
- `I` - Odd lot trade
- `K` - Rule 155 trde(NYSE MKT)
- `M` - Market center close price
- `P` - Prior reference price
- `Q` - Market center open price
- `S` - Split trade
- `V` - Contingent trade
- `W` - Average price trade
- `X` - Cross trade
- `1` - Stopped stock(Regular trade)
### Protobuf
```protobuf
message SecurityTradeResponse {
string symbol = 1;
repeated Trade trades = 2;
}
message Trade {
string price = 1;
int64 volume = 2;
int64 timestamp = 3;
string trade_type = 4;
int32 direction = 5;
TradeSession trade_session = 6;
}
```
### Response JSON Example
```json
{
"symbol": "AAPL.US",
"trades": [
{
"price": "158.760",
"volume": 1,
"timestamp": 1651103979,
"trade_type": "I",
"direction": 0,
"trade_session": 2
},
{
"price": "158.745",
"volume": 1,
"timestamp": 1651103985,
"trade_type": "I",
"direction": 0,
"trade_session": 2
},
{
"price": "158.800",
"volume": 1,
"timestamp": 1651103995,
"trade_type": "I",
"direction": 0,
"trade_session": 2
}
]
}
```
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
| 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct |
| 7 | 301603 | No quotes | Security no quote |
| 7 | 301604 | No access | No access to security quote |
| 7 | 301607 | Too many trades requeted | Reduce the amount of trades in each request |
---
# Brokers
URL: https://open.longbridge.com/docs/quote/push/broker.md
:::warning Longbridge HK / SG accounts only
This method is available to Longbridge HK / SG accounts only. It works with any supported symbol, including US stocks.
:::
Real-time brokers data push of the subscribed security.
:::info
[Business Command](../../socket/protocol/push): `103`
:::
## Data Format
### Properties
| Name | Type | Description |
|--------------|----------|---------------------------------------|
| symbol | string | Security code, for example: `AAPL.US` |
| sequence | int64 | Sequence number |
| ask_brokers | object[] | Ask brokers |
| ∟ position | int32 | Position |
| ∟ broker_ids | int32[] | [Broker ID](../pull/broker-ids) |
| bid_brokers | object[] | Bid brokers |
| ∟ position | int32 | Position |
| ∟ broker_ids | int32[] | [Broker ID](../pull/broker-ids) |
### Protobuf
```protobuf
message PushBrokers {
string symbol = 1;
int64 sequence = 2;
repeated Brokers ask_brokers = 3;
repeated Brokers bid_brokers = 4;
}
message Brokers {
int32 position = 1;
repeated int32 broker_ids = 2;
}
```
### Example
```python
from time import sleep
from longbridge.openapi import QuoteContext, Config, SubType, PushBrokers, OAuthBuilder
def on_brokers(symbol: str, event: PushBrokers):
print(symbol, event)
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.set_on_brokers(on_brokers)
ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Brokers])
sleep(30)
```
### JSON Example
```json
{
"symbol": "700.HK",
"sequence": 160808750000000,
"ask_brokers": [
{
"position": 1,
"broker_ids": [7358, 9057, 9028, 7364]
},
{
"position": 2,
"broker_ids": [6968, 3448, 3348, 1049, 4973, 6997, 3448, 5465, 6997]
}
],
"bid_brokers": [
{
"position": 1,
"broker_ids": [6996, 5465, 8026, 8304, 4978]
},
{
"position": 2,
"broker_ids": [7358, 9057, 9028, 7364]
}
]
}
```
---
# Candlesticks
URL: https://open.longbridge.com/docs/quote/push/candlestick.md
Real-time candlestick (K-line) data push for subscribed securities. The callback fires whenever the current candlestick updates (Realtime mode) or when a candlestick period closes (Confirmed mode).
:::tip
This page covers the **push** API (`subscribe_candlesticks`). To pull historical candlestick data on demand, see [Candlestick - Pull](/docs/quote/pull/candlestick).
:::
:::info
[Business Command](../../socket/protocol/push): `105`
:::
## Data Format
### Properties
| Name | Type | Description |
|---------------------|----------|------------------------------------------------------------------------------------------|
| symbol | string | Security code, for example: `AAPL.US` |
| period | int32 | Candlestick period, see [Period](../objects#period---candlestick-period) |
| candlestick | object | Candlestick data |
| ∟ close | string | Close price |
| ∟ open | string | Open price |
| ∟ high | string | High price |
| ∟ low | string | Low price |
| ∟ volume | int64 | Volume |
| ∟ turnover | string | Turnover |
| ∟ timestamp | int64 | Candlestick time (Unix timestamp) |
| ∟ trade_session | int32 | Trade session, see [TradeSession](../objects#tradesession---trading-session) |
### Protobuf
```protobuf
message PushCandlestick {
string symbol = 1;
Period period = 2;
Candlestick candlestick = 3;
}
message Candlestick {
string close = 1;
string open = 2;
string high = 3;
string low = 4;
int64 volume = 5;
string turnover = 6;
int64 timestamp = 7;
TradeSession trade_session = 8;
}
```
### Example
```python
from time import sleep
from longbridge.openapi import QuoteContext, Config, Period, PushCandlestick, OAuthBuilder
def on_candlestick(symbol: str, event: PushCandlestick):
print(symbol, event)
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.set_on_candlestick(on_candlestick)
ctx.subscribe_candlesticks("700.HK", Period.Min_1)
sleep(30)
```
### JSON Example
```json
{
"symbol": "700.HK",
"period": 1,
"candlestick": {
"close": "162.500",
"open": "160.000",
"high": "163.000",
"low": "159.800",
"volume": 123456,
"turnover": "19987654.000",
"timestamp": 1651103700,
"trade_session": 0
}
}
```
---
# Depth
URL: https://open.longbridge.com/docs/quote/push/depth.md
Real-time depth data push of the subscribed security.
:::info
[Business Command](../../socket/protocol/push): `102`
:::
## Data Format
### Properties
| Name | Type | Description |
|-------------|----------|---------------------------------------|
| symbol | string | Security code, for example: `AAPL.US` |
| sequence | int64 | Sequence number |
| ask | object[] | Ask depth |
| ∟ position | int32 | Position |
| ∟ price | string | Price |
| ∟ volume | int64 | Volume |
| ∟ order_num | int64 | Number of orders |
| bid | object[] | Bid depth |
| ∟ position | int32 | Position |
| ∟ price | string | Price |
| ∟ volume | int64 | Volume |
| ∟ order_num | int64 | Number of orders |
### Protobuf
```protobuf
message PushDepth {
string symbol = 1;
int64 sequence = 2;
repeated Depth ask = 3;
repeated Depth bid = 4;
}
message Depth {
int32 position = 1;
string price = 2;
int64 volume = 3;
int64 order_num = 4;
}
```
### Example
```python
from time import sleep
from longbridge.openapi import QuoteContext, Config, SubType, PushDepth, OAuthBuilder
def on_depth(symbol: str, event: PushDepth):
print(symbol, event)
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.set_on_depth(on_depth)
ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Depth])
sleep(30)
```
### JSON Example
```json
{
"symbol": "700.HK",
"sequence": 160808750000000,
"ask": [
{
"position": 1,
"price": "335.000",
"volume": 500,
"order_num": 1
},
{
"position": 2,
"price": "335.200",
"volume": 400,
"order_num": 1
},
{
"position": 3,
"price": "335.400",
"volume": 500,
"order_num": 2
},
{
"position": 4,
"price": "335.600",
"volume": 1200,
"order_num": 3
},
{
"position": 5,
"price": "335.800",
"volume": 14000,
"order_num": 8
}
],
"bid": [
{
"position": 1,
"price": "334.800",
"volume": 69400,
"order_num": 13
},
{
"position": 2,
"price": "334.600",
"volume": 266600,
"order_num": 27
},
{
"position": 3,
"price": "334.400",
"volume": 61300,
"order_num": 29
},
{
"position": 4,
"price": "334.200",
"volume": 125900,
"order_num": 31
},
{
"position": 5,
"price": "334.000",
"volume": 194600,
"order_num": 94
}
]
}
```
---
# Overview
URL: https://open.longbridge.com/docs/quote/subscribe/overview.md
Streaming provides real-time market data via WebSocket subscriptions. Instead of polling, you subscribe to specific securities and data types, and the server pushes updates to your connection as they happen.
## How It Works
1. **Establish a connection** — Connect to the Longbridge WebSocket endpoint using the SDK or the [binary protocol](../../socket/protocol/overview).
2. **Subscribe** — Call [Subscribe](./subscribe) with the securities and data types you want (quotes, depth, trades, brokers).
3. **Receive pushes** — The server sends real-time updates to your connection whenever there is a market change.
4. **Unsubscribe** — Call [Unsubscribe](./unsubscribe) to stop receiving updates for specific symbols or data types.
## Subscription Types
| Type | Description |
|------|-------------|
| `Quote` | Real-time bid/ask and last-done price |
| `Depth` | Level 2 order book |
| `Brokers` | Broker queue data |
| `Trade` | Real-time trade ticks |
## Pull vs. Subscribe
Subscriptions push incremental updates in real time. For one-off or on-demand queries, use the pull APIs instead:
| Data | Pull API |
|------|----------|
| Quotes | [Quotes](/docs/quote/pull/quote) |
| Depth | [Depth](/docs/quote/pull/depth) |
| Broker queue | [Broker Queue](/docs/quote/pull/brokers) |
| Trades | [Trades](/docs/quote/pull/trade) |
| Intraday | [Intraday](/docs/quote/pull/intraday) |
| Candlesticks | [Candlesticks](/docs/quote/pull/candlestick) |
## Notes
- Subscriptions are scoped to the current connection; they are cleared when the connection drops.
- Use [Get Subscriptions](./subscription) to inspect your active subscriptions at any time.
- Quote permissions determine which data types are available. See [Quote Permission Levels](../overview#quote-permission-levels).
---
# Quote
URL: https://open.longbridge.com/docs/quote/push/quote.md
Real-time quote push of the subscribed security. In the pushed data structure, only the fields that have changed will be filled with data.
:::info
[Business Command](../../socket/protocol/push): `101`
:::
## Data Format
### Properties
| Name | Type | Description |
| ---------------- | ------ | --------------------------------------------------------------------------------------------------------------- |
| symbol | string | Security code, for example: `AAPL.US` |
| sequence | int64 | Sequence number |
| last_done | string | Latest price |
| open | string | Open |
| high | string | High |
| low | string | Low |
| timestamp | int64 | Time of latest price |
| volume | int64 | Volume |
| turnover | string | Turnover |
| trade_status | int32 | Security trading status, see [TradeStatus](../objects#tradestatus---security-status) |
| trade_session | int32 | Trade session, see [TradeSession](../objects#tradesession---trading-session) |
| current_volume | int32 | Increase volume between pushes |
| current_turnover | string | Increase turnover between pushes |
| tag | int32 | Price tag
**Optional value:**
`0` - Real-time quote
`1` - Revised data after market close |
### Protobuf
```protobuf
message PushQuote {
string symbol = 1;
int64 sequence = 2;
string last_done = 3;
string open = 4;
string high = 5;
string low = 6;
int64 timestamp = 7;
int64 volume = 8;
string turnover = 9;
TradeStatus trade_status = 10;
TradeSession trade_session = 11;
}
```
### Example
```python
from time import sleep
from longbridge.openapi import QuoteContext, Config, SubType, PushQuote, OAuthBuilder
def on_quote(symbol: str, event: PushQuote):
print(symbol, event)
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.set_on_quote(on_quote)
ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote], is_first_push=True)
sleep(30)
```
### JSON Example
```json
{
"symbol": "AAPL.US",
"sequence": 160808750000000,
"last_done": "156.570",
"open": "155.910",
"high": "159.790",
"low": "155.380",
"timestamp": 1651089600,
"volume": 88063191,
"turnover": "13865092584.000",
"trade_status": 0,
"trade_session": 0,
"current_volume": 111234,
"current_turnover": "23234343454.000",
"tag": 0
}
```
---
# Get Subscriptions
URL: https://open.longbridge.com/docs/quote/subscribe/subscription.md
This API is used to obtain the subscription information.
# list active real-time WebSocket subscriptions
longbridge subscriptions
:::info
[Business Command](../../socket/biz_command): `5`
:::
## Request
### Protobuf
```protobuf
message SubscriptionRequest {
}
```
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, SubType, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote])
resp = ctx.subscriptions()
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, SubType, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote])
resp = await ctx.subscriptions()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.subscriptions()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
Subscription[] resp = ctx.getSubscriptions().get();
for (Subscription s : resp) System.out.println(s);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.subscriptions().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.subscriptions([](auto res) {
if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; }
for (const auto& s : *res) std::cout << s.symbol << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
subs, err := qctx.Subscriptions(context.Background())
if err != nil {
log.Fatal(err)
}
for symbol := range subs {
fmt.Println(symbol)
}
}
```
## Response
### Response Properties
| Name | Type | Description |
| ---------- | -------- | --------------------------------------------------------------------------------- |
| sub_list | object[] | Subscribed data |
| ∟ symbol | string | Security code |
| ∟ sub_type | []int32 | Subscription type, see [SubType](../objects#subtype---quote-type-of-subscription) |
### Protobuf
```protobuf
message SubscriptionResponse {
repeated SubTypeList sub_list = 1;
}
message SubTypeList {
string symbol = 1;
repeated SubType sub_type = 2;
}
```
### Response JSON Example
```json
{
"sub_list": [
{
"symbol": "700.HK",
"sub_type": [1, 2, 3]
},
{
"symbol": "AAPL.US",
"sub_type": [2]
}
]
}
```
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
---
# Subscribe Quote
URL: https://open.longbridge.com/docs/quote/subscribe/subscribe.md
This API is used to subscribe quote.
:::info
[Business Command](../../socket/biz_command): `6`
:::
## Request
### Parameters
| Name | Type | Required | Description |
| ------------- | -------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| symbol | string[] | Yes | Security code list, for example: `[700.HK]`
**Check rules:**
The maximum number of symbols that can be passed in each request is `500`
The maximum number of subscriptions per user is `500` |
| sub_type | int32[] | Yes | Subscription type, for example: `[1,2]`, see [SubType](../objects#subtype---quote-type-of-subscription) |
| is_first_push | bool | Yes | Whether to perform a data push immediately after subscribing. (trade not supported) |
### Protobuf
```protobuf
message SubscribeRequest {
repeated string symbol = 1;
repeated SubType sub_type = 2;
bool is_first_push = 3;
}
```
### Request Example
```python
from time import sleep
from longbridge.openapi import QuoteContext, Config, SubType, PushQuote, OAuthBuilder
def on_quote(symbol: str, event: PushQuote):
print(symbol, event)
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.set_on_quote(on_quote)
ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote])
sleep(30)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, SubType, PushQuote, OAuthBuilder
async def main() -> None:
async def on_quote(symbol: str, event: PushQuote) -> None:
print(symbol, event)
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
ctx.set_on_quote(on_quote)
await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote])
await asyncio.sleep(30)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth, SubType } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
ctx.setOnQuote((event) => console.log(event))
await ctx.subscribe(['700.HK', 'AAPL.US'], [SubType.Quote], true)
await new Promise((r) => setTimeout(r, 30000))
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
ctx.setOnQuote(event -> System.out.println(event));
ctx.subscribe(new String[] { "700.HK", "AAPL.US" }, new SubType[] { SubType.Quote }, true).get();
Thread.sleep(30000);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config, quote::SubFlags};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
ctx.subscribe(vec!["700.HK".to_string(), "AAPL.US".to_string()], SubFlags::quote(), true).await?;
tokio::time::sleep(std::time::Duration::from_secs(30)).await;
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.set_on_quote([](auto e) { std::cout << e->symbol << std::endl; });
ctx.subscribe(symbols, SubFlags::QUOTE(), true, [](auto res) {
if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; }
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
qctx.OnQuote(func(e *quote.PushQuote) { fmt.Println(e.Symbol) })
err = qctx.Subscribe(context.Background(), []string{"700.HK", "AAPL.US"}, []quote.SubType{quote.SubTypeQuote}, true)
if err != nil {
log.Fatal(err)
}
// keep running to receive push
select {}
}
```
## Response
### Response Properties
Returns the securities and types of the successful subscription of this request.
| Name | Type | Description |
| ---------- | -------- | --------------------------------------------------------------------------------- |
| sub_list | object[] | Subscription list |
| ∟ symbol | string | Seurity code |
| ∟ sub_type | int32[] | Subscription type, see [SubType](../objects#subtype---quote-type-of-subscription) |
### Protobuf
```protobuf
message SubscriptionResponse {
repeated SubTypeList sub_list = 1;
}
message SubTypeList {
string symbol = 1;
repeated SubType sub_type = 2;
}
```
### Response JSON Example
```json
{
"sub_list": [
{
"symbol": "700.HK",
"sub_type": [1, 2, 3]
},
{
"symbol": "AAPL.US",
"sub_type": [2]
}
]
}
```
## API Restrictions
:::caution
- HK BMP quote level does not support quote push.
:::
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | -------------------------- | ------------------------------------------------------------- |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
| 7 | 301605 | Too many subscriptons | Unsubscribe some subscribed securities |
| 7 | 301600 | Invalue request parameters | Please check the request parameter: `sub_type` |
---
# Trades
URL: https://open.longbridge.com/docs/quote/push/trade.md
Real-time trades data push of the subscribed security.
:::info
[Business Command](../../socket/protocol/push): `104`
:::
## Data Format
### Properties
| Name | Type | Description |
|-----------------|----------|--------------------------------------------------------------------------------------------------|
| symbol | string | Security code, for example: `AAPL.US` |
| sequence | int64 | Sequence number |
| trades | object[] | Trades data |
| ∟ price | string | Price |
| ∟ volume | int64 | Volume |
| ∟ timestamp | int64 | Time of trading |
| ∟ trade_type | string | [Trade type](#trade-type) |
| ∟ direction | int32 | Trade direction
**Optional value:**
`0` - neutral
`1` - down
`2` - up |
| ∟ trade_session | int32 | Trade session, see [TradeSession](../objects#tradesession---trading-session) |
#### Trade Type
HK
- `*` - Overseas trade
- `D` - Odd-lot trade
- `M` - Non-direct off-exchange trade
- `P` - Late trade (Off-exchange previous day)
- `U` - Auction trade
- `X` - Direct off-exchange trade
- `Y` - Automatch internalized
- ` ` - Automatch normal
US
- ` ` - Regular sale
- `A` - Acquisition
- `B` - Bunched trade
- `D` - Distribution
- `F` - Intermarket sweep
- `G` - Bunched sold trades
- `H` - Price variation trade
- `I` - Odd lot trade
- `K` - Rule 155 trde(NYSE MKT)
- `M` - Market center close price
- `P` - Prior reference price
- `Q` - Market center open price
- `S` - Split trade
- `V` - Contingent trade
- `W` - Average price trade
- `X` - Cross trade
- `1` - Stopped stock(Regular trade)
### Protobuf
```protobuf
message PushTrade {
string symbol = 1;
int64 sequence = 2;
repeated Trade trade = 3;
}
message Trade {
string price = 1;
int64 volume = 2;
int64 timestamp = 3;
string trade_type = 4;
int32 direction = 5;
TradeSession trade_session = 6;
}
```
### Example
```python
from time import sleep
from longbridge.openapi import QuoteContext, Config, SubType, PushTrades, OAuthBuilder
def on_trades(symbol: str, event: PushTrades):
print(symbol, event)
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.set_on_trades(on_trades)
ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Trade])
sleep(30)
```
### JSON Example
```json
{
"symbol": "700.HK",
"sequence": 160808750000000,
"trades": [
{
"price": "158.760",
"volume": 1,
"timestamp": 1651103979,
"trade_type": "I",
"direction": 0,
"trade_session": 2
},
{
"price": "158.745",
"volume": 1,
"timestamp": 1651103985,
"trade_type": "I",
"direction": 0,
"trade_session": 2
},
{
"price": "158.800",
"volume": 1,
"timestamp": 1651103995,
"trade_type": "I",
"direction": 0,
"trade_session": 2
}
]
}
```
---
# Unsubscribe
URL: https://open.longbridge.com/docs/quote/subscribe/unsubscribe.md
This API is used to unsubscribe quote.
:::info
[Business Command](../../socket/biz_command): `7`
:::
## Request
### Parameters
| Name | Type | Required | Description |
| --------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| symbol | string[] | Yes | Security code list, for example: `[700.HK]`
**Check rules:**
The maximum number of symbols that can be passed in each request is `500` |
| sub_type | int32[] | Yes | Subscription type list, for example: `[1,2]`, see [SubType](../objects#subtype---quote-type-of-subscription) |
| unsub_all | bool | Yes | Is unsubscribe all.
- When `symbol` is empty, unsubscribe all subscriptions
- When `symbol` is not empty, unsubscribe these all subscriptions of these symbols |
### Protobuf
```protobuf
message UnsubscribeRequest {
repeated string symbol = 1;
repeated SubType sub_type = 2;
bool unsub_all = 3;
}
```
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, SubType, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote])
ctx.unsubscribe(["AAPL.US"], [SubType.Quote])
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, SubType, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
await ctx.subscribe(["700.HK", "AAPL.US"], [SubType.Quote])
await ctx.unsubscribe(["AAPL.US"], [SubType.Quote])
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth, SubType } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
await ctx.unsubscribe(['700.HK', 'AAPL.US'], [SubType.Quote])
console.log('unsubscribed')
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
ctx.unsubscribe(new String[] { "700.HK", "AAPL.US" }, new SubType[] { SubType.Quote }).get();
System.out.println("unsubscribed");
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config, quote::SubFlags};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
ctx.unsubscribe(vec!["700.HK".to_string(), "AAPL.US".to_string()], SubFlags::quote()).await?;
println!("unsubscribed");
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.unsubscribe(symbols, SubFlags::QUOTE(), [](auto res) {
if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; }
std::cout << "unsubscribed" << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
err = qctx.Unsubscribe(context.Background(), false, []string{"700.HK", "AAPL.US"}, []quote.SubType{quote.SubTypeQuote})
if err != nil {
log.Fatal(err)
}
fmt.Println("unsubscribed")
}
```
## Response
### Protobuf
```protobuf
message UnsubscribeResponse{
}
```
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | -------------------------- | ------------------------------------------------------------- |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
| 7 | 301600 | Invalue request parameters | Please check the request parameter: `sub_type` |
---
# Issuers
URL: https://open.longbridge.com/docs/quote/pull/issuer.md
This API is used to obtain the warrant issuer IDs data (which can be synchronized once a day).
# list all warrant issuers in the HK market
longbridge warrant issuers
:::info
[Business Command](../../socket/biz_command): `22`
:::
## Request
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.warrant_issuers()
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.warrant_issuers()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.warrantIssuers()
for (const obj of resp) {
console.log(obj.toString())
}
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id")
.build(url -> System.out.println("Open to authorize: " + url))
.get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
IssuerInfo[] resp = ctx.getWarrantIssuers().get();
for (IssuerInfo obj : resp) {
System.out.println(obj);
}
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.warrant_issuers().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.warrant_issuers([](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
for (const auto& i : *res) {
std::cout << i.id << " " << i.name_cn << " " << i.name_en << std::endl;
}
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
issuers, err := qctx.WarrantIssuers(context.Background())
if err != nil {
log.Fatal(err)
}
for _, i := range issuers {
fmt.Println(i.Id, i.NameCn, i.NameEn)
}
}
```
## Response
### Parameters
| Name | Type | Description |
| ----------- | -------- | ------------------- |
| issuer_info | object[] | Issuer information |
| ∟ id | int32 | Issuer ID |
| ∟ name_cn | string | Issuer Name (zh-CN) |
| ∟ name_en | string | Issuer Name (en) |
| ∟ name_hk | string | Issuer Name (zh-HK) |
### Protobuf
```protobuf
message IssuerInfoResponse {
repeated IssuerInfo issuer_info = 1;
}
message IssuerInfo {
int32 id = 1;
string name_cn = 2;
string name_en = 3;
string name_hk = 4;
}
```
### Response JSON Example
```json
{
"issuer_info": [
{
"id": 15,
"name_cn": "瑞银",
"name_en": "UB",
"name_hk": "瑞銀"
},
{
"id": 14,
"name_cn": "汇丰",
"name_en": "HS",
"name_hk": "滙豐"
},
{
"id": 12,
"name_cn": "花旗",
"name_en": "CT",
"name_hk": "花旗"
}
]
}
```
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | ------------------ | ------------------------------------------------------------- |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
---
# Screener
URL: https://open.longbridge.com/docs/quote/pull/warrant-filter.md
This API is used to obtain the quotes of HK warrants, and supports sorting and filtering.
# list warrants linked to Tencent
longbridge warrant list 700.HK
# list warrants linked to Alibaba
longbridge warrant list 9988.HK
# list warrants linked to JD.com
longbridge warrant list 9618.HK
:::info
[Business Command](../../socket/biz_command): `23`
:::
## Request
### Parameters
| Name | Type | Required | Description |
| ------------- | ------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| symbol | string | Yes | Security code, in `ticker.region` format, for example:`700.HK` |
| filter_config | object | Yes | Filter conditions |
| ∟ sort_by | int32 | Yes | Which data to sort by, for example: `0`, see the `OrderSequence` field of the response data for the sequence number. |
| ∟ sort_order | int32 | Yes | Order, for example: `1`
**Optional value:**
`0` - Ascending
`1` - Descending |
| ∟ sort_offset | int32 | Yes | The first data offset of paging, for example: `0` |
| ∟ sort_count | int32 | Yes | Number of paginated pages per page, for example: `20`, no pagination when filling in `0` |
| ∟ type | int32[] | No | Filter warrant type, for example: `[0,1]`
**Optional value:**
`0` - Call
`1` - Put
`2` - Bull
`3` - Bear
`4` - Inline |
| ∟ issuer | int32[] | No | Filter issuer example: `[12,14]`, obtain [Issuer ID](./issuer) through API |
| ∟ expiry_date | int32[] | No | Filter expiry date, example: `[1]`
**Optional value:**
`1` - Less than 3 months
`2` - 3 - 6 months
`3` - 6 - 12 months
`4` - greater than 12 months |
| ∟ price_type | int32[] | No | Filter in/out of bounds, for example: `[2]`
**Optional value:**
`1` - In bounds
`2` - Out bounds |
| ∟ status | int32[] | No | Filter status, for example: `[2]`
**Optional value:**
`2`- Suspend trading
`3` - Papare List
`4` - Normal |
| language | int32 | Yes | Language, for example: `[1]`
**Optional value:**
`0` - zh-CN
`1` - en
`2` - zh-HK |
### Protobuf
```protobuf
message WarrantFilterListRequest {
string symbol = 1;
FilterConfig filter_config = 2;
int32 language = 3;
}
message FilterConfig {
int32 sort_by = 1;
int32 sort_order = 2;
int32 sort_offset = 3;
int32 sort_count = 4;
repeated int32 type = 5;
repeated int32 issuer = 6;
repeated int32 expiry_date = 7;
repeated int32 price_type = 8;
repeated int32 status = 9;
}
```
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, WarrantSortBy, SortOrderType, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.warrant_list("700.HK", WarrantSortBy.LastDone, SortOrderType.Ascending)
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, WarrantSortBy, SortOrderType, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.warrant_list("700.HK", WarrantSortBy.LastDone, SortOrderType.Ascending)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth, WarrantSortBy, SortOrderType } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.warrantList('700.HK', WarrantSortBy.LastDone, SortOrderType.Ascending)
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
WarrantInfo[] resp = ctx.queryWarrantList(new QueryWarrantOptions("700.HK", WarrantSortBy.LastDone, SortOrderType.Ascending)).get();
for (WarrantInfo w : resp) System.out.println(w);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::{QuoteContext, WarrantSortBy, SortOrderType}, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.warrant_list("700.HK", WarrantSortBy::LastDone, SortOrderType::Ascending, None, None, None, None, None).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.warrant_list("700.HK", WarrantSortBy::Turnover, SortOrderType::Descending, {}, {}, {}, {}, {}, [](auto res) {
if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; }
std::cout << "warrants: " << res->size() << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
list, err := qctx.WarrantList(context.Background(), "700.HK", quote.WarrantFilter{
SortBy: quote.WarrantVolume, SortOrder: quote.WarrantDesc, SortOffset: 0, SortCount: 10,
}, quote.WarrantEN)
if err != nil {
log.Fatal(err)
}
fmt.Println("warrants:", len(list))
}
```
## Response
### Response Properties
| Name | Type | Description | OrderSequence | Support_Call/Put | Support_Bull/Bear | Support_Inline |
| -------------------- | -------- | ---------------------------------------------------------------------------------------------------------- | ------------- | ---------------- | ----------------- | -------------- |
| warrant_list | object[] | Filted warrant data list | | | | |
| ∟ symbol | string | Security code | | true | true | true |
| ∟ name | string | Security name | | true | true | true |
| ∟ last_done | string | Latest price | 0 | true | true | true |
| ∟ change_rate | string | Quote change rate | 1 | true | true | true |
| ∟ change_val | string | Quote change | 2 | true | true | true |
| ∟ volume | int64 | Volume | 3 | true | true | true |
| ∟ turnover | string | Turnover | 4 | true | true | true |
| ∟ expiry_date | string | Expiry date, in `YYMMDD` format | 5 | true | true | true |
| ∟ strike_price | string | Strike price | 6 | true | true | false |
| ∟ upper_strike_price | string | Upper bound price | 7 | false | false | true |
| ∟ lower_strike_price | string | Lower bound price | 8 | false | false | true |
| ∟ outstanding_qty | string | Outstanding quantity | 9 | true | true | true |
| ∟ outstanding_ratio | string | Outstanding ratio | 10 | true | true | true |
| ∟ premium | string | Premium | 11 | true | true | true |
| ∟ itm_otm | string | In/out of the bound | 12 | true | true | false |
| ∟ implied_volatility | string | Implied volatility | 13 | true | false | false |
| ∟ delta | string | Greek value Delta | 14 | true | false | false |
| ∟ call_price | string | Call price | 15 | false | true | false |
| ∟ to_call_price | string | Price interval from the call price | 16 | false | true | false |
| ∟ effective_leverage | string | Effective leverage | 17 | true | false | false |
| ∟ leverage_ratio | string | Leverage ratio | 18 | true | true | true |
| ∟ conversion_ratio | string | Conversion ratio | 19 | true | true | false |
| ∟ balance_point | string | Breakeven point | 20 | true | true | false |
| ∟ status | int32 | Status,
**Optional value:**
`2`- Suspend trading
`3` - Papare List
`4` - Normal | 21 | true | true | true |
| total_count | int32 | Total number of eligible | | | | |
### Protobuf
```protobuf
message WarrantFilterListResponse {
repeated FilterWarrant warrant_list = 1;
int32 total_count = 2;
}
message FilterWarrant {
string symbol = 1;
string name = 2;
string last_done = 3;
string change_rate = 4;
string change_val = 5;
int64 volume = 6;
string turnover = 7;
string expiry_date = 8;
string strike_price = 9;
string upper_strike_price = 10;
string lower_strike_price = 11;
string outstanding_qty = 12;
string outstanding_ratio = 13;
string premium = 14;
string itm_otm = 15;
string implied_volatility = 16;
string delta = 17;
string call_price = 18;
string to_call_price = 19;
string effective_leverage = 20;
string leverage_ratio = 21;
string conversion_ratio = 22;
string balance_point = 23;
int32 status = 24;
}
```
### Response JSON Example
```json
{
"warrant_list": [
{
"symbol": "13157.HK",
"name": "MBTENCT@EP2207A",
"last_done": "2.26",
"change_rate": "-0.0216450216450218",
"change_val": "-0.050000000000000266",
"turnover": "0",
"expiry_date": "20220705",
"strike_price": "442.233",
"upper_strike_price": "0",
"lower_strike_price": "0",
"outstanding_qty": "5000",
"outstanding_ratio": "0.0003",
"premium": "0.016784269662921222",
"itm_otm": "0.23524476916014864",
"implied_volatility": "0.5275",
"delta": "-0.8524",
"call_price": "0",
"effective_leverage": "-2.627683451852457",
"leverage_ratio": "3.0826882353970637",
"conversion_ratio": "48.544",
"balance_point": "332.52356000000003",
"status": 4
},
{
"symbol": "13649.HK",
"name": "MBTENCT@EP2205A",
"last_done": "1.14",
"change_rate": "0",
"change_val": "0",
"turnover": "0",
"expiry_date": "20220518",
"strike_price": "445.223",
"upper_strike_price": "0",
"lower_strike_price": "0",
"outstanding_qty": "80000",
"outstanding_ratio": "0.0004",
"premium": "0.010810703725606",
"itm_otm": "0.24038066317328624",
"implied_volatility": "0.5997",
"delta": "-0.7964",
"call_price": "0",
"effective_leverage": "-2.4335424241487873",
"leverage_ratio": "3.055678583813144",
"conversion_ratio": "97.087",
"balance_point": "334.54382000000004",
"status": 4
}
],
"total_count": 1197
}
```
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | ---------------------------- | ------------------------------------------------------------- |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
| 7 | 301600 | Symbol not found | Check that the requested `symbol` is correct |
| 7 | 301603 | No quotes | Security no quote |
| 7 | 301604 | No access | No access to security quote |
| 7 | 301607 | Too many symbols in one page | Reduce the number of symbols in a page of request |
---
# Quotes
URL: https://open.longbridge.com/docs/quote/pull/warrant-quote.md
This API is used to obtain the real-time quotes of HK warrants, including the warrant-specific data.
# real-time quote for a Tencent-linked warrant
longbridge warrant quote 25228.HK
# real-time quote for another Tencent-linked warrant
longbridge warrant quote 24687.HK
:::info
[Business Command](../../socket/biz_command): `13`
:::
## Request
### Parameters
| Name | Type | Required | Description |
| ------ | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| symbol | string[] | Yes | Security code list, in `ticker.region` format, for example: `[13447.HK]`
**Check rules:**
The maximum number of symbols in each request is `500` |
### Protobuf
```protobuf
message MultiSecurityRequest {
repeated string symbol = 1;
}
```
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.warrant_quote(["21125.HK"])
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.warrant_quote(["21125.HK"])
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.warrantQuote(['21125.HK'])
for (const obj of resp) {
console.log(obj.toString())
}
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id")
.build(url -> System.out.println("Open to authorize: " + url))
.get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
WarrantQuote[] resp = ctx.getWarrantQuote(new String[] { "21125.HK" }).get();
for (WarrantQuote obj : resp) {
System.out.println(obj);
}
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.warrant_quote(["21125.HK"]).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
std::vector symbols = {"21926.HK"};
ctx.warrant_quote(symbols, [](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
for (const auto& q : *res) {
std::cout << q.symbol << " " << (double)q.last_done << std::endl;
}
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
quotes, err := qctx.WarrantQuote(context.Background(), []string{"21926.HK"})
if err != nil {
log.Fatal(err)
}
for _, q := range quotes {
fmt.Println(q.Symbol, q.LastDone)
}
}
```
## Response
### Response Properties
| Name | Type | Description |
| --------------------- | -------- | -------------------------------------------------------------------------------------------------------------- |
| secu_quote | object[] | Warrants quote |
| ∟ symbol | string | Security code |
| ∟ last_done | string | Latest price |
| ∟ prev_close | string | Yesterday's close |
| ∟ open | string | Open |
| ∟ high | string | High |
| ∟ low | string | Low |
| ∟ timestamp | int64 | Time of latest price |
| ∟ volume | int64 | Volume |
| ∟ turnover | string | Turnover |
| ∟ trade_status | int32 | Security trading status, see [TradeStatus](../objects#tradestatus---security-status) |
| ∟ warrant_extend | object | Warrant extend quote |
| ∟∟ implied_volatility | string | Implied volatility |
| ∟∟ expiry_date | string | Exprity date, in `YYMMDD` format |
| ∟∟ last_trade_date | string | Last tradalbe date, in `YYMMDD` format |
| ∟∟ outstanding_ratio | string | Outstanding ratio |
| ∟∟ outstanding_qty | int64 | Outstanding quantity |
| ∟∟ conversion_ratio | string | Conversion ratio |
| ∟∟ category | string | Warrant type
**Optional value: **
`Call`
`Put`
`Bull`
`Bear`
`Inline` |
| ∟∟ strike_price | string | Strike price |
| ∟∟ upper_strike_price | string | Upper bound price |
| ∟∟ lower_strike_price | string | Lower bound price |
| ∟∟ call_price | string | Call price |
| ∟∟ underlying_symbol | string | Underlying security symbol of the option |
### Protobuf
```protobuf
message WarrantQuoteResponse {
repeated WarrantQuote secu_quote = 2;
}
message WarrantQuote {
string symbol = 1;
string last_done = 2;
string prev_close = 3;
string open = 4;
string high = 5;
string low = 6;
int64 timestamp = 7;
int64 volume = 8;
string turnover = 9;
TradeStatus trade_status = 10;
WarrantExtend warrant_extend = 11;
}
message WarrantExtend {
string implied_volatility = 1;
string expiry_date = 2;
string last_trade_date = 3;
string outstanding_ratio = 4;
int64 outstanding_qty = 5;
string conversion_ratio = 6;
string category = 7;
string strike_price = 8;
string upper_strike_price = 9;
string lower_strike_price = 10;
string call_price = 11;
string underlying_symbol = 12;
}
```
### Response JSON Example
```json
{
"secu_quote": [
{
"symbol": "66642.HK",
"last_done": "0.345",
"prev_close": "0.365",
"open": "0.345",
"high": "0.345",
"low": "0.345",
"timestamp": 1651130421,
"volume": 200000,
"turnover": "69000.000",
"warrant_extend": {
"implied_volatility": "0.319",
"expiry_date": "20220830",
"last_trade_date": "20220829",
"outstanding_ratio": "0.0001",
"outstanding_qty": 20000,
"conversion_ratio": "10000",
"category": "Bear",
"strike_price": "23200.000",
"upper_strike_price": "0.000",
"lower_strike_price": "0.000",
"call_price": "23100.000",
"underlying_symbol": "HSI.HK"
}
},
{
"symbol": "14993.HK",
"last_done": "0.073",
"prev_close": "0.066",
"open": "0.069",
"high": "0.076",
"low": "0.069",
"timestamp": 1651130930,
"volume": 320825000,
"turnover": "23401125.000",
"warrant_extend": {
"implied_volatility": "0.404",
"expiry_date": "20220927",
"last_trade_date": "20220921",
"outstanding_ratio": "0.0247",
"outstanding_qty": 2465000,
"conversion_ratio": "10",
"category": "Call",
"strike_price": "70.050",
"upper_strike_price": "0.000",
"lower_strike_price": "0.000",
"call_price": "0.000",
"underlying_symbol": "2318.HK"
}
}
]
}
```
## API Restrictions
:::caution
- The HK stocks quotation beyond the 20th will be delayed if the quote level is BMP.
:::
## Error Code
| Protocol Error Code | Business Error Code | Description | Troubleshooting Suggestions |
| ------------------- | ------------------- | ------------------------ | ------------------------------------------------------------- |
| 3 | 301600 | Invalid request | Invalid request parameters or unpacking request failed |
| 3 | 301606 | Request rate limit | Reduce the frequency of requests |
| 7 | 301602 | Server error | Please try again or contact a technician to resolve the issue |
| 7 | 301607 | Too many request symbols | Reduce the number of symbols in a request |
---
# Update Pinned
URL: https://open.longbridge.com/docs/quote/watchlist/update-pinned.md
Pin or unpin a security within a watchlist group to control its display order.
## Request
HTTP Method PUT
HTTP URL /watchlist/groups
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| --------- | ------ | -------- | -------------------------------------------------------- |
| id | string | YES | Watchlist group ID |
| symbol | string | YES | Security symbol to pin or unpin, e.g. `AAPL.US` |
| is_pinned | bool | YES | Set to `true` to pin the security, `false` to unpin it |
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.update_pinned(group_id="2630", symbol="AAPL.US", is_pinned=True)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
await ctx.update_pinned(group_id="2630", symbol="AAPL.US", is_pinned=True)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
await ctx.updatePinned('2630', 'AAPL.US', true)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
ctx.updatePinned("2630", "AAPL.US", true).get();
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
ctx.update_pinned("2630", "AAPL.US", true).await?;
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::quote;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
QuoteContext ctx = QuoteContext::create(config);
ctx.update_pinned("2630", "AAPL.US", true, [](auto) {});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
if err := qctx.UpdatePinned(context.Background(), "2630", "AAPL.US", true); err != nil {
log.Fatal(err)
}
fmt.Println("OK")
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | None |
| 400 | Bad request | None |
## Schemas
No response schemas. The endpoint returns an empty `data` object on success.
---
# Create Group
URL: https://open.longbridge.com/docs/quote/watchlist/watchlist_create_group.md
Create watched group
# create a new watchlist group
longbridge watchlist create "My Portfolio"
# create another watchlist group
longbridge watchlist create "Tech Stocks"
## Request
HTTP Method POST
HTTP URL /v1/watchlist/groups
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| ---------- | -------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name | string | YES | Group name, for example `Information Technology Group`. |
| securities | string[] | NO | Security list, for example `["BABA.US", "AAPL.US"]`. Display order of securities in the group, in the same order as this list. If this parameter is not passed, create an empty group. |
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
group_id = ctx.create_watchlist_group(name = "Watchlist1", securities = ["700.HK", "AAPL.US"])
print(group_id)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
group_id = ctx.create_watchlist_group(name = "Watchlist1", securities = ["700.HK", "AAPL.US"])
print(group_id)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.createWatchlistGroup('My Group', ['700.HK', 'AAPL.US'])
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
WatchlistGroup resp = ctx.createWatchlistGroup("My Group", new String[] { "700.HK", "AAPL.US" }).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.create_watchlist_group("My Group", vec!["700.HK".to_string(), "AAPL.US".to_string()]).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.create_watchlist_group("My Group", symbols, [](auto res) {
if (!res) { std::cout << "failed" << std::endl; return; }
std::cout << "created: " << res->name << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
gid, err := qctx.CreateWatchlistGroup(context.Background(), "My Group", []string{"700.HK", "AAPL.US"})
if err != nil {
log.Fatal(err)
}
fmt.Println("created:", gid)
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"data": {
"id": 10086
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------- | ----------------------------------------------------- |
| 200 | Success | [create_group_response](#schemacreate_group_response) |
| 500 | Internal error | None |
## Schemas
### create_group_response
| Name | Type | Required | Description |
| ---- | ------- | -------- | ----------- |
| id | integer | false | Group ID |
---
# Delete Group
URL: https://open.longbridge.com/docs/quote/watchlist/watchlist_delete_group.md
Delete watched group
# delete a watchlist group by ID (get ID from: longbridge watchlist)
longbridge watchlist delete
## Request
HTTP Method DELETE
HTTP URL /v1/watchlist/groups
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| ----- | ------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| id | integer | YES | Group ID, for example `10086`. |
| purge | boolean | YES | Whether to clear the securities in the group. If set to `true`, the securities in the group will be unfollowed. If set to `false`, the securities in the group will remain in the `All` group. |
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.delete_watchlist_group(10086)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
ctx.delete_watchlist_group(10086)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
await ctx.deleteWatchlistGroup(1)
console.log('deleted')
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
ctx.deleteWatchlistGroup(1).get();
System.out.println("deleted");
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
ctx.delete_watchlist_group(1).await?;
println!("deleted");
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.delete_watchlist_group(1, [](auto res) {
if (!res) { std::cout << "failed" << std::endl; return; }
std::cout << "deleted" << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
err = qctx.DeleteWatchlistGroup(context.Background(), 1, false)
if err != nil {
log.Fatal(err)
}
fmt.Println("deleted")
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------- | ------ |
| 200 | Success | None |
| 500 | Internal error | None |
---
# Watchlist Groups
URL: https://open.longbridge.com/docs/quote/watchlist/watchlist_groups.md
Get Watchlist groups
# list all watchlist groups and their symbols
longbridge watchlist
## Request
HTTP Method GET
HTTP URL /v1/watchlist/groups
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.watchlist()
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.watchlist()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.watchlist()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
WatchlistGroup[] resp = ctx.getWatchlist().get();
for (WatchlistGroup g : resp) System.out.println(g);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.watchlist().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.watchlist([](auto res) {
if (!res) { std::cout << "failed" << std::endl; return; }
for (const auto& g : *res) std::cout << g.name << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
groups, err := qctx.WatchedGroups(context.Background())
if err != nil {
log.Fatal(err)
}
for _, g := range groups {
fmt.Println(g.Name)
}
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"data": {
"groups": [
{
"id": 28020,
"name": "all",
"securities": [
{
"symbol": "700.HK",
"market": "HK",
"name": "Tencent",
"watched_price": "364.4",
"watched_at": 1652855022,
"is_pinned": true
}
]
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------- | ----------------------------------------- |
| 200 | Success | [groups_response](#schemagroups_response) |
| 500 | Internal error | None |
## Schemas
### groups_response
| Name | Type | Required | Description |
| ---------------- | -------- | -------- | ------------------------------ |
| groups | object[] | false | Groups |
| ∟ id | integer | true | Group ID |
| ∟ name | string | true | Name |
| ∟ securities | object[] | true | Security |
| ∟∟ symbol | string | true | Symbol |
| ∟∟ market | string | true | Market |
| ∟∟ name | string | true | Name |
| ∟∟ watched_price | string | true | Watched price |
| ∟∟ watched_at | integer | true | Watched time |
| ∟∟ is_pinned | boolean | true | Whether the security is pinned |
---
# Manage Group Securities
URL: https://open.longbridge.com/docs/quote/watchlist/watchlist_update_group.md
Update watched group
# add symbols to a group
longbridge watchlist update --add TSLA.US --add AAPL.US
# remove a symbol from a group
longbridge watchlist update --remove NVDA.US
# add and remove at the same time
longbridge watchlist update --add TSLA.US --remove AAPL.US
## Request
HTTP Method PUT
HTTP URL /v1/watchlist/groups
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| ---------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| id | integer | YES | Group ID, for example `10086`. |
| name | string | NO | Group name, for example `Information Technology Group`.
If this parameter is not passed, the group name will not be updated. |
| securities | string[] | NO | Security list, for example `["BABA.US", "AAPL.US"]`.
Combined with the `mode` parameter below, it can be used to add securities, remove securities, and sort the watchlist. |
| mode | string | NO | Operation method
**optional values:**
`add` - Add securities
`remove` - Remove securities
`replace` - Update securities
When selecting `add`, the securities in the above list will be added to this group in order.
When selecting `remove`, the securities in the above list will be removed from this group.
When selecting `update`, the securities in the above list will completely replace the securities in this group.
For example, if the original group contains `APPL.US, BABA.US, TSLA.US`, and it is updated with `["BABA.US", "AAPL.US", "MSFT.US"]`, it will become `BABA.US, AAPL.US, MSFT.US`, removing `TSLA.US` and adding `MSFT.US`, while adjusting the order of `BABA.US and AAPL.US`. |
### Request Example
```python
from longbridge.openapi import QuoteContext, Config, SecuritiesUpdateMode, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
ctx.update_watchlist_group(10086, name = "Watchlist2", securities = ["700.HK", "AAPL.US"], SecuritiesUpdateMode.Replace)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, SecuritiesUpdateMode, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
ctx.update_watchlist_group(10086, name = "Watchlist2", securities = ["700.HK", "AAPL.US"], SecuritiesUpdateMode.Replace)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
await ctx.updateWatchlistGroup(1, 'New Name', ['700.HK'])
console.log('updated')
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
ctx.updateWatchlistGroup(1, "New Name", new String[] { "700.HK" }).get();
System.out.println("updated");
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
ctx.update_watchlist_group(1, "New Name", vec!["700.HK".to_string()]).await?;
println!("updated");
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.update_watchlist_group(1, "New Name", symbols, [](auto res) {
if (!res) { std::cout << "failed" << std::endl; return; }
std::cout << "updated" << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
err = qctx.UpdateWatchlistGroup(context.Background(), 1, "New Name", []string{"700.HK"}, quote.AddWatchlist)
if err != nil {
log.Fatal(err)
}
fmt.Println("updated")
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------- | ------ |
| 200 | Success | None |
| 500 | Internal error | None |
---
# Screener Indicators
URL: https://open.longbridge.com/docs/screener/screener-indicators.md
Get all indicator definitions supported by the [stock screener](https://longbridge.com/screener), including keys, names, units, and available ranges. Use these to build custom filter conditions.
Endpoint: `GET /v1/quote/ai/screener/indicators`
> **SDK response:** The `data` field contains a grouped structure `{"groups": [{...}]}`. The CLI `screener indicators --format json` flattens this to a flat array for convenience.
longbridge screener indicators
## Parameters
> **SDK method parameters.**
This method takes no parameters.
## Request Example
```python
from longbridge.openapi import ScreenerContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = ScreenerContext(config)
resp = ctx.screener_indicators()
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncScreenerContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncScreenerContext.create(config)
resp = await ctx.screener_indicators()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, ScreenerContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = ScreenerContext.new(config)
const resp = await ctx.screenerIndicators()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.screener.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
ScreenerContext ctx = ScreenerContext.create(config)) {
var resp = ctx.getScreenerIndicators().get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, screener::ScreenerContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = ScreenerContext::new(config);
let resp = ctx.screener_indicators().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::screener;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
ScreenerContext ctx = ScreenerContext::create(config);
ctx.screener_indicators([](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/screener"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := screener.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.ScreenerIndicators(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"groups": [
{
"group_name": "Company Size & Financials",
"indicators": [
{ "id": "1", "key": "marketcap", "name": "Market Cap", "unit": "B", "min": null, "max": null }
]
}
]
}
}
```
> The `filter_` prefix is stripped from all `key` values. The `id` field is a string.
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [ScreenerIndicatorsResponse](#ScreenerIndicatorsResponse) |
| 400 | Bad request | None |
## Schemas
### ScreenerIndicatorsResponse
The SDK response `data` is a grouped structure. The CLI `--format json` output flattens it to a flat array. The `filter_` prefix is stripped from all `key` values.
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| groups | object[] | false | Indicator groups |
| ∟ group_name | string | false | Group name |
| ∟ indicators | object[] | false | Indicators in this group |
| ∟ ∟ id | string | false | Indicator ID (string) |
| ∟ ∟ key | string | false | Indicator key for building filter conditions (no `filter_` prefix) |
| ∟ ∟ name | string | false | Indicator display name |
| ∟ ∟ unit | string | false | Unit (e.g. `%`, `B`) |
| ∟ ∟ min | string | false | Global lower bound; null means no lower bound |
| ∟ ∟ max | string | false | Global upper bound; null means no upper bound |
---
# Preset Screener Strategies
URL: https://open.longbridge.com/docs/screener/screener-recommend-strategies.md
Get the list of platform-preset stock screener strategies, including recent average daily change and constituent stocks.
Endpoint: `GET /v1/quote/ai/screener/strategies/recommend`
longbridge screener strategies
longbridge screener strategies --market HK
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| market | string | NO | Market filter: `US`, `HK`, `CN`, `SG`. Default: `US` |
## Request Example
```python
from longbridge.openapi import ScreenerContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = ScreenerContext(config)
# Default market (US)
resp = ctx.screener_recommend_strategies()
print(resp)
# Hong Kong market
resp = ctx.screener_recommend_strategies(market="HK")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncScreenerContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncScreenerContext.create(config)
resp = await ctx.screener_recommend_strategies(market="HK")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, ScreenerContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = ScreenerContext.new(config)
const resp = await ctx.screenerRecommendStrategies()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.screener.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
ScreenerContext ctx = ScreenerContext.create(config)) {
var resp = ctx.getScreenerRecommendStrategies().get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, screener::ScreenerContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = ScreenerContext::new(config);
let resp = ctx.screener_recommend_strategies().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::screener;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
ScreenerContext ctx = ScreenerContext::create(config);
ctx.screener_recommend_strategies([](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/screener"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := screener.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.ScreenerRecommendStrategies(context.Background(), "US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"strategys": [
{ "id": 19, "name": "Stocks that surged today", "type": "platform", "market": "US" },
{ "id": 20, "name": "Top growth stocks of the year", "type": "platform", "market": "US" }
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [ScreenerStrategiesResponse](#ScreenerStrategiesResponse) |
| 400 | Bad request | None |
## Schemas
### ScreenerStrategiesResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| strategys | object[] | false | Strategy list |
| ∟ id | integer | false | Strategy ID (pass to `screener_strategy` or `screener_search`) |
| ∟ name | string | false | Strategy name |
| ∟ type | string | false | `"platform"` for preset strategies |
| ∟ market | string | false | Target market (e.g. `"US"`, `"HK"`) |
---
# Screener Search
URL: https://open.longbridge.com/docs/screener/screener-search.md
Filter stocks by strategy ID or custom indicator conditions, with pagination support.
Endpoint: `POST /v1/quote/ai/screener/search`
> **Note on JSON output format:** The response uses a flat `items[]` array (not `stocks[]`), all numeric fields are JSON numbers (not strings), and indicator keys do not carry the `filter_` prefix.
longbridge screener search --strategy-id 42
longbridge screener search --market HK --filter marketcap:100:1000
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| market | string | YES | Market: `US`, `HK`, `CN`, `SG` |
| strategy_id | integer | NO | Strategy ID; use alone or combined with custom conditions |
| conditions | ScreenerCondition[] | NO | Custom filter conditions (Mode B, when strategy_id is omitted) |
| show | string[] | NO | Extra indicator keys to include in the response beyond the 7 default columns |
| page | integer | NO | 0-based page number, default 0 |
| size | integer | NO | Page size, default 20 |
## Request Example
```python
from longbridge.openapi import ScreenerContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = ScreenerContext(config)
# Filter by strategy ID
resp = ctx.screener_search("US", strategy_id=42)
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncScreenerContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncScreenerContext.create(config)
resp = await ctx.screener_search("US", strategy_id=42, page=1, size=20)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, ScreenerContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = ScreenerContext.new(config)
const resp = await ctx.screenerSearch('US', { strategyId: 42, page: 1, size: 20 })
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.screener.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
ScreenerContext ctx = ScreenerContext.create(config)) {
var resp = ctx.screenerSearch("US", 19L, null, List.of(), 0, 20).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, screener::ScreenerContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = ScreenerContext::new(config);
// Mode A: run a strategy
let resp = ctx.screener_search("", Some(19), vec![], vec![], 0, 20).await?;
println!("{:?}", resp);
// Mode B: custom conditions
use longbridge::screener::ScreenerCondition;
let conditions = vec![ScreenerCondition { key: "pettm".into(), min: "10".into(), max: "50".into(), tech_values: serde_json::json!({}) }];
let resp = ctx.screener_search("HK", None, conditions, vec![], 0, 20).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::screener;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
ScreenerContext ctx = ScreenerContext::create(config);
ctx.screener_search("US", 42, 1, 20, [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/screener"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := screener.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
// Mode A: run a strategy
stratID := int64(19)
resp, err := c.ScreenerSearch(context.Background(), "", &stratID, nil, nil, 0, 20)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
// Mode B: custom conditions
conditions := []screener.ScreenerCondition{
{Key: "pettm", Min: "10", Max: "50"},
{Key: "roe", Min: "5"},
}
resp2, err := c.ScreenerSearch(context.Background(), "HK", nil, conditions, []string{"roe"}, 0, 20)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp2)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"total": 88,
"page": 0,
"market": "US",
"items": [
{
"symbol": "AAPL.US",
"name": "Apple Inc.",
"prevchg": 0.62,
"marketcap": 3241500000000,
"pettm": 32.15,
"pbmrq": 50.21,
"salesgrowthyoy": 8.04
},
{
"symbol": "MSFT.US",
"name": "Microsoft",
"prevchg": 1.05,
"marketcap": 3085000000000,
"pettm": 35.42,
"pbmrq": 12.87,
"salesgrowthyoy": 12.61
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [ScreenerSearchResponse](#ScreenerSearchResponse) |
| 400 | Bad request | None |
## Schemas
### ScreenerSearchResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| total | integer | false | Total number of matching stocks |
| page | integer | false | Current page number (zero-based) |
| market | string | false | Market of the result set |
| items | object[] | false | Filtered stock list |
| ∟ symbol | string | false | Security symbol |
| ∟ name | string | false | Security name |
| ∟ prevchg | number | false | Previous day price change ratio (e.g. `1.24` = 1.24%) |
| ∟ marketcap | number | false | Market capitalisation (numeric) |
| ∟ pettm | number | false | P/E ratio (TTM, numeric) |
| ∟ pbmrq | number | false | P/B ratio (MRQ, numeric) |
| ∟ salesgrowthyoy | number | false | Revenue growth YoY (%) |
| ∟ industry | string | false | Industry classification |
> All numeric indicator fields are JSON numbers. Additional indicator fields depend on the strategy or filter used. Indicator keys do not carry the `filter_` prefix.
---
# Screener Strategy Detail
URL: https://open.longbridge.com/docs/screener/screener-strategy.md
Get the full configuration of a single stock screener strategy by strategy ID, including all indicator groups and the filter range for each indicator.
Endpoint: `GET /v1/quote/ai/screener/strategy/\{id\}` (strategy ID as path parameter)
longbridge screener run 42
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | integer | YES | Strategy ID from `screener_recommend_strategies` or `screener_user_strategies` |
## Request Example
```python
from longbridge.openapi import ScreenerContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = ScreenerContext(config)
resp = ctx.screener_strategy(42)
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncScreenerContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncScreenerContext.create(config)
resp = await ctx.screener_strategy(42)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, ScreenerContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = ScreenerContext.new(config)
const resp = await ctx.screenerStrategy(42)
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.screener.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
ScreenerContext ctx = ScreenerContext.create(config)) {
var resp = ctx.getScreenerStrategy(42L).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, screener::ScreenerContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = ScreenerContext::new(config);
let resp = ctx.screener_strategy(42).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::screener;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
ScreenerContext ctx = ScreenerContext::create(config);
ctx.screener_strategy(42, [](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/screener"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := screener.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.ScreenerStrategy(context.Background(), 42)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"id": 19,
"name": "Stocks that surged today",
"market": "US",
"type": "platform",
"filter": {
"filters": [
{ "key": "prevchg", "min": "2", "max": "", "tech_values": {} }
]
}
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [ScreenerStrategyDetail](#ScreenerStrategyDetail) |
| 400 | Bad request | None |
## Schemas
### ScreenerStrategyDetail
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | integer | false | Strategy ID |
| name | string | false | Strategy name |
| market | string | false | Target market |
| type | string | false | Strategy type |
| filter | object | false | Filter configuration |
| ∟ filters | object[] | false | Filter conditions |
| ∟ ∟ key | string | false | Indicator key (no `filter_` prefix) |
| ∟ ∟ min | string | false | Lower bound |
| ∟ ∟ max | string | false | Upper bound |
| ∟ ∟ tech_values | object | false | Technical indicator params |
---
# My Screener Strategies
URL: https://open.longbridge.com/docs/screener/screener-user-strategies.md
Get the list of custom stock screener strategies created by the currently logged-in user.
Endpoint: `GET /v1/quote/ai/screener/strategies/mine`
longbridge screener strategies --mine
longbridge screener strategies --mine --market HK
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| market | string | NO | Market filter: `US`, `HK`, `CN`, `SG`. Default: `US` |
Login required.
## Request Example
```python
from longbridge.openapi import ScreenerContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = ScreenerContext(config)
resp = ctx.screener_user_strategies()
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncScreenerContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncScreenerContext.create(config)
resp = await ctx.screener_user_strategies()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, ScreenerContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = ScreenerContext.new(config)
const resp = await ctx.screenerUserStrategies()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.screener.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
ScreenerContext ctx = ScreenerContext.create(config)) {
var resp = ctx.getScreenerUserStrategies().get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, screener::ScreenerContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = ScreenerContext::new(config);
let resp = ctx.screener_user_strategies().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::screener;
int main() {
OAuthBuilder("your-client-id").build(
[](const std::string& url) { std::cout << "Open: " << url << std::endl; },
[](auto res) {
if (!res) return;
Config config = Config::from_oauth(*res);
ScreenerContext ctx = ScreenerContext::create(config);
ctx.screener_user_strategies([](auto resp) {
if (resp) std::cout << "OK" << std::endl;
});
});
std::cin.get();
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/screener"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
c, err := screener.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.ScreenerUserStrategies(context.Background(), "US")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"strategys": [
{ "id": 42, "name": "My Growth Strategy", "type": "user", "market": "US" }
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [ScreenerStrategiesResponse](#ScreenerStrategiesResponse) |
| 400 | Bad request | None |
## Schemas
### ScreenerStrategiesResponse
The response structure is identical to [screener_recommend_strategies](/docs/screener/screener-recommend-strategies). Please refer to that document for the Schema definition.
---
# Data Commands
URL: https://open.longbridge.com/docs/socket/biz_command.md
Socket Feed providers real-time stock quote data updates and trade updates.
And stock quote and order have difference endpoints, [check here](./hosts).
## Stock Quote Overview
[Cancel Subscribe](../trade/trade-push#cancel-subscribe) |
| Notify | [Notification](../trade/trade-push#notification) |
More detail check [here](../trade/trade-push)
---
# Control Commands
URL: https://open.longbridge.com/docs/socket/control-command.md
Control Commands are basic commands, using for create connection and keep connection alive.
Control Commands:
| cmd_code | description |
| -------- | ------------------------------------------------------------------------------------------ |
| 0 | close - before server close the connection between client, server will send a close packet |
| 1 | heartbeat - keep connection alive |
| 2 | auth - auth connection |
| 3 | reconnect - use session to auth |
## Close
:::info
Cmd: `0`
:::
Before server close the connection between client, server will send a close packet.
> close packet is push type packet, no need response
Cases server will close the connection:
1. heartbeat timeout
2. server internal error
3. server shutdown
4. client send invalid packet(can't parse by server)
5. auth failed
6. session expired when reconnect
7. duplicate connection have been created
The reason why server close the connection will send by close packet, protobuf defination:
```protobuf
message Close {
enum Code {
HeartbeatTimeout = 0; // Heartbeat timeout
ServerError = 1; // Server internal error
ServerShutdown = 2; // Server shutdown
UnpackError = 3; // Server can't paser client packet
AuthError = 4; // Auth failed
SessExpired = 5; // Session expired
ConnectDuplicate = 6; // create duplicated connection
}
Code code = 1;
string reason = 2;
}
```
## Heartbeat
:::info
Cmd: `1`
:::
Oner peer and send heartbeat to another peer to known health of another peer. Heartbeat do not limit body structure, one peer receive a heartbeat packet, only need send the `body` back.
> Heartbeat not only can keep connection alive, but also can detect latency of the network between two peers. One peer can set current timestamp in heartbeat body, when receive the response, use current timestamp minus timestamp in the body to get lantency of network.
```mermaid
sequenceDiagram
par peer-a to peer-b
peer-a -->> peer-b: heartbeat request, req_id: 1
peer-b -->> peer-a: heartbeat response, req_id: 1
end
par peer-b to peer-a
peer-b -->> peer-a: heartbeat request, req_id: 1
peer-a -->> peer-b: heartbeat response, req_id: 1
end
```
Example of heartbeat `body`:
```protobuf
message Heartbeat {
int64 timestamp = 1;
}
```
## Auth
:::info
Cmd: `2`
:::
Client need prove connection is legal. After handshake with server, client send auth packet as first packet.
```mermaid
sequenceDiagram
Client -->> Server: auth request, req_id: 1, token: xxx
Server -->> Client: auth response, req_id: 1, session: xxx
```
> Auth `token` can be created through [HTTP API](/docs/socket-token-api)
After auth success, server will set session in auth response, client can use the session to reconnect and no need to request a new `token`.
Auth Request and Response protobuf:
```protobuf
message AuthRequest {
string token = 1;
}
message AuthResponse {
string session_id = 1;
int64 expires = 2;
}
```
## Reconnect
:::info
Cmd: `3`
:::
After client disconnect from server, client can use session to reconnect to server when session is not expired. After reconnect success, server will set new session in reconnect response body.
Reconnect Request and Response:
```protobuf
message ReconnectRequest {
string session_id = 1;
}
message ReconnectResponse {
string session_id = 1;
int64 expires = 2;
}
```
## Protobuf
All control command protobuf definations are opensource in [GitHub](https://github.com/longbridge/openapi-protobufs/blob/main/control/control.proto)
---
# Access Differences Between WebSocket and TCP
URL: https://open.longbridge.com/docs/socket/diff_ws_tcp.md
Longbridge support `WebSocket` and `TCP` feed, the differences:
- Data of `TCP` is streaming, so coding client is hard than `WebSocket`.
- `WebSocket` using URL Query to [Handshake](./protocol/handshake#websocket-how-to-handshake)
- `WebSocket` using [ping-pong](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#pings_and_pongs_the_heartbeat_of_websockets) to do Heartbeating, instead of sending heartbeat packet.
- `WebSocket` using `TLS` to secure connection, but `TCP` do not.
User can choice `TCP` or `WebSocket` on self demand.
> Advice: Using `WebSocket` first, it is more simple. If want more quick stock quote real-time pushing, using `TCP` to access stock quote gateway.
---
# Endpoints
URL: https://open.longbridge.com/docs/socket/hosts.md
Longbridge split Market Quote and Trading real-time pushing endpoints.
## Market Quote
| Endpoint | Access Type |
| --------------------------------------- | ----------- |
| tcp://openapi-quote.longbridge.com:2020 | TCP |
| wss://openapi-quote.longbridge.com | WebSocket |
## Trading
| Endpoint | Access Type |
| --------------------------------------- | ----------- |
| tcp://openapi-trade.longbridge.com:2020 | TCP |
| wss://openapi-trade.longbridge.com | WebSocket |
## Mainland China
Users in mainland China can use the following endpoints for better connectivity:
### Market Quote
| Endpoint | Access Type |
| -------------------------------------- | ----------- |
| tcp://openapi-quote.longbridge.cn:2020 | TCP |
| wss://openapi-quote.longbridge.cn | WebSocket |
### Trading
| Endpoint | Access Type |
| -------------------------------------- | ----------- |
| tcp://openapi-trade.longbridge.cn:2020 | TCP |
| wss://openapi-trade.longbridge.cn | WebSocket |
---
# Subscribe Real-Time Market Data
URL: https://open.longbridge.com/docs/socket/subscribe_quote.md
:::success NOTE
Our OpenAPI SDK has fully implemented the function of subscribing to quotes, and you can use the SDK directly.
https://open.longbridge.com/sdk
The documentation in this chapter provides API details for your reference.
:::
Client can access market quote feed by `WebSocket` and `TCP`. After client subscribing stock quote, quote gateway can push real-time quote data to client.
:::info
WebSocket Endpoint: `wss://openapi-quote.longbridge.com`
TCP Endpoint: `openapi-quote.longbridge.com:2020`
:::
Flow:
```mermaid
sequenceDiagram
autonumber
Client ->> Server: Handshake
Server -->> Client: Establish connection
Client -->> Server: Auth request
Server -->> Client: Auth response
par Subscribe Market Quote
Client -->> Server: Subscribe request, req_id: 10, cmd: 6
Server -->> Client: Subscribe response, req_id: 10, cmd: 6
Server -->> Client: price pushing, cmd: 101
Server -->> Client: depth pushing, cmd: 102
Server -->> Client: broker pushing, cmd: 103
Server -->> Client: transaction pushing, cmd: 104
end
```
## Subscribe
Client can subscribe different quote type through subscribe commmand.
Subscribe command [protobuf defination](../quote/subscribe/subscribe)
Example:
```json
{
"symbol": ["700.HK", "AAPL.US"]
"sub_type": [1, 2]
"is_first_push": true
}
```
> Here is `JSON` for easy showing case, actually need using protobuf encoding.
Client can also check quote topics already subscribing, [protobuf defination](../quote/subscribe/subscription).
After client success subscribing quote, server will push real-time quote data to client, data [protobuf defination](../quote/overview).
## Other Quote APIs
All quote all should be fetched by our quote gateway, more details can be found in [quote overview](../quote/overview).
## Feed Protocol
If you want subscribe quote data from socket, you must know more details of our [protocol](./protocol/overview)
---
# Subscribe Real-Time Trading Data
URL: https://open.longbridge.com/docs/socket/subscribe_trade.md
Client can access trade feed by `WebSocket` and `TCP`. After client subscribing, trade gateway can push real-time trade changings of user.
:::info
WebSocket Endpoint: `wss://openapi-trade.longbridge.com`
TCP Endpoint: `openapi-trade.longbridge.com`
:::
Flow:
```mermaid
sequenceDiagram
autonumber
Client ->> Server: Handshake
Server -->> Client: Establish Connection
Client -->> Server: Auth Request
Server -->> Client: Auth Response
par Subscribe
Client -->> Server: Subscribe request, req_id: 10, cmd: 16
Server -->> Client: Subscribe response, req_id: 10, cmd: 16
Server -->> Client: Push order updating, cmd: 18
Server -->> Client: Push order updating, cmd: 18
end
```
## Subscribe
Subscribe [protobuf defination](../trade/trade-push)
Example:
```json
{
"topics": ["private"]
}
```
> Here is `JSON` for easy showing case, actually need using protobuf encoding.
## Pushing Example
```json
{
"topic": "private",
"content_type": 2,
"dispatch_type": 1,
"data": "eyJldmVudCI6Im9yZGVyX2NoYW5nZWRfbGIiLCJkYXRhIjp7InNpZGUiOiJCdXkiLCJzdG9ja19uYW1lIjoi6IW+6K6v5o6n6IKhIiwicXVhbnRpdHkiOiIxMDAwIiwic3ltYm9sIjoiNzAwLkhLIiwib3JkZXJfdHlwZSI6IkxPIiwicHJpY2UiOiIyMTMuMiIsImV4ZWN1dGVkX3F1YW50aXR5IjoiMTAwMCIsImV4ZWN1dGVkX3ByaWNlIjoiMjEzLjIiLCJvcmRlcl9pZCI6IjI3IiwiY3VycmVuY3kiOiJIS0QiLCJzdGF0dXMiOiJOZXdTdGF0dXMiLCJzdWJtaXR0ZWRfYXQiOiIxNTYyNzYxODkzIiwidXBkYXRlZF9hdCI6IjE1NjI3NjE4OTMiLCJ0cmlnZ2VyX3ByaWNlIjoiMjEzLjAiLCJtc2ciOiJJbnN1ZmZpY2llbnQgUXR5IC0gMTAwMCIsInRhZyI6IkdUQyIsInRyaWdnZXJfc3RhdHVzIjoiQUNUSVZFIiwidHJpZ2dlcl9hdCI6IjE1NjI3NjE4OTMiLCJ0YWlsaW5nX2Ftb3VudCI6IjUiLCJ0YWlsaW5nX3BlcmNlbnQiOiIxIiwibGltaXRfb2Zmc2V0IjoiMC4wMSIsImFjY291bnRfbm8iOiJISzEyMzQ0NSJ9fQ=="
}
```
:::info
`data` is binary(Base64) content of `JSON` string
:::
The real `JSON` format of `data`:
```json
{
"event": "order_changed_lb",
"data": {
"side": "Buy",
"stock_name": "Tecent",
"quantity": "1000",
"symbol": "700.HK",
"order_type": "LO",
"price": "213.2",
"executed_quantity": "1000",
"executed_price": "213.2",
"order_id": "27",
"currency": "HKD",
"status": "NewStatus",
"submitted_at": "1562761893",
"updated_at": "1562761893",
"trigger_price": "213.0",
"msg": "Insufficient Qty - 1000",
"tag": "GTC",
"trigger_status": "ACTIVE",
"trigger_at": "1562761893",
"trailing_amount": "5",
"trailing_percent": "1",
"limit_offset": "0.01",
"account_no": "HK123445",
"last_share": "100",
"last_price": "234",
"remark": "abc"
}
}
```
Field description is [here](../trade/trade-definition#websocket-push-notification)
## Feed Protocol
If you want subscribe trading data from socket, you must know more details of our [protocol](./protocol/overview)
---
# Communication Model
URL: https://open.longbridge.com/docs/socket/protocol/connect.md
There are three type packet will client and server send to each other:
- handshake - start establish connection
- request - client send request to server
- response - server send response to client
- push - server push real-time data to client
## Handshake
Flow:
```mermaid
sequenceDiagram
client ->> server: 1. handshake
server ->> server: 1.1 check handshake
alt handshake invalid
server --x client: 2. disconnect
else is valid
server -->> client: 2. build connection
end
```
After client sending handshake packet server, the connection has been established. If handshake packet is invalid, server will push a close data to client. If access by `TCP`, client can send handshake packet and first data packet(auth) for accelerating communication.
## Request and Response
`Request <--> Response`: Client send a request packet, server will send back a response packet.
Flow:
```mermaid
sequenceDiagram
autonumber
par request 1
client -->> server: request, req_id: 1
server -->> client: response, req_id: 1
end
par request 100
client -->> server: request, req_id: 100
server -->> client: response: req_id: 100
end
par request n
client -->> server: request, req_id: n
server -->> client: response, req_id: n
end
```
After client and server sucess handshaking, peers can use `Request <--> Response` to communicate. `Request` and `Response` are paired by `request_id`.
> Client and Server can send heartbeat request to each other.
## Push
Push is one peer send data to another peer, and no need response.
```mermaid
sequenceDiagram
server -->> client: push, data 1
server -->> client: push, data 2
```
> Right now, we only support server push data to client.
---
# Parse Handshake
URL: https://open.longbridge.com/docs/socket/protocol/handshake.md
Handshake is first thing before client and server establish connection. Handshake negotiate thress things:
- protocol version - right now only version `1`
- data codec type - right now only support `protobuf`, value is `1`
- client platform - value is `9` as `OpenAPI`
So handshake is always fixed contents.
## How `TCP` do handshaking
Client need send two bytes handshake to server.
### Data structure
```
0 1 2 3 4 5 6 7
+-+-+-+-+-+-+-+-+
| ver | codec |
+-+-+-+-+-+-+-+-+
|platfo.|reserve|
+-+-+-+-+-+-+-+-+
```
Fields Explain:
| field | length in bit | description |
| -------- | ------------- | ----------------------------------------- |
| ver | 4 | protocol version: only value `1` |
| codec | 4 | data codec: only value `1` for `protobuf` |
| platform | 4 | client platform: 0b1001 - OpenAPI |
| reserve | 4 | reserved |
### Example
- ver - 0b0001
- codec - 0b0001
- platform - 0b1001
- reserve - 0b0000
Two bytes contents:
```
0b00010001,
0b00001001
```
## How `WebSocket` do handshaking
`WebSocket` send handshake info by `URL Query`
### Query Parameters
| Field | Type | Description |
| -------- | ---- | ----------------------------------------- |
| version | 4 | protocol version: only value `1` |
| codec | 4 | data codec: only value `1` for `protobuf` |
| platform | 4 | client platform: `9` - OpenAPI |
### Example
```
wss://openapi-quote.longbridge.com?version=1&codec=1&platform=9
```
---
# Parse Header of Packet
URL: https://open.longbridge.com/docs/socket/protocol/header.md
We have three type packet:
- request
- response
- push
The type of packet and some other info can decide the length of packet. Then length of Header is 1 byte.
:::info
The length of Header is 1 byte.
:::
## Structure
```
0 1 2 3 4 5 6 7
+-+-+-+-+-+-+-+-+
| type |v|g|re.|
+-+-+-+-+-+-+-+-+
```
| Field | Length in bit | description |
| ------- | ------------- | ----------------------------------------------------------------- |
| type | 4 | packet type:
`1` - request
`2` - resopnse
`3` - push |
| verify | 1 | if have signature data
`0` - Yes
`1` - No |
| gzip | 1 | if use `gzip` to compress data:
`1` - Yes
`0` - No |
| reserve | 2 | reversed |
## Example
```
// reserve - 0, gzip - 0, verify - 0, type - 1
0b 0000 0001
// reserve - 0, gzip - 1, verify - 0, type - 2
0b 0011 0010
// reserve - 0, gzip - 1, verify - 1, type - 3
0b 0001 0011
// reserve - 3, gzip - 1, verify - 0, type - 3
0b 1110 0011
```
---
# Parse Push Packet
URL: https://open.longbridge.com/docs/socket/protocol/push.md
Push is one side send data to another side, no need response.
:::info
Packet `type` value is `3`
:::
```
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| type=3|v|g|re.| cmd_code | body_len |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| body_len | body(by body_len) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ nonce(optional) +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ signature(optional) +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
```
Fields Descriptions:
| Field | length in bit | Length in byte | description |
| --------- | ------------------------------------- | --------------- | ----------------------------------------------------------------------------------------------------- |
| cmd_code | 8 | 1 | Comand |
| body_len | 24(uint32) | 3 | Then length of `body` in bytes.
Max: 16 MB
If gzip is enabled, the value is after compress |
| body | Variable length, decide by `body_len` | variable length | `body`, max size: 16 MB |
| nonce | 64 | 8 | exists when `verify` is `1` |
| signature | 128 | 16 | exists when `verify` is `1` |
---
# Parse Request Packet
URL: https://open.longbridge.com/docs/socket/protocol/request.md
Request packet is used for invoke apis: send api request and get api response.
:::info
Packet type is `1`
:::
Structure:
```
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| type=1|v|g|re.| cmd_code | request_id |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | timeout |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| body_len | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +
| body(by body_len) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ nonce(optional) +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ signature(optional) +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
```
Fields Descriptions:
| Field | Length in bit | Length in byte | description |
| ---------- | ------------------------------------- | --------------- | ---------------------------------------------------------------------------------------------------------- |
| cmd_code | 8 | 1 | Command |
| request_id | 32(uint32) | 4 | Request id, it should be unique for one connection.
Can start from 1, when reach 4294967295 start over |
| timeout | 16(uint16) | 2 | `timeout` in millisecond
max: 60000(60s) |
| body_len | 24(uint32) | 3 | Then length of `body` in bytes.
Max: 16 MB
If gzip is enabled, the value is after compress |
| body | Variable length, decide by `body_len` | variable length | `body`, max size: 16 MB |
| nonce | 64 | 8 | exists when `verify` is `1` |
| signature | 128 | 16 | exists when `verify` is `1` |
:::info
Using specific protobuf defination to encode/decode body data
:::
---
# Parse Response Packet
URL: https://open.longbridge.com/docs/socket/protocol/response.md
One peer need send back a response packet after receiving and handlding request packet.
:::info
Packet type is `2`
:::
## Structure
```
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| type=2|v|g|re.| cmd_code | request_id |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | status_code | body_len |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| body_len | |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +
| body(by body_len) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ nonce(optional) +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
+ +
| |
+ signature(optional) +
| |
+ +
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
```
Fields Descriptions:
| Field | Length in bit | Length in byte | description |
| ---------- | ------------------------------------- | --------------- | ----------------------------------------------------------------------------------------------------- |
| cmd_code | 8 | 1 | Command |
| request_id | 32(uint32) | 4 | Request id, need to be same as request packet for pairing |
| status | 8(uint8) | 1 | status code: `0` - success; others show in [status code table](#status-code-table) |
| body_len | 24(uint32) | 3 | Then length of `body` in bytes.
Max: 16 MB
If gzip is enabled, the value is after compress |
| body | Variable length, decide by `body_len` | variable length | `body`, max size: 16 MB |
| nonce | 64 | 8 | exists when `verify` is `1` |
| signature | 128 | 16 | exists when `verify` is `1` |
## Status Code Table
| value | flag | description |
| ----- | --------------------- | ----------------------------- |
| 0 | SUCCESS | Success like HTTP status 200 |
| 1 | SERVER_TIMEOUT | Timeout like HTTP status 408 |
| 3 | BAD_REQUEST | Bad Request like HTTP 400 |
| 5 | UNAUTHENTICATED | Unauthorized like HTTP 401 |
| 7 | SERVER_INTERNAL_ERROR | Internal server like HTTP 500 |
---
# Protocol Overview
URL: https://open.longbridge.com/docs/socket/protocol/overview.md
We use binary format data for communication, protocol support both `WebSocket` and `TCP`.
:::info
Endianness is `BigEndian`
:::
If your are familiar with `Python` or `C++`, we provider [SDK](https://open.longbridge.com/en/sdk) for you.
If you want parse protocol by self, you can check our [Go Implemetation](https://github.com/longbridge/openapi-protocol/tree/main/go).
The endponts of `WebSocket` and `TCP` can be found [here](../hosts).
Before start parse protocol, you should know our [Communication Model](./connect), we split to three type of communication:
- Handshake - For establishing connection
- Request and Response - Pairing data packet for handle api request
- Push - One peer send data to another, no need response
Depends on communication model, there are out typs of packet:
- [Handkeshake](./handshake)
- [Request](./request)
- [Response](./response)
- [Push](./push)
Data is in the `body` of the packet, current we only support [`Protobuf`](https://developers.google.com/protocol-buffers) for codec.
`Protobuf` definition can be found in:
- [Control command](../control-command)
- [Data command](../biz_command)
---
# Overnight Eligible Securities
URL: https://open.longbridge.com/docs/quote/security/security_list.md
Get the list of US stocks eligible for overnight trading.
# list of US overnight-eligible securities
longbridge security-list
### Request
HTTP Method GET
HTTP URL /v1/quote/get_security_list
#### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| -------- | ------ | -------- | ------------------------------------------- |
| market | string | YES | Market, currently only supports US |
| category | string | YES | Market subcategory, only supports Overnight |
#### Request Example
```python
from longbridge.openapi import QuoteContext, Config, Market, SecurityListCategory, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = QuoteContext(config)
resp = ctx.security_list(Market.US, SecurityListCategory.Overnight)
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncQuoteContext, Config, Market, SecurityListCategory, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncQuoteContext.create(config)
resp = await ctx.security_list(Market.US, SecurityListCategory.Overnight)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, QuoteContext, OAuth, SecurityListCategory } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = QuoteContext.new(config)
const resp = await ctx.securityList(SecurityListCategory.Overnight)
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
QuoteContext ctx = QuoteContext.create(config)) {
Security[] resp = ctx.getSecurityList(SecurityListCategory.Overnight).get();
for (Security s : resp) System.out.println(s);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, quote::QuoteContext, Config, quote::SecurityListCategory};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = QuoteContext::new(config);
let resp = ctx.security_list(SecurityListCategory::Overnight).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::quote;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
QuoteContext ctx = QuoteContext::create(config);
ctx.security_list(SecurityListCategory::Overnight, [](auto res) {
if (!res) { std::cout << "failed: " << *res.status().message() << std::endl; return; }
std::cout << "securities: " << res->size() << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
list, err := qctx.SecurityList(context.Background(), quote.MarketUS, quote.Overnight)
if err != nil {
log.Fatal(err)
}
fmt.Println("securities:", len(list))
}
```
### Response
#### Response Headers
- Content-Type: application/json
#### Response Example
```json
{
"code": 0,
"data": {
"list": [
{
"symbol": "BAC.US",
"name_cn": "美国银行",
"name_hk": "美國銀行",
"name_en": "Bank of America"
},
{
"symbol": "RDDT.US",
"name_cn": "REDDIT INC",
"name_hk": "REDDIT INC",
"name_en": "REDDIT INC"
},
{
"symbol": "GOOGL.US",
"name_cn": "谷歌-A",
"name_hk": "谷歌-A",
"name_en": "Alphabet"
}
]
}
}
```
#### Response Status
| Status | Description | Schema |
| ------ | ----------------- | ------------------------------------------- |
| 200 | Successful return | [security_response](#get_security_list_rsp) |
| 400 | Parameter error | None |
## Schemas
### security_response
| Name | Type | Required | Description |
| --------- | -------- | -------- | ------------------------ |
| list | object[] | false | List |
| ∟ symbol | integer | true | Security code |
| ∟ name_cn | string | true | Chinese name |
| ∟ name_hk | string | true | Traditional Chinese name |
| ∟ name_en | string | true | English name |
## Error Code
| Business Error Code | Description | Troubleshooting Suggestion |
| ------------------- | --------------------- | ----------------------------------------- |
| 310010 | Invalid request | Check the request parameters |
| 310011 | Internal server error | Please retry or contact technical support |
---
# Get Socket OTP (One-Time Password)
URL: https://open.longbridge.com/docs/socket-token-api.md
# Get OTP (One Time Password) API
Our socket `Token` is one time password, you can use the `Token` to connect to quote or trade gateway. It will be expired after authing.
> Last Update at 2022-04-28
## API
| Info | |
| ----------- | ---------------- |
| HTTP Method | GET |
| HTTP URL | /v1/socket/token |
### Request Headers
| Field | Type | Required | description |
| ------------- | ------ | -------- | ----------------------------------------------------- |
| Authorization | string | Yes | |
| Content-Type | string | Yes | **Fixed Contents**: "application/json; charset=utf-8" |
### Request Parameters
## Response
### Response Body
| Field | Type | Description |
| ------- | ------ | --------------------------------- |
| code | int | error code, failed if not equal 0 |
| msg | string | error description |
| data | object | |
| ∟otp | string | token |
| ∟limit | int | Total connection limit |
| ∟online | int | Current online connection count |
### Response Example
```json
{
"code": 0,
"message": "",
"data": {
"otp": "xxxxxxxx",
"online": 1,
"limit": 10
}
}
```
---
# API Reference Standards
URL: https://open.longbridge.com/docs/style-guide/api-reference.md
# API Reference Standards
The API Reference is grounded in `openapi.yaml`. Writing in this area means maintaining the spec first, then the rendered pages.
## Source of truth
`openapi.yaml` is the single source of truth for all API endpoints. Never invent parameter names, types, or response fields in the documentation — always check the spec first. When the docs and spec conflict, fix the spec, then the docs.
---
## Resource naming
Each resource is a top-level grouping of related endpoints.
- **Name:** short noun phrase — "Quotes", "Orders", "Positions"
- **Description:** one sentence, high-level — what operations this resource covers
---
## Endpoint titles and descriptions
### Title format
Use **imperative verb + object noun phrase** — active voice.
| Good | Bad |
|------|-----|
| "Get static quote" | "Static quote retrieval" |
| "Submit order" | "Order submission" |
| "List today's orders" | "Getting today's orders" |
**Standard verbs by HTTP method:**
| HTTP Method | Preferred verbs |
|-------------|----------------|
| GET (single resource) | Get |
| GET (collection) | List |
| POST (create) | Create, Submit, Place |
| POST (action) | Send, Trigger, Execute |
| PUT / PATCH | Update, Modify |
| DELETE | Delete, Cancel, Remove |
Use the root form of the verb in the title — not the gerund. "Submit an order", not "Submitting an order".
### Description format
Write the description in **third-person singular present tense**: "Filters…", "Returns…", "Lists…". Do not use the imperative form ("Filter…", "Return…", "List…") — the imperative is for titles; descriptions use the declarative form.
One to two sentences. Explain what the endpoint does and when to use it. Write for developers who may not know the business domain.
**Prohibited patterns:**
Do not start a description with any of these phrases:
- "The API is used to…"
- "This endpoint can be used to…"
- "This endpoint is used to…"
Use a direct active verb instead: "Returns the available balance…", "Submits a limit order…", "Lists orders placed today…".
---
## Parameter and field descriptions
- Every required parameter must have a description
- Descriptions: one sentence; explain the value's meaning in business terms, not just the data type
- Include valid values or ranges where bounded
- Timestamps: note the format and timezone — Unix timestamp in seconds, UTC unless otherwise stated
---
## Request examples
- Include a working cURL example for every endpoint
- Always include `Content-Type: application/json` header for requests with a body
- Do not pipe through `jq` — keep examples dependency-free
- Use realistic but non-sensitive placeholder values — real ticker symbols like `AAPL.US`, `700.HK`, `TSLA.US`
:::info Existing pages
Many existing endpoint pages lack a cURL example. All new and updated endpoint pages must include one. Existing pages without cURL are not retroactively invalid until edited.
:::
---
## Response examples
- Show a representative successful response
- Do not show error responses inline — link to the error code reference
---
## Deprecated endpoints
When an endpoint is deprecated:
1. Add `deprecated: true` to the OpenAPI spec
2. Add this notice at the top of the endpoint description: "Deprecated. Use [alternative] instead. This endpoint will be removed on [full date, e.g. August 1, 2027]."
3. Link to the replacement endpoint or migration guide
4. Do not remove the endpoint from the spec until the end-of-life date passes
---
## `` component
All API endpoint doc pages must include the `` component to link to SDK-specific method documentation:
```markdown
```
| Attribute | Description |
|-----------|-------------|
| `module` | Lowercase domain name — `trade`, `quote`, `account` |
| `klass` | SDK context class name — `TradeContext`, `QuoteContext` |
| `method` | snake_case method name as defined in the Rust SDK |
---
# Content Types
URL: https://open.longbridge.com/docs/style-guide/content-types.md
# Content Types
Every page must have exactly one content type. The type is fixed at creation and determines the page's required sections, title format, and placement in the site. A page that mixes two content types must be split into separate pages.
## Content type taxonomy
| Type | Required per product area? | Primary audience |
|------|---------------------------|-----------------|
| [Overview](#overview) | Yes | Developers discovering a product area |
| [Get Started](#get-started) | Yes | Developers starting integration |
| [Concept](#concept) | As needed | Developers needing background knowledge |
| [How-to Guide](#how-to-guide) | As needed | Developers completing a specific task |
| [Implementation Guide](#implementation-guide) | As needed | Developers building end-to-end integrations |
| [Reference](#reference) | As needed | Developers looking up values or limits |
| [Changelog](#changelog) | Yes (site-wide) | All developers tracking platform changes |
| [FAQ / Troubleshooting](#faq--troubleshooting) | As needed | Developers who are stuck |
| [API Endpoint Doc](#api-endpoint-doc) | Per endpoint | Developers making specific API calls |
---
## Overview
**Purpose:** Welcome developers to a product area and orient them.
**Required sections:**
- One-paragraph product description — what it does and when to use it
- Key capabilities (bullet list or table)
- Next steps / navigation links to child pages
**Rules:**
- Must be the first page (`index.md`) in any nested navigation section
- Do not bury setup instructions here — link to Get Started
- If the overview adds no value beyond a table of contents, remove it and promote child pages directly
**Title format:** noun phrase matching the product area — "Market Data", "Trading", "Quote API"
---
## Get Started
**Purpose:** Take a developer from zero to their first working integration.
**Required sections:**
1. Prerequisites (account, permissions, installed tools)
2. Installation / setup steps (numbered)
3. A minimal working example
4. Next steps (link to deeper guides)
**Rules:**
- Must exist at the top level of every major product area
- Steps must be numbered and actionable — no vague guidance
- The working example must actually run without modification beyond credentials
- One path only — pick the recommended approach (OAuth, not legacy API key as the primary example)
- Do not embed reference tables (environment variables, legacy API key details) inline — link to a dedicated Reference page instead
- A Get Started page over ~400 lines is a signal that reference content must be extracted
**Title format:** "Get started with [product area]" or plain "Get Started"
---
## Concept
**Purpose:** Explain background knowledge developers need before using a feature.
**When to create:** When a term, behavior, or design decision requires explanation that does not fit inline in a how-to — for example: "WebSocket connection model", "Quote subscription model", "Order types".
**Required sections:**
- A clear definition in the first paragraph
- How it relates to the developer's work
- Links to related how-to guides
**Rules:**
- No step-by-step instructions — concepts explain, they do not instruct
- Keep to one concept per page; cross-link related concepts
**Title format:** noun phrase — "Quote subscription model", "Order lifecycle"
---
## How-to Guide
**Purpose:** Step-by-step instructions for a specific, bounded task.
**Required sections:**
1. Prerequisites
2. Numbered steps
3. Expected result
**Rules:**
- Each step = one action + its expected outcome; never multi-action steps
- Code examples must be complete and runnable for the target language
- Do not explain concepts inline — link to a concept page instead
**Title format:** imperative verb phrase — "Subscribe to real-time quotes", not "Subscribing to quotes"
---
## Implementation Guide
**Purpose:** End-to-end walkthrough for achieving a specific integration goal that spans multiple API areas.
Examples: "Build a real-time quote dashboard", "Automate a DCA strategy with the Trade API".
**Required sections:**
1. What you'll build (2–3 sentences + diagram if helpful)
2. Prerequisites
3. Numbered implementation steps
4. Complete working code
5. Next steps
**Rules:**
- Scope to a concrete outcome, not a feature tour
- Longer than a how-to — but keep it focused on the stated goal
**Title format:** imperative verb phrase describing the outcome — "Build a real-time quote dashboard"
---
## Reference
**Purpose:** Enumerate values, limits, error codes, field definitions, or configuration options.
**Rules:**
- Table-first format — minimize prose
- Keep in sync with `openapi.yaml` for anything covered by the spec
- Do not duplicate API Reference content here; link to it instead
---
## Changelog
**Purpose:** Record platform-level changes visible to developers.
**Rules:**
- One entry per date (`## YYYY-MM-DD`), newest first
- Each entry: 1–3 bullet points, user-facing value only (no internal jargon)
- CLI releases: sub-heading `### CLI vX.Y.Z` with link to GitHub release
- All three language versions updated simultaneously
---
## FAQ / Troubleshooting
**Purpose:** Answer the top questions and unblock common failure modes.
**Rules:**
- FAQ: question as heading (`### Why does X happen?`), concise answer below
- Troubleshooting: symptom → cause → fix structure
- Keep entries short; if the fix requires multiple steps, link to a how-to
---
## API Endpoint Doc
**Purpose:** Technical reference for a single HTTP or WebSocket API endpoint.
**Required sections** (in this order):
1. One-sentence description in active voice (third-person present: "Returns…", "Filters…", "Lists…")
2. `` block — if a CLI command maps to this endpoint
3. `` component — required on all API endpoint pages (see [API Reference Standards](./api-reference#sdklinks-component))
4. `## Request` — HTTP method + URL table; then `### Parameters` table (name / type / required / description); then `### Request Example` using `` (see [Writing Guidelines](./writing-guidelines#multi-language-tabs)) with all supported SDK languages
5. `## Response` — response headers, `### Response Example` (JSON), `### Response Status` (status code table)
6. `## Schemas` — field definition tables for complex nested types
**Rules:**
- One endpoint per page — never combine two endpoints on a single page
- All parameter names, types, and required/optional flags must match `openapi.yaml` exactly
- Do not invent parameters or response fields not in the spec
**Title format:** imperative verb + object noun — "Get static quote", "Submit order"
**Valid frontmatter fields:** `title`, `id`, `slug`, `sidebar_position`, `sidebar_icon`
**Deprecated frontmatter fields** (from a legacy Slate-based system; remove when editing existing pages):
`language_tabs`, `toc_footers`, `includes`, `highlight_theme`, `headingLevel`
---
# Documentation Style Guide
URL: https://open.longbridge.com/docs/style-guide.md
# Documentation Style Guide
Standards and guidelines for creating and maintaining documentation on the Longbridge Developers platform (`open.longbridge.com`).
These guidelines apply to all documentation contributors: human writers, AI agents, and API engineers. Consistent, well-structured documentation reduces time-to-first-working-integration and builds developer confidence across the platform.
## What's in this guide
| Page | What it covers |
|------|----------------|
| [Content Types](/docs/style-guide/content-types) | The nine content types — when to use each, required sections, and title format |
| [Information Architecture](/docs/style-guide/information-architecture) | Standard user journey, sidebar ordering, and mixed-content rules |
| [API Reference Standards](/docs/style-guide/api-reference) | Endpoint titles, parameter descriptions, cURL examples, and deprecation handling |
| [Writing Guidelines](/docs/style-guide/writing-guidelines) | Voice, headings, code examples, callout boxes, links, and tables |
| [Multilingual and Frontmatter](/docs/style-guide/multilingual) | Three-language sync rules, frontmatter fields, and what not to write |
## Content architecture
The site has **one unified content directory** — there is no separate `api/` directory. All documentation lives under `docs/{lang}/docs/`.
| Area | Path | Purpose |
|------|------|---------|
| **Docs** | `docs/{lang}/docs/` | Scenario-based guides, tutorials, and conceptual background |
| **API endpoint docs** | `docs/{lang}/docs/{domain}/{endpoint}.md` | Per-endpoint reference: HTTP method, parameters, request/response examples |
| **Interactive API reference** | `docs/en/docs/api.md` | Single special page with `layout: api-reference` that renders `openapi.yaml` interactively via `` |
Docs explains *how to use* the platform. API endpoint docs explain *what* each endpoint does. These two areas share the same directory tree and must not be blended on a single page.
---
# Information Architecture
URL: https://open.longbridge.com/docs/style-guide/information-architecture.md
# Information Architecture
## Standard user journey
Every product area in Docs follows this standard user journey. The order is intentional — it mirrors how a developer progresses from discovery to mastery.
```
Overview ← required: welcome + capabilities
Get Started ← required: first working integration
Concepts ← as needed: background knowledge
How-to guides ← as needed: specific tasks
Implementation ← as needed: end-to-end scenarios
Reference ← as needed: enumerations, limits, codes
Troubleshooting ← as needed: common failures
FAQ ← as needed: common questions
```
**Rules:**
- Overview and Get Started are required for every top-level product area
- Concepts come before how-tos — don't force developers to learn concepts mid-task
- Troubleshooting and FAQ go last — developers reach them when stuck
- Sidebar order reflects the user journey above; use `sidebar_position` to enforce it
### `sidebar_position` reference
Use these ranges to enforce the user-journey order. Gaps between ranges leave room for future pages without requiring a full renumber.
| Content type | Typical `sidebar_position` |
|---|---|
| Overview | 0 |
| Get Started | 1 |
| Concepts | 10–19 |
| How-to guides | 20–49 |
| Implementation guides | 50–69 |
| Reference | 70–89 |
| Troubleshooting / FAQ | 90+ |
---
## Mixed-content-type pages
A page with more than one content type must be split into separate pages. The only permitted exception is a designated entry-point page (for example, the top-level Get Started) that links out to reference material instead of embedding it.
**Signs a page needs to be split:**
- The page has both numbered how-to steps and reference tables
- The page is over ~400 lines and contains embedded reference content (env vars, API key details)
- The page title does not accurately describe all the content on it
### `getting-started.md` ruling
Keep the top-level `getting-started.md` as a single Get Started page. Do not embed environment variable reference tables, legacy API key configuration details, or language-specific reference material inline. Move such content to a dedicated Reference page and link to it from the Get Started page.
A Get Started page over ~400 lines is a reliable signal that reference content must be extracted.
---
## Directory structure
### New product area checklist
When adding a new product area (for example, "DCA"):
1. Create `docs/{lang}/docs/dca/` in all three locales
2. Add `_category_.json` with `position`, `label`, and `collapsed`
3. Create `index.md` (Overview) as the first page
4. Create `get-started.md` as the second page
5. Add Concept, How-to, and Reference pages as needed
6. Assign `sidebar_position` values following the reference table above
### Top-level standalone pages
Top-level standalone pages (for example, pricing, about) must use a folder structure:
```
docs/pricing/index.md ✓ → URL: /pricing
docs/pricing.md ✗ → generates /pricing.html, causes 404
```
Nginx resolves `/pricing` to `pricing/index.html`. A flat `pricing.md` file generates `pricing.html` and causes a 404.
---
# Multilingual and Frontmatter
URL: https://open.longbridge.com/docs/style-guide/multilingual.md
# Multilingual and Frontmatter
## Three-language rule
Every `.md` page must exist in all three directories:
- `docs/en/` — English, primary; served at `/docs/...`
- `docs/zh-CN/` — Simplified Chinese; served at `/zh-CN/docs/...`
- `docs/zh-HK/` — Traditional Chinese; served at `/zh-HK/docs/...`
English is the source of truth. `zh-CN` and `zh-HK` follow English structure and content. Never add a page to only one language directory.
:::info Exception
Files under `docs/en/docs/style-guide/` are English-only and exempt from the three-language rule — they are contributor guidelines, not product documentation.
:::
---
## Translation scope
| Element | Translate? |
|---------|-----------|
| Prose and headings | Yes |
| Code sample comments | Yes — translate the comment text only |
| Code identifiers, string literals | No — keep identical to English |
| CLI command names and flags | No |
| Frontmatter `title` | Yes |
| Frontmatter `slug` and `id` | No — must be identical across locales |
---
## Sync discipline
When updating an English page:
1. Update the English page
2. Update `zh-CN` to match
3. Update `zh-HK` to match
All three changes go in the same commit. Never merge a change that updates only one or two locales.
---
## Page frontmatter
Every `.md` file requires this frontmatter block:
```yaml
---
title: 'Page Title'
id: category_filename # e.g., quote_pull-static — stable identifier, no spaces
slug: '/quote/pull/static' # absolute path, must start with /
sidebar_position: 3 # lower = higher in sidebar
sidebar_icon: book # optional; book_open | book | zap | cpu | terminal | sparkles
---
```
### Field rules
| Field | Required | Rule |
|-------|----------|------|
| `title` | Yes | Translated in zh-CN and zh-HK |
| `id` | Yes | Identical across all locales; missing `id` breaks cross-locale link resolution |
| `slug` | Yes | Absolute path starting with `/`; a slug without a leading `/` is a violation |
| `sidebar_position` | Yes | Assign deliberately following the [user-journey order](./information-architecture) |
| `sidebar_icon` | No | Valid values: `book_open`, `book`, `zap`, `cpu`, `terminal`, `sparkles` |
### Deprecated frontmatter fields
The following fields are carried over from a legacy Slate/Swagger doc system. Do not add them to new pages. Remove them when editing an existing page.
`language_tabs`, `toc_footers`, `includes`, `highlight_theme`, `headingLevel`
---
## What not to write
**Do not duplicate the API spec in Docs.** If a parameter is fully described in the API Reference, link there — do not copy the table.
**Do not write aspirational content.** "You can build amazing trading bots", "Start today!" — cut it. Describe what exists, not what could be built.
**Do not write feature announcements in Docs.** That belongs in the Changelog.
**Do not describe SDK internals.** Docs covers what developers call, not how the SDK is implemented. Do not mention the implementation language (e.g., "SDK is implemented based on Rust") or internal architecture in user-facing documentation.
**Do not add inapplicable caveats.** Qualifier bloat erodes trust. Only warn about things that can actually affect the reader's scenario.
**Do not mix content types on one page.** A page with both how-to steps and reference tables must be split. See [Content Types](./content-types) and [Information Architecture](./information-architecture).
---
# Writing Guidelines
URL: https://open.longbridge.com/docs/style-guide/writing-guidelines.md
# Writing Guidelines
## Voice and tone
- **Second person:** "you" for the developer — not "the user" or "the developer"
- **Active voice:** "Call the endpoint", not "The endpoint should be called"
- **Present tense:** "The API returns…", not "The API will return…"
- **Concise:** one idea per sentence; remove filler phrases — "In order to", "Please note that"
---
## Headings
- **Sentence case:** "Get static quote", not "Get Static Quote"
- **Be specific:** "Subscribe to real-time quotes", not "Subscription"
- **No gerunds in titles:** "Submit an order", not "Submitting an order"
---
## Code examples
Every how-to, implementation guide, and Get Started page must have runnable code. Code must be verifiable — do not include examples that cannot be tested (trade-execution examples are exempt).
Use real symbols: prefer US stocks (`AAPL.US`, `TSLA.US`, `NVDA.US`) and `700.HK` as examples.
### Multi-language tabs
Use `` for SDK code examples.
**Language order:** Python, JavaScript, Rust, Go, Java, C++
**Tab labels:** Use `JavaScript` as the label for the Node.js/JavaScript SDK tab. Do not use `Node.js` — inconsistent labels break cross-page tab sync. Existing pages that use `Node.js` as a label must be corrected when the page is edited.
The `python-async` tab is optional. Include it only when async usage meaningfully differs from the sync example — for example, when the async version uses a different context class such as `AsyncTradeContext` vs `TradeContext`, or requires a different import pattern. Do not include it when the only difference is adding `await`.
**Standard `groupId` values:**
| `groupId` | Use case |
|-----------|----------|
| `programming-language` | SDK code examples by language |
| `cli-install` | CLI installation steps by OS or method |
| `shell` | Shell variant differences |
Do not use ad-hoc `groupId` values. Inconsistent values break cross-page tab-sync behavior.
### `` rules
- Comments go *before* the command, not inline
- Multi-command blocks require a comment before each command
- Single-command blocks with self-explanatory commands (e.g., `longbridge auth login`) may omit the comment
- Provide 2–4 examples using real ticker symbols; prefer US stocks
- Do not use angle-bracket placeholders like `` — Vue parses them as HTML tags and breaks the build; use a numeric example with a preceding comment instead
**Example:**
```markdown
# Get real-time quote for Apple
longbridge quote AAPL.US
# Get quotes for multiple symbols
longbridge quote AAPL.US TSLA.US 700.HK
```
---
## Callout boxes
Use sparingly. A callout that could be a sentence in the main text should be a sentence in the main text.
**Supported types:**
| Type | When to use |
|------|-------------|
| `:::tip` | Better alternatives, shortcuts, recommended practices |
| `:::info` | Background context the reader might not know |
| `:::warning` | Non-obvious gotchas that could cause silent failures |
| `:::danger` | Security implications, irreversible actions |
**Deprecated types** — migrate to the supported equivalent when editing a page:
| Deprecated | Migrate to |
|-----------|-----------|
| `:::success` | `:::tip` |
| `:::caution` | `:::warning` |
---
## Links
- Link to related pages on first mention of a concept
- Do not repeat the same link within one page
- External links: use descriptive text, not raw URLs
- `openapi.yaml` path references: link to the rendered API Reference page, not the YAML file
---
## Tables
Prefer Markdown table syntax. Raw HTML `` elements are acceptable only when the required structure — merged cells, `rowspan`, or `colspan` — cannot be expressed in standard Markdown. Do not use raw HTML tables purely for formatting preference.
---
## Language integrity
English pages must contain no Chinese characters — including inside code blocks, code comments, and string literals. If a code block was copied from a Chinese locale page, remove all CJK text before committing.
---
# Account Assets
URL: https://open.longbridge.com/docs/trade/asset/account.md
The API is used to obtain the available, desirable, frozen, to-be-settled, and in-transit
funds (fund purchase and redemption) information for each currency of the user.
longbridge assets
## Request
HTTP Method GET
HTTP URL /v1/asset/account
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| -------- | ------ | -------- | ------------------------ |
| currency | string | NO | Currency (HKD, USD, CNH) |
### Request Example
```python
from longbridge.openapi import TradeContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.account_balance()
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncTradeContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.account_balance()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, TradeContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = TradeContext.new(config)
const resp = await ctx.accountBalance()
for (const obj of resp) {
console.log(obj.toString())
}
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.trade.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id")
.build(url -> System.out.println("Open to authorize: " + url))
.get();
Config config = Config.fromOAuth(oauth);
TradeContext ctx = TradeContext.create(config)) {
AccountBalance[] resp = ctx.getAccountBalance().get();
for (AccountBalance obj : resp) {
System.out.println(obj);
}
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, trade::TradeContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = TradeContext::new(config);
let resp = ctx.account_balance(None).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::trade;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
TradeContext ctx = TradeContext::create(config);
ctx.account_balance([](auto res) {
if (!res) {
std::cout << "failed: " << *res.status().message() << std::endl;
return;
}
for (const auto& b : *res) {
std::cout << b.currency << " " << (double)b.available << std::endl;
}
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/trade"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
tctx, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer tctx.Close()
ab, err := tctx.AccountBalance(context.Background(), &trade.GetAccountBalance{})
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", ab[0])
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"data": {
"list": [
{
"total_cash": "1759070010.72",
"max_finance_amount": "977582000",
"remaining_finance_amount": "0",
"risk_level": "1",
"margin_call": "2598051051.50",
"currency": "HKD",
"net_assets": "24145.90",
"init_margin": "1540.09",
"maintenance_margin": "1540.09",
"buy_power": "1759070.12",
"cash_infos": [
{
"withdraw_cash": "97592.30",
"available_cash": "195902464.37",
"frozen_cash": "11579339.13",
"settling_cash": "207288537.81",
"currency": "HKD"
},
{
"withdraw_cash": "199893416.74",
"available_cash": "199893416.74",
"frozen_cash": "28723.76",
"settling_cash": "-276806.51",
"currency": "USD"
}
],
"frozen_transaction_fees": [
{
"currency": "USD",
"frozen_transaction_fee": "6.51"
}
]
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------- | ----------------------------------------- |
| 200 | Success | [accountcash_rsp](#schemaaccountcash_rsp) |
| 400 | Internal Error | None |
## Schemas
### accountcash_rsp
| Name | Type | Required | Description |
| -------------------------- | -------- | -------- | -------------------------------------------------------------------------------------------------------------------------------- |
| list | object[] | false | Account Balance |
| ∟ total_cash | string | true | Total Cash |
| ∟ max_finance_amount | string | true | Maximum Financing Amount |
| ∟ remaining_finance_amount | string | true | Remaining Financing Amount |
| ∟ risk_level | string | true | Risk control level
Option:
`0` - safe
`1` - medium risk
`2` - early warning
`3` - danger |
| ∟ margin_call | string | true | Margin Call |
| ∟ net_assets | string | true | net asset |
| ∟ init_margin | string | true | initial margin |
| ∟ maintenance_margin | string | true | maintenance margin |
| ∟ currency | string | true | Currency |
| ∟ buy_power | string | true | Buy Power |
| ∟ cash_infos | object[] | false | Cash Details |
| ∟∟ withdraw_cash | string | true | Withdraw Cash |
| ∟∟ available_cash | string | true | Available Cash |
| ∟∟ frozen_cash | string | true | Frozen Cash |
| ∟∟ settling_cash | string | true | Cash to be Settled |
| ∟∟ currency | string | true | Currency |
| ∟ frozen_transaction_fees | object[] | false | frozen fees |
| ∟∟ currency | string | false | currency |
| ∟∟ frozen_transaction_fee | string | false | frozen amount |
---
# Cash Flow
URL: https://open.longbridge.com/docs/trade/asset/cashflow.md
The API is used to obtain capital inflow/outflow direction, capital type, capital amount, occurrence time,
associated stock code and capital flow description information.
longbridge cash-flow
## Request
HTTP Method GET
HTTP URL /v1/asset/cashflow
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| ------------- | ------ | -------- | ----------------------------------------------------------------------------------------------------------- |
| start_time | string | YES | start time timestamp, in `seconds`, E.g:`1650037563` |
| end_time | string | YES | end time timestamp, in `seconds`, E.g:`1650747581` |
| business_type | string | NO | Balance type
Option:
`1` - cash
`2` - stock
`3` - fund |
| symbol | string | NO | Target code, E.g:`AAPL.US` |
| page | string | NO | start page
Default value: `1`
Data validation rules:
Ranges: `>=1` |
| size | string | NO | page size
Default value: `50`
Data validation rules: `1~10000` |
### Request Example
```python
from datetime import datetime
from longbridge.openapi import TradeContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.cash_flow(
start_at = datetime(2022, 5, 9),
end_at = datetime(2022, 5, 12),
)
print(resp)
```
```python
import asyncio
from datetime import datetime
from longbridge.openapi import AsyncTradeContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.cash_flow(
start_at = datetime(2022, 5, 9),
end_at = datetime(2022, 5, 12),
)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, TradeContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = TradeContext.new(config)
const resp = await ctx.cashFlow({ startAt: new Date(2022, 4, 9), endAt: new Date(2022, 4, 12) })
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.trade.*;
import java.time.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
TradeContext ctx = TradeContext.create(config)) {
GetCashFlowOptions opts = new GetCashFlowOptions(
OffsetDateTime.of(2022, 5, 9, 0, 0, 0, 0, ZoneOffset.UTC),
OffsetDateTime.of(2022, 5, 12, 0, 0, 0, 0, ZoneOffset.UTC));
CashFlow[] resp = ctx.getCashFlow(opts).get();
for (CashFlow c : resp) System.out.println(c);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, trade::{TradeContext, GetCashFlowOptions}, Config};
use time::macros::datetime;
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = TradeContext::new(config);
let opts = GetCashFlowOptions::new(datetime!(2022-05-09 0:00 UTC), datetime!(2022-05-12 0:00 UTC));
let resp = ctx.cash_flow(opts).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::trade;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
TradeContext ctx = TradeContext::create(config);
GetCashFlowOptions opts{}; ctx.account_balance(opts, [](auto res) {
if (!res) { std::cout << "failed" << std::endl; return; }
std::cout << "cashflow" << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/trade"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
tctx, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer tctx.Close()
start := time.Date(2024, 5, 1, 0, 0, 0, 0, time.UTC).Unix()
end := time.Date(2024, 6, 1, 0, 0, 0, 0, time.UTC).Unix()
flows, err := tctx.CashFlow(context.Background(), &trade.GetCashFlow{
StartAt: start,
EndAt: end,
BusinessType: trade.BalanceTypeCash,
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", flows)
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"data": {
"list": [
{
"transaction_flow_name": "BuyContract-Stocks",
"direction": 1,
"balance": "-248.60",
"currency": "USD",
"business_time": "1621507957",
"symbol": "AAPL.US",
"description": "AAPL"
},
{
"transaction_flow_name": "BuyContract-Stocks",
"direction": 1,
"balance": "-125.16",
"currency": "USD",
"business_time": "1621504824",
"symbol": "AAPL.US",
"description": "AAPL"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------- | ----------------------------------- |
| 200 | Success | [cashflow_rsp](#schemacashflow_rsp) |
| 400 | Internal Error | None |
## Schemas
### cashflow_rsp
| Name | Type | Required | Description |
| ----------------------- | -------- | -------- | -------------------------------------------------------------------------------------------- |
| list | object[] | false | Cash flow info |
| ∟ transaction_flow_name | string | true | Cash flow name |
| ∟ direction | string | true | outflow direction
Option:
`1` - outflow
`2` - inflow |
| ∟ business_type | string | true | Funding Category
Option:
`1` - cash
`2` - stock
`3` - fund |
| ∟ balance | string | true | Cash amount |
| ∟ currency | string | true | Cash Currency |
| ∟ business_time | string | true | business time |
| ∟ symbol | string | false | associated Stock code information |
| ∟ description | string | false | Cash flow description |
---
# Fund Positions
URL: https://open.longbridge.com/docs/trade/asset/fund.md
:::warning Longbridge HK / SG accounts only
This API is available to Longbridge HK / SG accounts only.
:::
The API is used to obtain fund position information including account, fund code, holding share, cost net worth,
current net worth, and currency.
longbridge fund-positions
## Request
HTTP Method GET
HTTP URL /v1/asset/fund
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| ------ | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| symbol | string[] | NO | Fund code, in `ISIN` format, E.g:`HK0000676327` ISIN explain |
### Request Example
```python
from longbridge.openapi import TradeContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.fund_positions()
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncTradeContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.fund_positions()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, TradeContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = TradeContext.new(config)
const resp = await ctx.fundPositions()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.trade.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
TradeContext ctx = TradeContext.create(config)) {
FundPositionsResponse resp = ctx.getFundPositions(null).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, trade::TradeContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = TradeContext::new(config);
let resp = ctx.fund_positions(None).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::trade;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
TradeContext ctx = TradeContext::create(config);
ctx.fund_positions(std::nullopt, [](auto res) {
if (!res) { std::cout << "failed" << std::endl; return; }
std::cout << "fund positions" << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/trade"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
tctx, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer tctx.Close()
positions, err := tctx.FundPositions(context.Background(), []string{"AAPL.US", "700.HK"})
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", positions)
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"data": {
"list": [
{
"account_channel": "lb",
"fund_info": [
{
"counter_id": "UT/FD/HK0000447943",
"symbol_name": "GAOTENG EMERGING MARKETS PLUS LONG/SHORT FIXED INCOME ALPHA FUND",
"currency": "USD",
"holding_units": "5.000",
"current_net_asset_value": "0",
"cost_net_asset_value": "0.00",
"net_asset_value_day": "1649865600"
}
]
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------- | --------------------------- |
| 200 | Success | [fund_rsp](#schemafund_rsp) |
| 400 | Internal Error | None |
## Schemas
### fund_rsp
| Name | Type | Required | Description |
| -------------------------- | -------- | -------- | ------------------------- |
| list | object[] | false | stock holding information |
| ∟ account_channel | string | true | account type |
| ∟ fund_info | object[] | false | Fund Details |
| ∟∟ counter_id | string | true | Fund counter id (last /-segment is the ISIN) |
| ∟∟ current_net_asset_value | string | true | current Equity |
| ∟∟ net_asset_value_day | string | true | current Equity time |
| ∟∟ symbol_name | string | true | Fund name |
| ∟∟ currency | string | true | Currency |
| ∟∟ cost_net_asset_value | string | true | Net Cost |
---
# Margin Ratio
URL: https://open.longbridge.com/docs/trade/asset/margin_ratio.md
:::warning Longbridge HK / SG accounts only
This API is available to Longbridge HK / SG accounts only.
:::
This API is used to obtain the initial margin ratio, maintain the margin ratio and strengthen the
margin ratio of stocks.
longbridge margin-ratio TSLA.US
## Request
HTTP Method GET
HTTP URL /v1/risk/margin-ratio
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| ------ | ------ | -------- | ---------------------------------------------------------------------- |
| symbol | string | YES | Stock symbol, using the format `ticker.region`, for example: `AAPL.US` |
### Request Example
```python
from datetime import datetime
from longbridge.openapi import TradeContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.margin_ratio("700.HK")
print(resp)
```
```python
import asyncio
from datetime import datetime
from longbridge.openapi import AsyncTradeContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.margin_ratio("700.HK")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, TradeContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = TradeContext.new(config)
const resp = await ctx.marginRatio('700.HK')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.trade.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
TradeContext ctx = TradeContext.create(config)) {
MarginRatio resp = ctx.getMarginRatio("700.HK").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, trade::TradeContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = TradeContext::new(config);
let resp = ctx.margin_ratio("700.HK").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::trade;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
TradeContext ctx = TradeContext::create(config);
ctx.margin_ratio("700.HK", [](auto res) {
if (!res) { std::cout << "failed" << std::endl; return; }
std::cout << "margin_ratio" << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/trade"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
tctx, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer tctx.Close()
mr, err := tctx.MarginRatio(context.Background(), "700.HK")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", mr)
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"data": {
"im_factor": "0.1",
"mm_factor": "0.1",
"fm_factor": "0.1"
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------- | ------------------------------------------- |
| 200 | Success | [margin_ratio_rsp](#schemamargin_ratio_rsp) |
| 400 | Internal Error | None |
## Schemas
### margin_ratio_rsp
| Name | Type | Required | Description |
| --------- | ------ | -------- | --------------------------------- |
| im_factor | string | true | Initial margin ratio |
| mm_factor | string | true | Maintain the initial margin ratio |
| fm_factor | string | true | Forced close-out margin ratio |
---
# Stock Positions
URL: https://open.longbridge.com/docs/trade/asset/stock.md
The API is used to obtain stock position information including account, stock code, number of shares held,
number of available shares, average position price (calculated according to account settings), and currency.
longbridge positions
## Request
HTTP Method GET
HTTP URL /v1/asset/stock
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| ------ | -------- | -------- | ----------------------------------------------------- |
| symbol | string[] | NO | Stock code, use `ticker.region` format, E.g:`AAPL.US` |
### Request Example
```python
from longbridge.openapi import TradeContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.stock_positions()
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncTradeContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.stock_positions()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, TradeContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = TradeContext.new(config)
const resp = await ctx.stockPositions()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.trade.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
TradeContext ctx = TradeContext.create(config)) {
StockPositionsResponse resp = ctx.getStockPositions(null).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, trade::TradeContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = TradeContext::new(config);
let resp = ctx.stock_positions(None).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::trade;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
TradeContext ctx = TradeContext::create(config);
ctx.stock_positions(std::nullopt, [](auto res) {
if (!res) { std::cout << "failed" << std::endl; return; }
std::cout << "positions" << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/trade"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
tctx, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer tctx.Close()
positions, err := tctx.StockPositions(context.Background(), []string{"AAPL.US", "700.HK"})
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", positions)
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"data": {
"list": [
{
"account_channel": "lb",
"stock_info": [
{
"symbol": "700.HK",
"symbol_name": "TENCENT",
"currency": "HKD",
"quantity": "650",
"market": "HK",
"available_quantity": "-450",
"cost_price": "457.53",
"init_quantity": "214"
},
{
"symbol": "9991.HK",
"symbol_name": "BAOZUN-SW",
"currency": "HKD",
"market": "HK",
"quantity": "200",
"available_quantity": "0",
"cost_price": "32.25",
"init_quantity": "214"
},
{
"symbol": "TCEHY.US",
"symbol_name": "Tencent (ADR)",
"currency": "USD",
"market": "US",
"quantity": "10",
"available_quantity": "10",
"init_quantity": "18"
},
{
"symbol": "2628.HK",
"symbol_name": "CHINA LIFE",
"currency": "HKD",
"market": "HK",
"quantity": "9000",
"available_quantity": "0",
"init_quantity": "8000"
},
{
"symbol": "5.HK",
"symbol_name": "HSBC HOLDINGS",
"currency": "HKD",
"market": "HK",
"quantity": "2400",
"available_quantity": "2000",
"init_quantity": "2000"
},
{
"symbol": "BABA.US",
"symbol_name": "Alibaba",
"currency": "USD",
"market": "US",
"quantity": "2000209",
"available_quantity": "2000209",
"init_quantity": "214"
},
{
"symbol": "2.HK",
"symbol_name": "CLP HOLDINGS",
"currency": "HKD",
"market": "HK",
"quantity": "2000",
"available_quantity": "2000",
"init_quantity": "2000"
},
{
"symbol": "NOK.US",
"symbol_name": "Nokia",
"currency": "USD",
"market": "US",
"quantity": "1",
"available_quantity": "0",
"init_quantity": "1"
}
]
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------- | ----------------------------- |
| 200 | Success | [stock_rsp](#schemastock_rsp) |
| 400 | Internal Error | None |
## Schemas
### stock_rsp
| Name | Type | Required | Description |
| --------------------- | -------- | -------- | -------------------------------------------------------------------------------- |
| list | object[] | false | Stock holding information |
| ∟ account_channel | string | true | Account type |
| ∟ stock_info | object[] | false | Stock list |
| ∟∟ symbol | string | true | Stock code |
| ∟∟ symbol_name | string | true | Stock name |
| ∟∟ quantity | string | true | The number of holdings |
| ∟∟ available_quantity | string | false | Available quantity |
| ∟∟ currency | string | true | Currency |
| ∟∟ market | string | true | market |
| ∟∟ cost_price | string | true | Cost Price(According to the client's choice of average purchase or diluted cost) |
| ∟∟ init_quantity | string | false | Initial position before market opening |
---
# Definition
URL: https://open.longbridge.com/docs/trade/trade-definition.md
## OrderType
- Description: HongKong stock support order type
| Enum | Description |
| ------- | ----------------------------------------------- |
| LO | Limit Order |
| ELO | Enhanced Limit Order |
| MO | Market Order |
| AO | At-auction Order |
| ALO | At-auction Limit Order |
| ODD | Odd Lots Order |
| LIT | Limit If Touched |
| MIT | Market If Touched |
| TSLPAMT | Trailing Limit If Touched (Trailing Amount) |
| TSLPPCT | Trailing Limit If Touched (Trailing Percent) |
| SLO | Special Limit Order. Not Support Replace Order. |
- Description: US stock support order type
| Enum | Description |
| ------- | --------------------------------------------- |
| LO | Limit Order |
| MO | Market Order |
| LIT | Limit If Touched |
| MIT | Market If Touched |
| TSLPAMT | Trailing Limit If Touched (Trailing Amount) |
| TSLPPCT | Trailing Limit If Touched (Trailing Percent) |
## OrderStatus
- Description: Order Status
| Enum | Description |
| -------------------- | ------------------------------- |
| NotReported | NotReported |
| ReplacedNotReported | NotReported (Replaced Order) |
| ProtectedNotReported | NotReported (Protected Order) |
| VarietiesNotReported | NotReported (Conditional Order) |
| DelayedNotReported | Monitoring (Time-Conditional Order)|
| FilledStatus | Filled |
| WaitToNew | Wait To New |
| NewStatus | New |
| WaitToReplace | Wait To Replace |
| PendingReplaceStatus | Pending Replace |
| ReplacedStatus | Replaced |
| PartialFilledStatus | Partial Filled |
| WaitToCancel | Wait To Cancel |
| PendingCancelStatus | Pending Cancel |
| RejectedStatus | Rejected |
| CanceledStatus | Canceled |
| ExpiredStatus | Expired |
| PartialWithdrawal | Partial Withdrawal |
## Market
- Description: Market
| Enum | Description |
| ---- | ------------------------------- |
| HK | Hong Kong Market |
| US | United States of America Market |
## WebSocket Notification
- Description: Push notification field description
| field | type | Description |
| ------------------ | ------ | --------------------------------------------------------------------------------------------------------------------- |
| side | string | order side
**Enum Value**
`Buy`
`Sell` |
| stock_name | string | stock name |
| submitted_quantity | string | submitted quantity |
| symbol | string | order symbol |
| order_type | string | [Order Type](./trade-definition#ordertype) |
| submitted_price | string | submitted price |
| executed_quantity | string | executed quantity |
| executed_price | string | executed price |
| order_id | string | order id |
| currency | string | currency |
| status | string | [order status](./trade-definition#orderstatus) |
| submitted_at | string | submitted time, formatted as a timestamp (second) |
| updated_at | string | last updated time, formatted as a timestamp (second) |
| trigger_price | string | "`LIT` / `MIT` order trigger price" |
| msg | string | rejected message or remark |
| tag | string | order tag
**Enum Value**
`Normal` - Normal Order
`GTC` - Long term Order
`Grey` - Grey Order |
| trigger_status | string | conditional order trigger status
**Enum Value**
`NOT_USED`
`DEACTIVE`
`ACTIVE`
`RELEASED` |
| trigger_at | string | conditional order trigger time. formatted as a timestamp (second) |
| trailing_amount | string | "`TSLPAMT` order trailing amount" |
| trailing_percent | string | "`TSLPPCT` order trailing percent" |
| limit_offset | string | "`TSLPAMT` / `TSLPPCT` order limit offset amount" |
| account_no | string | account no |
| remark | string | remark message |
| last_share | string | last share |
| last_price | string | last price |
| multi_leg | object | Multi-leg strategy information. Only pushed for multi-leg option combination orders |
| ∟ strategy | string | Multi-leg strategy
**Enum Value**
`0` - CoveredCall (Covered stock)
`1` - CoveredPut (Covered stock)
`2` - VerticalCallSpread (Vertical spread)
`3` - VerticalPutSpread (Vertical spread)
`4` - Collar
`5` - Straddle
`6` - Strangle
`7` - CalendarCallSpread (Calendar)
`8` - CalendarPutSpread (Calendar) |
| ∟ strategy_name | string | strategy name |
| ∟ multileg_id | string | multi-leg combination ID |
| ∟ code | string | multi-leg combination code |
| ∟ legs | object[] | legs of the combination order |
| ∟∟ symbol | string | option symbol, use `ticker.region` format |
| ∟∟ side | string | order side
**Enum Value**
`Buy`
`Sell` |
| ∟∟ position | string | position direction
**Enum Value**
`LONG`
`SHORT` |
| ∟∟ ratio_quantity | string | leg ratio quantity |
| ∟∟ strike_price | string | strike price |
| ∟∟ expire_date | string | option expiry date, format: `YYYYMMDD` |
| ∟∟ contract_direction | string | contract type
**Enum Value**
`C` - Call
`P` - Put |
### example
```JSON
{
"event": "order_changed_lb",
"data": {
"side": "Buy",
"stock_name": "Tencent Holdings Ltd.",
"submitted_quantity": "1000",
"symbol": "700.HK",
"order_type": "LO",
"submitted_price": "213.2",
"executed_quantity": "1000",
"executed_price": "213.2",
"order_id": "27",
"currency": "HKD",
"status": "NewStatus",
"submitted_at": "1562761893",
"updated_at": "1562761893",
"trigger_price": "213.0",
"msg": "Insufficient Qty - 1000",
"tag": "GTC",
"trigger_status": "ACTIVE",
"trigger_at": "1562761893",
"trailing_amount": "5",
"trailing_percent": "1",
"limit_offset": "0.01",
"account_no": "HK123445",
"last_share": "100",
"last_price": "234",
"remark": "abc",
"multi_leg": {
"strategy": "2",
"strategy_name": "Vertical spread",
"multileg_id": "Spread_QQQ20260731C764/767",
"code": "QQQ 260731 764/767 Vertical spread",
"legs": [
{
"symbol": "QQQ260731C764000.US",
"side": "Buy",
"position": "LONG",
"ratio_quantity": "1",
"strike_price": "764",
"expire_date": "20260731",
"contract_direction": "C"
},
{
"symbol": "QQQ260731C767000.US",
"side": "Sell",
"position": "SHORT",
"ratio_quantity": "1",
"strike_price": "767",
"expire_date": "20260731",
"contract_direction": "C"
}
]
}
}
}
```
---
# All Executions
URL: https://open.longbridge.com/docs/trade/execution/all_executions.md
This API is used to query execution (fill) records, including both buy and sell records. It supports querying today's and historical executions at the same time.
## Request
HTTP Method GET
HTTP URL /v3/trade/execution/all
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| -------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| symbol | string | NO | Stock symbol, use `ticker.region` format, example: `AAPL.US` |
| order_id | string | NO | Order ID, example: `701276261045858304` |
| start_at | string | NO | Start time, formatted as a timestamp (second), example: `1650410999`.
If the start time is null, the default is the 90 days before of the end time or 90 days before of the current time. |
| end_at | string | NO | End time, formatted as a timestamp (second), example: `1650410999`.
If the end time is null, the default is the current time or 90 days after of the start time. |
| page | int32 | NO | Page number, starting from `1`. The maximum number of records per query is 1000. If the number of results exceeds 1000, `has_more` will be `true`, use `page` together with `has_more` to paginate. |
### Request Example
```python
from datetime import datetime
from longbridge.openapi import TradeContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.all_executions(
symbol = "700.HK",
start_at = datetime(2022, 5, 9),
end_at = datetime(2022, 5, 12),
)
print(resp)
```
```python
import asyncio
from datetime import datetime
from longbridge.openapi import AsyncTradeContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.all_executions(
symbol = "700.HK",
start_at = datetime(2022, 5, 9),
end_at = datetime(2022, 5, 12),
)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, TradeContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = TradeContext.new(config)
const resp = await ctx.allExecutions({ symbol: '700.HK' })
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.trade.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
TradeContext ctx = TradeContext.create(config)) {
AllExecutionsResponse resp = ctx.getAllExecutions(null).get();
for (Execution e : resp.getTrades()) System.out.println(e);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, trade::TradeContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = TradeContext::new(config);
let resp = ctx.all_executions(None).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::trade;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
TradeContext ctx = TradeContext::create(config);
ctx.all_executions(std::nullopt, [](auto res) {
if (!res) { std::cout << "failed" << std::endl; return; }
for (const auto& e : res->trades) std::cout << e.order_id << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/trade"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
tctx, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer tctx.Close()
start := time.Date(2022, 5, 9, 0, 0, 0, 0, time.UTC)
end := time.Date(2022, 5, 12, 0, 0, 0, 0, time.UTC)
resp, err := tctx.AllExecutions(context.Background(), &trade.GetAllExecutions{
Symbol: "700.HK",
StartAt: start,
EndAt: end,
})
if err != nil {
log.Fatal(err)
}
for _, e := range resp.Trades {
fmt.Println(e.OrderId)
}
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"has_more": false,
"trades": [
{
"order_id": "693664675163312128",
"price": "388",
"quantity": "100",
"symbol": "700.HK",
"trade_done_at": "1648611351",
"trade_id": "693664675163312128-1648611351433741210",
"side": "Buy"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------------------------------------------------- | ----------------------------------------------- |
| 200 | Get All Executions Success | [all_executions_rsp](#schemaall_executions_rsp) |
| 400 | The query failed with an error in the request parameter. | None |
## Schemas
### all_executions_rsp
| Name | Type | Required | Description |
| --------------- | -------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| has_more | boolean | true | has more orders record.
The maximum number of orders per query is 1000, if the number of results exceeds 1000, then has_more will be true |
| trades | object[] | false | Execution Detail |
| ∟ order_id | string | true | Order ID |
| ∟ trade_id | string | true | Execution ID |
| ∟ symbol | string | true | Stock symbol, use `ticker.region` format,example: `AAPL.US` |
| ∟ trade_done_at | string | true | Trade done time, formatted as a timestamp (second) |
| ∟ quantity | string | true | Executed quantity |
| ∟ price | string | true | Executed price |
| ∟ side | string | true | Trade side
**Enum Value:**
`Buy`
`Sell` |
---
# History Executions
URL: https://open.longbridge.com/docs/trade/execution/history_executions.md
This API is used to get history executions, including the sell and buy records, and does not support querying today's execution details.
longbridge order executions --history
## Request
HTTP Method GET
HTTP URL /v1/trade/execution/history
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| -------- | ------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| symbol | string | NO | Stock symbol, use `ticker.region` format, example: `AAPL.US` |
| start_at | string | NO | Start time, formatted as a timestamp (second), example: `1650410999`.
If the start time is null, the default is the 90 days before of the end time or 90 days before of the current time. |
| end_at | string | NO | End time, formatted as a timestamp (second), example: `1650410999`.
If the end time is null, the default is the current time or 90 days after of the start time. |
| page | int32 | NO | Page number, starting from `1`. The maximum number of records per query is 1000. If the number of results exceeds 1000, `has_more` will be `true`, use `page` together with `has_more` to paginate. |
### Request Example
```python
from datetime import datetime
from longbridge.openapi import TradeContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.history_executions(
symbol = "700.HK",
start_at = datetime(2022, 5, 9),
end_at = datetime(2022, 5, 12),
)
print(resp)
```
```python
import asyncio
from datetime import datetime
from longbridge.openapi import AsyncTradeContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.history_executions(
symbol = "700.HK",
start_at = datetime(2022, 5, 9),
end_at = datetime(2022, 5, 12),
)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, TradeContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = TradeContext.new(config)
const resp = await ctx.historyExecutions({})
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.trade.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
TradeContext ctx = TradeContext.create(config)) {
Execution[] resp = ctx.getHistoryExecutions(null).get();
for (Execution e : resp) System.out.println(e);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, trade::TradeContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = TradeContext::new(config);
let resp = ctx.history_executions(None).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::trade;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
TradeContext ctx = TradeContext::create(config);
ctx.history_executions(std::nullopt, [](auto res) {
if (!res) { std::cout << "failed" << std::endl; return; }
for (const auto& e : *res) std::cout << e.order_id << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/trade"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
tctx, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer tctx.Close()
start := time.Date(2024, 5, 1, 0, 0, 0, 0, time.UTC)
end := time.Date(2024, 5, 10, 0, 0, 0, 0, time.UTC)
executions, err := tctx.HistoryExecutions(context.Background(), &trade.GetHistoryExecutions{
Symbol: "AAPL.US",
StartAt: start,
EndAt: end,
})
if err != nil {
log.Fatal(err)
}
for _, e := range executions {
fmt.Println(e.OrderId)
}
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"has_more": false,
"trades": [
{
"order_id": "693664675163312128",
"price": "388",
"quantity": "100",
"side": "Buy",
"symbol": "700.HK",
"trade_done_at": "1648611351",
"trade_id": "693664675163312128-1648611351433741210"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------------------------------------------------- | ------------------------------------------------------- |
| 200 | Get History Executions Success | [history_executions_rsp](#schemahistory_executions_rsp) |
| 400 | The query failed with an error in the request parameter. | None |
## Schemas
### history_executions_rsp
| Name | Type | Required | Description |
| --------------- | -------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| has_more | boolean | true | has more orders record.
The maximum number of orders per query is 1000, if the number of results exceeds 1000, then has_more will be true |
| trades | object[] | false | Execution Detail |
| ∟ order_id | string | true | Order ID |
| ∟ trade_id | string | true | Execution ID |
| ∟ symbol | string | true | Stock symbol, use `ticker.region` format,example: `AAPL.US` |
| ∟ trade_done_at | string | true | Trade done time, formatted as a timestamp (second) |
| ∟ quantity | string | true | Executed quantity |
| ∟ price | string | true | Executed price |
| ∟ side | string | true | Trade side
**Enum Value:**
`Buy`
`Sell` |
---
# Today Executions
URL: https://open.longbridge.com/docs/trade/execution/today_executions.md
This API is used to get today executions.
longbridge order executions
## Request
HTTP Method GET
HTTP URL /v1/trade/execution/today
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| -------- | ------ | -------- | ------------------------------------------------------------ |
| symbol | string | NO | Stock symbol, use `ticker.region` format, example: `AAPL.US` |
| order_id | string | NO | Order ID, example: `701276261045858304` |
### Request Example
```python
from longbridge.openapi import TradeContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.today_executions(symbol = "700.HK")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncTradeContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.today_executions(symbol = "700.HK")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, TradeContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = TradeContext.new(config)
const resp = await ctx.todayExecutions({})
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.trade.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
TradeContext ctx = TradeContext.create(config)) {
Execution[] resp = ctx.getTodayExecutions(null).get();
for (Execution e : resp) System.out.println(e);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, trade::TradeContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = TradeContext::new(config);
let resp = ctx.today_executions(None).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::trade;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
TradeContext ctx = TradeContext::create(config);
ctx.today_executions(std::nullopt, [](auto res) {
if (!res) { std::cout << "failed" << std::endl; return; }
for (const auto& e : *res) std::cout << e.order_id << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/trade"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
tctx, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer tctx.Close()
executions, err := tctx.TodayExecutions(context.Background(), &trade.GetTodayExecutions{})
if err != nil {
log.Fatal(err)
}
for _, e := range executions {
fmt.Println(e.OrderId)
}
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"trades": [
{
"order_id": "693664675163312128",
"price": "388",
"quantity": "100",
"side": "Buy",
"symbol": "700.HK",
"trade_done_at": "1648611351",
"trade_id": "693664675163312128-1648611351433741210"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------------------------------------------------- | ------ |
| 200 | Get Today Executions Success | None |
| 400 | The query failed with an error in the request parameter. | None |
### Response Schema
## Schemas
### today_executions_rsp
| Name | Type | Required | Description |
| --------------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------- |
| trades | object[] | false | Execution Detail |
| ∟ order_id | string | true | Order ID |
| ∟ trade_id | string | true | Execution ID |
| ∟ symbol | string | true | Stock symbol, use `ticker.region` format, example: `AAPL.US` |
| ∟ trade_done_at | string | true | Trade done time, formatted as a timestamp (second) |
| ∟ quantity | string | true | Executed quantity |
| ∟ price | string | true | Executed price |
| ∟ side | string | true | Trade side
**Enum Value:**
`Buy`
`Sell` |
---
# Cancel Grid Order
URL: https://open.longbridge.com/docs/trade/grid/cancel.md
Cancel a grid order. The grid stops immediately and no further trigger orders are placed. Cancellation is permanent — a canceled grid cannot be restarted; submit a new grid order instead.
# Cancel a grid order by ID
longbridge grid cancel 764609681686573056
## Request
HTTP Method POST
HTTP URL /v1/gridtrading/cancel
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| -------- | ------ | -------- | -------------------------------------------- |
| order_id | string | YES | Grid order ID, example: `764609681686573056` |
### Request Example
```python
from longbridge.openapi import GridContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
# Grid REST calls go through the standalone GridContext
ctx = GridContext(config)
resp = ctx.cancel("764609681686573056")
print(resp)
```
```javascript
const { Config, GridContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = GridContext.new(config)
const resp = await ctx.cancel('764609681686573056')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.grid.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
GridContext ctx = GridContext.create(config)) {
ctx.cancel("764609681686573056").get();
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{Config, grid::GridContext, oauth::OAuthBuilder};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = GridContext::new(config);
ctx.cancel("764609681686573056").await?;
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::grid;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
GridContext ctx = GridContext::create(config);
ctx.cancel("764609681686573056", [](auto res) {
if (!res) {
std::cout << "failed" << std::endl;
return;
}
std::cout << "canceled" << std::endl;
});
}
int main(int argc, char const* argv[]) {
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed" << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ------------------------------------------------------------ | ------ |
| 200 | The grid order was canceled successfully. | None |
| 400 | The request was rejected with an incorrect request parameter. | None |
---
# Grid Order Detail
URL: https://open.longbridge.com/docs/trade/grid/detail.md
Query the full detail of a single grid order, including its rule, paged executed sub-orders (`grid_sub_orders`), and paged lifecycle history (`grid_order_history`).
# Rule, sub-orders and history of a grid order
longbridge grid detail 764609681686573056
## Request
HTTP Method GET
HTTP URL /v1/gridtrading/detail
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| ---------- | ------ | -------- | ------------------------------------------------------------------------------------ |
| order_id | string | YES | Grid order ID, example: `764609681686573056` |
| history_id | string | NO | Cursor for paging the lifecycle history. Pass the last `history_id` of a page to fetch older entries. |
| limit | int32 | NO | Page size for `grid_sub_orders` and `grid_order_history` |
### Request Example
```python
from longbridge.openapi import GridContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
# Grid REST calls go through the standalone GridContext
ctx = GridContext(config)
resp = ctx.detail("764609681686573056")
print(resp)
```
```javascript
const { Config, GridContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = GridContext.new(config)
const resp = await ctx.detail({ orderId: '764609681686573056' })
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.grid.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
GridContext ctx = GridContext.create(config)) {
GridOrderDetail resp = ctx.detail(new GetGridOrderDetailOptions("764609681686573056")).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{
Config,
grid::{GridContext, GetGridOrderDetailOptions},
oauth::OAuthBuilder,
};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = GridContext::new(config);
let resp = ctx.detail(GetGridOrderDetailOptions::new("764609681686573056")).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::grid;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
GridContext ctx = GridContext::create(config);
GetGridOrderDetailOptions opts{ "764609681686573056" };
ctx.detail(opts, [](auto res) {
if (!res) {
std::cout << "failed" << std::endl;
return;
}
std::cout << "order_id: " << res->order_id << std::endl;
});
}
int main(int argc, char const* argv[]) {
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed" << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"order_id": "764609681686573056",
"symbol": "700.HK",
"stock_name": "TENCENT",
"status": "Performing",
"grid_status": "Performing",
"suspend_reason": "",
"sleeping_reason": "",
"submitted_base_price": "300",
"current_base_price": "300",
"upper_limit_price": "360",
"lower_limit_price": "240",
"trigger_price_type": 2,
"trigger_spread_up": "",
"trigger_spread_down": "",
"trigger_percent_up": "2",
"trigger_percent_down": "2",
"pullback_percent": "",
"pullback_spread": "",
"rebound_percent": "",
"rebound_spread": "",
"multiple_trigger": false,
"time_in_force": 1,
"trigger_quantity": "100",
"trigger_sell_quantity": "0",
"trigger_buy_quantity": "0",
"upper_limit_quantity": "200",
"lower_limit_quantity": "100",
"upper_limit_event": 1,
"lower_limit_event": 1,
"trigger_sell_depth": 0,
"trigger_buy_depth": 0,
"created_at": "2024-08-12T10:30:00+08:00",
"updated_at": "2024-08-12T10:30:00+08:00",
"settlement_currency": "HKD",
"expire_time": "",
"gtd": "",
"grid_sub_orders": [],
"sub_has_more": false,
"grid_order_history": [
{
"history_id": "764609681686573100",
"created_at": "2024-08-12T10:30:00+08:00",
"status": "Performing",
"suspend_reason": "",
"reason": "Grid order started"
}
],
"history_has_more": false,
"support_shortsell": false,
"rth": 0,
"grid_order_type_up": "GMO",
"grid_order_type_down": "GMO"
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ---------------------------------------------------- | ------ |
| 200 | The grid order detail was returned successfully. | [grid_order_detail_rsp](#schemagrid_order_detail_rsp) |
| 400 | The request was rejected with an incorrect parameter.| None |
## Schemas
### grid_order_detail_rsp
| Name | Type | Required | Description |
| --------------------- | -------- | -------- | -------------------------------------------------------------------------------------------------------------- |
| order_id | string | true | Grid order ID |
| symbol | string | true | Security symbol, `ticker.region` format |
| stock_name | string | true | Security name |
| status | string | true | Grid order status, example: `Performing` / `Suspended` |
| grid_status | string | true | Detailed grid running status |
| suspend_reason | string | true | Reason the grid is suspended, empty when running |
| sleeping_reason | string | true | Reason the grid is dormant, empty when active |
| submitted_base_price | string | true | Base price the grid was anchored to at submission |
| current_base_price | string | true | Current base price after triggers |
| upper_limit_price | string | true | Upper price bound |
| lower_limit_price | string | true | Lower price bound |
| trigger_price_type | int32 | true | How trigger thresholds are interpreted
**Enum Value:**
`1` - spread (absolute)
`2` - percent |
| trigger_spread_up | string | true | Upward trigger spread (when `trigger_price_type` is `1`) |
| trigger_spread_down | string | true | Downward trigger spread (when `trigger_price_type` is `1`) |
| trigger_percent_up | string | true | Upward trigger percent (when `trigger_price_type` is `2`) |
| trigger_percent_down | string | true | Downward trigger percent (when `trigger_price_type` is `2`) |
| pullback_percent | string | true | Pullback percent |
| pullback_spread | string | true | Pullback spread |
| rebound_percent | string | true | Rebound percent |
| rebound_spread | string | true | Rebound spread |
| multiple_trigger | boolean | true | Whether a single grid level may trigger multiple times |
| time_in_force | int32 | true | Time in force
**Enum Value:**
`0` - Day
`1` - GTC
`6` - GTD |
| trigger_quantity | string | true | Quantity per trigger |
| trigger_sell_quantity | string | true | Cumulative quantity triggered on the sell side |
| trigger_buy_quantity | string | true | Cumulative quantity triggered on the buy side |
| upper_limit_quantity | string | true | Quantity handled when the upper bound is reached |
| lower_limit_quantity | string | true | Quantity handled when the lower bound is reached |
| upper_limit_event | int32 | true | Action at the upper bound
**Enum Value:**
`1` - ignore
`2` - close position at last price |
| lower_limit_event | int32 | true | Action at the lower bound
**Enum Value:**
`1` - ignore
`2` - close position at last price |
| trigger_sell_depth | int32 | true | Sell-side order-book depth (-5 ~ 5). `0` = use `grid_order_type_up` |
| trigger_buy_depth | int32 | true | Buy-side order-book depth (-5 ~ 5). `0` = use `grid_order_type_down` |
| created_at | string | true | Creation time, RFC3339 format |
| updated_at | string | true | Last update time, RFC3339 format |
| settlement_currency | string | true | Settlement currency, example: `HKD` |
| expire_time | string | true | Expiry time, RFC3339 format (when `time_in_force` is GTD) |
| gtd | string | true | Good-Til-Date, `YYYY-MM-DD` format |
| grid_sub_orders | object[] | false | Executed sub-orders for this grid |
| ∟ id | string | true | Sub-order ID |
| ∟ price | string | true | Order price |
| ∟ order_type | string | true | Order type |
| ∟ quantity | string | true | Order quantity |
| ∟ executed_qty | string | true | Executed quantity |
| ∟ action | int32 | true | Buy/sell direction |
| ∟ status | string | true | Sub-order status |
| ∟ submitted_at | string | true | Submission time, RFC3339 format |
| ∟ rth | int32 | true | Regular-trading-hours flag (`0` / `1` / `2`) |
| sub_has_more | boolean | true | Whether more sub-orders can be paged |
| grid_order_history | object[] | false | Lifecycle history entries |
| ∟ history_id | string | true | History entry ID, also used as the paging cursor |
| ∟ created_at | string | true | Event time, RFC3339 format |
| ∟ status | string | true | Grid status after the event |
| ∟ suspend_reason | string | true | Suspend reason, when applicable |
| ∟ reason | string | true | Human-readable description of the event |
| history_has_more | boolean | true | Whether more history entries can be paged via `history_id` |
| support_shortsell | boolean | true | Whether short selling is allowed |
| rth | int32 | true | Regular-trading-hours flag (`0` / `1` / `2`) |
| grid_order_type_up | string | true | Sell-side order type when `trigger_sell_depth` is `0`
**Enum Value:**
`GMO` / `GLO` / `GTG` |
| grid_order_type_down | string | true | Buy-side order type when `trigger_buy_depth` is `0`
**Enum Value:**
`GMO` / `GLO` / `GTG` |
---
# List Grid Orders
URL: https://open.longbridge.com/docs/trade/grid/list.md
Get a paged list of your grid orders, optionally filtered by market, symbol, or status.
# List all grid orders (default)
longbridge grid
# Filter by symbol and status
longbridge grid --symbol 700.HK --status Performing
## Request
HTTP Method GET
HTTP URL /v1/gridtrading/list
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| ---------- | ------ | -------- | ---------------------------------------------------------------------------------------- |
| page | int32 | NO | Page number, starts at `1` |
| limit | int32 | NO | Page size |
| market | string | NO | Market filter
**Enum Value:**
`US` / `HK` / `CN` / `SG` |
| symbol | string | NO | Security symbol, `ticker.region` format, example: `700.HK` |
| status | string | NO | Grid order status filter, comma-joined, example: `Performing,Suspended` |
| sort_by | string | NO | Field to sort by |
| sort_order | string | NO | Sort direction |
### Request Example
```python
from longbridge.openapi import GridContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
# Grid REST calls go through the standalone GridContext
ctx = GridContext(config)
resp = ctx.list(symbol="700.HK", status="Performing", limit=20)
print(resp)
```
```javascript
const { Config, GridContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = GridContext.new(config)
const resp = await ctx.list({ symbol: '700.HK', status: 'Performing', limit: 20 })
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.grid.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
GridContext ctx = GridContext.create(config)) {
GridOrder[] orders = ctx.list(new GetGridOrdersOptions().setSymbol("700.HK").setLimit(20)).get();
for (GridOrder order : orders) {
System.out.println(order);
}
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{
Config,
grid::{GridContext, GetGridOrdersOptions},
oauth::OAuthBuilder,
};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = GridContext::new(config);
let resp = ctx.list(GetGridOrdersOptions::new().symbol("700.HK").limit(20)).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::grid;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
GridContext ctx = GridContext::create(config);
GetGridOrdersOptions opts;
opts.symbol = "700.HK";
opts.status = "Performing";
opts.limit = 20;
ctx.list(std::optional(opts), [](auto res) {
if (!res) {
std::cout << "failed" << std::endl;
return;
}
std::cout << "grid orders: " << res->count << std::endl;
});
}
int main(int argc, char const* argv[]) {
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed" << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"grid_order": [
{
"order_id": "764609681686573056",
"symbol": "700.HK",
"stock_name": "TENCENT",
"market": "HK",
"status": "Performing",
"grid_status": "Performing",
"submitted_base_price": "300.000",
"current_base_price": "300.000",
"pre_trigger_base_price": "300.000",
"post_trigger_base_price": "306.000",
"upper_limit_price": "360.000",
"lower_limit_price": "240.000",
"trigger_price_type": 2,
"trigger_spread_up": "",
"trigger_spread_down": "",
"trigger_percent_up": "2",
"trigger_percent_down": "2",
"pullback_percent": "",
"pullback_spread": "",
"rebound_percent": "",
"rebound_spread": "",
"trigger_sell_order_type": "GMO",
"trigger_buy_order_type": "GMO",
"trigger_sell_depth": 0,
"trigger_buy_depth": 0,
"trigger_quantity": "100",
"trigger_sell_quantity": "100",
"trigger_buy_quantity": "100",
"upper_limit_quantity": "200",
"lower_limit_quantity": "100",
"upper_limit_event": 1,
"lower_limit_event": 1,
"multiple_trigger": false,
"trigger_times": 3,
"total_buy_quantity": "300",
"total_sell_quantity": "200",
"total_profit_balance": "1250.00",
"settlement_currency": "HKD",
"time_in_force": 1,
"gtd": "",
"created_at": "2025-01-15T09:30:00+08:00",
"rth": 0,
"support_shortsell": false,
"grid_order_type_up": "GMO",
"grid_order_type_down": "GMO"
}
],
"has_more": false
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ---------------------------------------------------------------- | ------ |
| 200 | The grid order list was returned successfully. | [list_grid_orders_rsp](#schemalist_grid_orders_rsp) |
| 400 | The request was rejected with an incorrect request parameter. | None |
## Schemas
### list_grid_orders_rsp
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| grid_order | object[] | false | Grid orders |
| ∟ order_id | string | true | Grid order ID |
| ∟ symbol | string | true | Stock symbol, use `ticker.region` format, example: `AAPL.US` |
| ∟ stock_name | string | true | Stock name |
| ∟ market | string | true | Market |
| ∟ status | string | true | Grid order status |
| ∟ grid_status | string | true | Grid running status |
| ∟ submitted_base_price | string | true | Base price submitted when the grid was created |
| ∟ current_base_price | string | true | Current base price |
| ∟ pre_trigger_base_price | string | true | Base price before the last trigger |
| ∟ post_trigger_base_price | string | true | Base price after the last trigger |
| ∟ upper_limit_price | string | true | Upper price bound |
| ∟ lower_limit_price | string | true | Lower price bound |
| ∟ trigger_price_type | int32 | true | Trigger price type
**Enum Value:**
`1` - Spread
`2` - Percent |
| ∟ trigger_spread_up | string | true | Upward trigger spread |
| ∟ trigger_spread_down | string | true | Downward trigger spread |
| ∟ trigger_percent_up | string | true | Upward trigger percent |
| ∟ trigger_percent_down | string | true | Downward trigger percent |
| ∟ pullback_percent | string | true | Pullback percent |
| ∟ pullback_spread | string | true | Pullback spread |
| ∟ rebound_percent | string | true | Rebound percent |
| ∟ rebound_spread | string | true | Rebound spread |
| ∟ trigger_sell_order_type | string | true | Sell-side order type |
| ∟ trigger_buy_order_type | string | true | Buy-side order type |
| ∟ trigger_sell_depth | int32 | true | Sell-side order-book depth |
| ∟ trigger_buy_depth | int32 | true | Buy-side order-book depth |
| ∟ trigger_quantity | string | true | Quantity per trigger |
| ∟ trigger_sell_quantity | string | true | Sell-side trigger quantity |
| ∟ trigger_buy_quantity | string | true | Buy-side trigger quantity |
| ∟ upper_limit_quantity | string | true | Quantity handled at the upper bound |
| ∟ lower_limit_quantity | string | true | Quantity handled at the lower bound |
| ∟ upper_limit_event | int32 | true | Action when the upper bound is reached
**Enum Value:**
`1` - Ignore
`2` - Close position at last price |
| ∟ lower_limit_event | int32 | true | Action when the lower bound is reached
**Enum Value:**
`1` - Ignore
`2` - Close position at last price |
| ∟ multiple_trigger | boolean | true | Whether a single grid level can trigger multiple times |
| ∟ trigger_times | int32 | true | Number of times triggered |
| ∟ total_buy_quantity | string | true | Total bought quantity |
| ∟ total_sell_quantity | string | true | Total sold quantity |
| ∟ total_profit_balance | string | true | Total realized profit |
| ∟ settlement_currency | string | true | Settlement currency |
| ∟ time_in_force | int32 | true | Time in force
**Enum Value:**
`0` - Day
`1` - GTC (Good-Til-Canceled)
`6` - GTD (Good-Til-Date) |
| ∟ gtd | string | true | GTD expiration date, format: `YYYY-MM-DD` |
| ∟ created_at | string | true | Creation time, in RFC3339 format |
| ∟ rth | int32 | true | Regular trading hours flag |
| ∟ support_shortsell | boolean | true | Whether short selling is allowed |
| ∟ grid_order_type_up | string | true | Sell-side order type used when the depth is `0` |
| ∟ grid_order_type_down | string | true | Buy-side order type used when the depth is `0` |
| has_more | boolean | true | Whether there are more pages |
---
# Query Grid Orders by IDs
URL: https://open.longbridge.com/docs/trade/grid/list_by_ids.md
Query specific grid orders by their IDs.
# Query specific grid orders by ID
longbridge grid --ids 764609681686573056 764609681686573057
## Request
HTTP Method POST
HTTP URL /v1/gridtrading/list
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| --------- | -------- | -------- | ------------------------------------ |
| order_ids | string[] | YES | Grid order IDs to query |
### Request Example
```python
from longbridge.openapi import GridContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
# Grid REST calls go through the standalone GridContext
ctx = GridContext(config)
resp = ctx.list_by_ids(["764609681686573056"])
print(resp)
```
```javascript
const { Config, GridContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = GridContext.new(config)
const resp = await ctx.listByIds({ orderIds: ['764609681686573056'] })
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.grid.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
GridContext ctx = GridContext.create(config)) {
GridOrder[] orders = ctx.listByIds(new String[]{"764609681686573056"}).get();
for (GridOrder order : orders) {
System.out.println(order);
}
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{
Config,
grid::{GridContext, GetGridOrdersByIdsOptions},
oauth::OAuthBuilder,
};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = GridContext::new(config);
let resp = ctx.list_by_ids(GetGridOrdersByIdsOptions::new(["764609681686573056"])).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::grid;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
GridContext ctx = GridContext::create(config);
GetGridOrdersByIdsOptions opts;
opts.order_ids = { "764609681686573056" };
ctx.list_by_ids(opts, [](auto res) {
if (!res) {
std::cout << "failed" << std::endl;
return;
}
std::cout << "grid orders: " << res->count << std::endl;
});
}
int main(int argc, char const* argv[]) {
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed" << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"grid_order": [
{
"order_id": "764609681686573056",
"symbol": "700.HK",
"stock_name": "TENCENT",
"market": "HK",
"status": "Performing",
"grid_status": "Performing",
"submitted_base_price": "300.000",
"current_base_price": "300.000",
"pre_trigger_base_price": "300.000",
"post_trigger_base_price": "306.000",
"upper_limit_price": "360.000",
"lower_limit_price": "240.000",
"trigger_price_type": 2,
"trigger_spread_up": "",
"trigger_spread_down": "",
"trigger_percent_up": "2",
"trigger_percent_down": "2",
"pullback_percent": "",
"pullback_spread": "",
"rebound_percent": "",
"rebound_spread": "",
"trigger_sell_order_type": "GMO",
"trigger_buy_order_type": "GMO",
"trigger_sell_depth": 0,
"trigger_buy_depth": 0,
"trigger_quantity": "100",
"trigger_sell_quantity": "100",
"trigger_buy_quantity": "100",
"upper_limit_quantity": "200",
"lower_limit_quantity": "100",
"upper_limit_event": 1,
"lower_limit_event": 1,
"multiple_trigger": false,
"trigger_times": 3,
"total_buy_quantity": "300",
"total_sell_quantity": "200",
"total_profit_balance": "1250.00",
"settlement_currency": "HKD",
"time_in_force": 1,
"gtd": "",
"created_at": "2025-01-15T09:30:00+08:00",
"rth": 0,
"support_shortsell": false,
"grid_order_type_up": "GMO",
"grid_order_type_down": "GMO"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ---------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| 200 | The grid orders were returned successfully. | [list_grid_orders_by_ids_rsp](#schemalist_grid_orders_by_ids_rsp) |
| 400 | The request was rejected with an incorrect request parameter. | None |
## Schemas
### list_grid_orders_by_ids_rsp
| Name | Type | Required | Description |
| -------------------------- | -------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| grid_order | object[] | false | Grid orders |
| ∟ order_id | string | true | Grid order ID |
| ∟ symbol | string | true | Stock symbol, use `ticker.region` format, example: `AAPL.US` |
| ∟ stock_name | string | true | Stock name |
| ∟ market | string | true | Market |
| ∟ status | string | true | Grid order status |
| ∟ grid_status | string | true | Grid running status |
| ∟ submitted_base_price | string | true | Submitted base price the grid is anchored to |
| ∟ current_base_price | string | true | Current base price |
| ∟ pre_trigger_base_price | string | true | Base price before the last trigger |
| ∟ post_trigger_base_price | string | true | Base price after the last trigger |
| ∟ upper_limit_price | string | true | Upper price bound |
| ∟ lower_limit_price | string | true | Lower price bound |
| ∟ trigger_price_type | int32 | true | Trigger price type
**Enum Value:**
`1` - Spread
`2` - Percent |
| ∟ trigger_spread_up | string | true | Upward trigger spread, used when `trigger_price_type` is `1` |
| ∟ trigger_spread_down | string | true | Downward trigger spread, used when `trigger_price_type` is `1` |
| ∟ trigger_percent_up | string | true | Upward trigger percent, used when `trigger_price_type` is `2` |
| ∟ trigger_percent_down | string | true | Downward trigger percent, used when `trigger_price_type` is `2` |
| ∟ pullback_percent | string | true | Pullback percent |
| ∟ pullback_spread | string | true | Pullback spread |
| ∟ rebound_percent | string | true | Rebound percent |
| ∟ rebound_spread | string | true | Rebound spread |
| ∟ trigger_sell_order_type | string | true | Sell-side grid order type
**Enum Value:**
`GMO` - Grid market order
`GLO` - Grid limit order
`GTG` - Grid touch-to-go |
| ∟ trigger_buy_order_type | string | true | Buy-side grid order type
**Enum Value:**
`GMO` - Grid market order
`GLO` - Grid limit order
`GTG` - Grid touch-to-go |
| ∟ trigger_sell_depth | int32 | true | Sell-side order-book depth, range `-5..5`; `0` means use `trigger_sell_order_type` |
| ∟ trigger_buy_depth | int32 | true | Buy-side order-book depth, range `-5..5`; `0` means use `trigger_buy_order_type` |
| ∟ trigger_quantity | string | true | Quantity per trigger |
| ∟ trigger_sell_quantity | string | true | Sell-side trigger quantity |
| ∟ trigger_buy_quantity | string | true | Buy-side trigger quantity |
| ∟ upper_limit_quantity | string | true | Quantity handled at the upper bound |
| ∟ lower_limit_quantity | string | true | Quantity handled at the lower bound |
| ∟ upper_limit_event | int32 | true | Event when the upper bound is reached
**Enum Value:**
`1` - Ignore (keep grid running)
`2` - Close position at last price |
| ∟ lower_limit_event | int32 | true | Event when the lower bound is reached
**Enum Value:**
`1` - Ignore (keep grid running)
`2` - Close position at last price |
| ∟ multiple_trigger | boolean | true | Whether a single grid level can trigger multiple times |
| ∟ trigger_times | int32 | true | Number of times the grid has triggered |
| ∟ total_buy_quantity | string | true | Total bought quantity |
| ∟ total_sell_quantity | string | true | Total sold quantity |
| ∟ total_profit_balance | string | true | Total profit balance |
| ∟ settlement_currency | string | true | Settlement currency |
| ∟ time_in_force | int32 | true | Time in force type
**Enum Value:**
`0` - Day
`1` - Good-Til-Canceled
`6` - Good-Til-Date |
| ∟ gtd | string | true | Good-Til-Date expiry date, format: `YYYY-MM-DD` |
| ∟ created_at | string | true | Creation time, formatted as RFC3339 |
| ∟ rth | int32 | true | Regular trading hours flag
**Enum Value:**
`0`
`1`
`2` |
| ∟ support_shortsell | boolean | true | Whether short selling is allowed |
| ∟ grid_order_type_up | string | true | Sell-side order type when depth is `0`
**Enum Value:**
`GMO` - Grid market order
`GLO` - Grid limit order
`GTG` - Grid touch-to-go |
| ∟ grid_order_type_down | string | true | Buy-side order type when depth is `0`
**Enum Value:**
`GMO` - Grid market order
`GLO` - Grid limit order
`GTG` - Grid touch-to-go |
---
# Grid Trading Overview
URL: https://open.longbridge.com/docs/trade/grid/overview.md
Grid trading is an automated strategy that buys as the price falls and sells as it rises within a price band anchored to a base price. It profits from oscillation: each downward step places a buy, each upward step places a sell, and the accumulated spread becomes realized profit. The Grid Trading API lets you submit, monitor, adjust, and cancel grid strategies programmatically.
## How it works
A grid is defined by a base price and a price band, plus rules for when and how much to trade at each step.
- **Base price** — `submitted_base_price` is the anchor the grid is centered on. Trigger levels are measured relative to this price.
- **Upper / lower bounds** — `upper_limit_price` and `lower_limit_price` mark the top and bottom of the band. The grid runs only inside `[lower_limit_price, upper_limit_price]`.
- **Trigger by percent vs. spread** — `trigger_price_type` decides how the step size is interpreted: `1` = spread (an absolute price difference, `trigger_spread_up` / `trigger_spread_down`), `2` = percent (a percentage of the base price, `trigger_percent_up` / `trigger_percent_down`).
- **Per-trigger quantity** — `trigger_quantity` is the amount bought or sold each time a level triggers. `upper_limit_quantity` and `lower_limit_quantity` are the amounts handled when the band's upper or lower bound is reached.
- **Upper / lower limit events** — `upper_limit_event` and `lower_limit_event` decide what happens at the bounds: `1` = ignore (keep the grid running), `2` = close the position at the last price.
- **Grid order types** — when the corresponding order-book depth (`trigger_sell_depth` / `trigger_buy_depth`) is `0`, `grid_order_type_up` / `grid_order_type_down` decide the order type: `GMO` (grid market order), `GLO` (grid limit order), `GTG` (grid touch-to-go).
- **Time in force** — `time_in_force` controls how long the grid stays active: `0` = Day, `1` = GTC (Good-Til-Canceled), `6` = GTD (Good-Til-Date, paired with `expire_time`).
## Prerequisites
::: tip Prerequisites
Grid trading requires the **Trade** permission on your access token. You must also record the strategy risk-disclosure consent **once** before submitting any grid order — see [Submit Strategy Questionnaire](./questionnaire). You can check whether the consent has been recorded via the `strategy_granted` field on [Grid Symbol Info](./symbol_info).
:::
## Typical workflow
1. Record the risk-disclosure consent once — [Submit Strategy Questionnaire](./questionnaire).
2. Fetch the security's grid info (lot size, last price, authorization) — [Grid Symbol Info](./symbol_info).
3. Submit the grid strategy — [Submit Grid Order](./submit).
4. List and inspect running grids — [List Grid Orders](./list) and [Grid Order Detail](./detail).
5. Review what the grid has triggered — [Trigger History](./trigger_history).
6. Adjust or stop the grid — [Suspend](./suspend), [Restart](./restart), [Replace](./replace), or [Cancel](./cancel).
## Quickstart (CLI)
# Record the one-time strategy risk-disclosure consent
longbridge grid questionnaire
# Check the security's grid info (lot size, last price, authorization)
longbridge grid info 700.HK
# Submit a percent-triggered grid on 700.HK
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
# List your grid orders
longbridge grid
---
# Submit Strategy Questionnaire
URL: https://open.longbridge.com/docs/trade/grid/questionnaire.md
Record the strategy risk-disclosure consent. This is a one-time acknowledgement that must be submitted **once** before you can place any grid order. Until it is recorded, submitting a grid order will be rejected.
# Submit the strategy risk-disclosure questionnaire (one-time consent)
longbridge grid questionnaire
## Request
HTTP Method POST
HTTP URL /v1/record/questionnaire
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| ----- | ------ | -------- | ---------------------------------------------------- |
| type | string | YES | Questionnaire type, fixed value: `strategy` |
| items | object | YES | Consent items, e.g. `{ "agree": "true" }` |
### Request Example
```python
from longbridge.openapi import GridContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
# Grid REST calls go through the standalone GridContext
ctx = GridContext(config)
resp = ctx.submit_strategy_questionnaire()
print(resp)
```
```javascript
const { Config, GridContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = GridContext.new(config)
const resp = await ctx.submitStrategyQuestionnaire()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.grid.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
GridContext ctx = GridContext.create(config)) {
ctx.submitStrategyQuestionnaire().get();
System.out.println("consent recorded");
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{
Config,
grid::{GridContext, SubmitStrategyQuestionnaireOptions},
oauth::OAuthBuilder,
};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = GridContext::new(config);
ctx.submit_strategy_questionnaire(SubmitStrategyQuestionnaireOptions::new()).await?;
println!("consent recorded");
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::grid;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
GridContext ctx = GridContext::create(config);
ctx.submit_strategy_questionnaire([](auto res) {
if (!res) {
std::cout << "failed" << std::endl;
return;
}
std::cout << "consent recorded" << std::endl;
});
}
int main(int argc, char const* argv[]) {
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed" << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ---------------------------------------------------------------- | ------ |
| 200 | The strategy consent was recorded successfully. | None |
| 400 | The request was rejected with an incorrect request parameter. | None |
---
# Modify Grid Order
URL: https://open.longbridge.com/docs/trade/grid/replace.md
Modify an existing grid order's rule. The whole `grid_trading_rule` is replaced with the one you submit, so pass the complete rule — not just the fields you changed.
# Modify a grid order's base/bound prices and quantities
longbridge grid replace 764609681686573056 --base-price 305 --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
# Validate the new rule without applying it
longbridge grid replace 764609681686573056 --base-price 305 --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 --dry-run
## Request
HTTP Method POST
HTTP URL /v1/gridtrading/replace
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| ----------------- | ------ | -------- | ------------------------------------------------- |
| order_id | string | YES | Grid order ID, example: `764609681686573056` |
| grid_trading_rule | object | YES | The full grid rule to apply. Fields below. |
#### grid_trading_rule
| Name | Type | Required | Description |
| --------------------- | ------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| submitted_base_price | string | YES | Base price the grid is anchored to |
| upper_limit_price | string | YES | Upper price bound |
| lower_limit_price | string | YES | Lower price bound |
| trigger_price_type | int32 | YES | How trigger thresholds are interpreted
**Enum Value:**
`1` - spread (absolute)
`2` - percent |
| trigger_spread_up | string | NO | Upward trigger spread, required when `trigger_price_type` is `1` |
| trigger_spread_down | string | NO | Downward trigger spread, required when `trigger_price_type` is `1` |
| trigger_percent_up | string | NO | Upward trigger percent, required when `trigger_price_type` is `2` |
| trigger_percent_down | string | NO | Downward trigger percent, required when `trigger_price_type` is `2` |
| trigger_quantity | string | YES | Quantity per trigger |
| upper_limit_quantity | string | YES | Quantity handled when the upper bound is reached |
| lower_limit_quantity | string | YES | Quantity handled when the lower bound is reached |
| time_in_force | int32 | YES | Time in force
**Enum Value:**
`0` - Day
`1` - GTC (Good-Til-Canceled)
`6` - GTD (Good-Til-Date) |
| expire_time | int64 | NO | Expiry time (Unix timestamp, in seconds), required when `time_in_force` is `6` (GTD) |
| upper_limit_event | int32 | NO | Action when the upper bound is reached
**Enum Value:**
`1` - ignore (keep running)
`2` - close position at last price |
| lower_limit_event | int32 | NO | Action when the lower bound is reached
**Enum Value:**
`1` - ignore (keep running)
`2` - close position at last price |
| trigger_sell_depth | int32 | NO | Sell-side order-book depth (-5 ~ 5). `0` = use `grid_order_type_up` instead of a depth level |
| trigger_buy_depth | int32 | NO | Buy-side order-book depth (-5 ~ 5). `0` = use `grid_order_type_down` instead of a depth level |
| grid_order_type_up | string | NO | Sell-side order type when `trigger_sell_depth` is `0`
**Enum Value:**
`GMO` / `GLO` / `GTG` |
| grid_order_type_down | string | NO | Buy-side order type when `trigger_buy_depth` is `0`
**Enum Value:**
`GMO` / `GLO` / `GTG` |
| multiple_trigger | boolean | NO | Whether a single grid level may trigger multiple times |
| support_shortsell | boolean | NO | Whether short selling is allowed |
| rth | int32 | NO | Regular-trading-hours flag (`0` / `1` / `2`) |
### Request Example
```python
from decimal import Decimal
from longbridge.openapi import (
GridContext, Config, OAuthBuilder,
GridTradeRule, TriggerPriceType, GridTimeInForce, GridLimitEvent,
)
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
# Grid REST calls go through the standalone GridContext
ctx = GridContext(config)
rule = GridTradeRule(
Decimal(305), Decimal(360), Decimal(240), # base, upper, lower price
TriggerPriceType.Percent, Decimal(2), Decimal(2), # trigger type, up, down
Decimal(100), Decimal(200), Decimal(100), # quantity, upper qty, lower qty
GridTimeInForce.GoodTilCanceled,
upper_limit_event=GridLimitEvent.Ignore,
lower_limit_event=GridLimitEvent.Ignore,
grid_order_type_up="GMO",
grid_order_type_down="GMO",
)
resp = ctx.replace("764609681686573056", rule)
print(resp)
```
```javascript
const { Config, GridContext, OAuth, Decimal, TriggerPriceType, GridTimeInForce, GridLimitEvent } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = GridContext.new(config)
const resp = await ctx.replace({
orderId: '764609681686573056',
gridTradingRule: {
submittedBasePrice: new Decimal(305),
upperLimitPrice: new Decimal(360),
lowerLimitPrice: new Decimal(240),
triggerPriceType: TriggerPriceType.Percent,
triggerPercentUp: new Decimal(2),
triggerPercentDown: new Decimal(2),
triggerQuantity: new Decimal(100),
upperLimitQuantity: new Decimal(200),
lowerLimitQuantity: new Decimal(100),
timeInForce: GridTimeInForce.GoodTilCanceled,
upperLimitEvent: GridLimitEvent.Ignore,
lowerLimitEvent: GridLimitEvent.Ignore,
gridOrderTypeUp: 'GMO',
gridOrderTypeDown: 'GMO',
},
})
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.grid.*;
import java.math.BigDecimal;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
GridContext ctx = GridContext.create(config)) {
GridTradeRule rule = new GridTradeRule(
new BigDecimal("305"), new BigDecimal("360"), new BigDecimal("240"),
GridTrigger.percent(new BigDecimal("2"), new BigDecimal("2")),
new BigDecimal("100"), new BigDecimal("200"), new BigDecimal("100"),
GridTimeInForce.GoodTilCanceled)
.orderTypes("GMO", "GMO")
.limitEvents(GridLimitEvent.Ignore, GridLimitEvent.Ignore);
ctx.replace(new ReplaceGridOrderOptions("764609681686573056", rule)).get();
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{
Config,
grid::{GridContext, GridTradeRule, ReplaceGridOrderOptions},
oauth::OAuthBuilder,
};
use rust_decimal::Decimal;
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = GridContext::new(config);
let rule = GridTradeRule {
submitted_base_price: Some(Decimal::new(305, 0)),
upper_limit_price: Some(Decimal::new(360, 0)),
lower_limit_price: Some(Decimal::new(240, 0)),
trigger_price_type: Some(2.into()), // 1 = spread, 2 = percent
trigger_percent_up: Some(Decimal::new(2, 0)),
trigger_percent_down: Some(Decimal::new(2, 0)),
trigger_quantity: Some(Decimal::new(100, 0)),
upper_limit_quantity: Some(Decimal::new(200, 0)),
lower_limit_quantity: Some(Decimal::new(100, 0)),
time_in_force: Some(1.into()), // GTC
grid_order_type_up: Some("GMO".to_string()),
grid_order_type_down: Some("GMO".to_string()),
upper_limit_event: Some(1.into()),
lower_limit_event: Some(1.into()),
..Default::default()
};
ctx.replace(ReplaceGridOrderOptions::new("764609681686573056", rule)).await?;
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::grid;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
GridContext ctx = GridContext::create(config);
GridTradeRule rule;
rule.submitted_base_price = Decimal("305");
rule.upper_limit_price = Decimal("360");
rule.lower_limit_price = Decimal("240");
rule.trigger_price_type = TriggerPriceType::Percent;
rule.trigger_percent_up = Decimal("2");
rule.trigger_percent_down = Decimal("2");
rule.trigger_quantity = Decimal("100");
rule.upper_limit_quantity = Decimal("200");
rule.lower_limit_quantity = Decimal("100");
rule.time_in_force = GridTimeInForce::GoodTilCanceled;
rule.grid_order_type_up = "GMO";
rule.grid_order_type_down = "GMO";
ReplaceGridOrderOptions opts{ "764609681686573056", rule };
ctx.replace(opts, [](auto res) {
if (!res) {
std::cout << "failed" << std::endl;
return;
}
std::cout << "replaced" << std::endl;
});
}
int main(int argc, char const* argv[]) {
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed" << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ------------------------------------------------------------ | ------ |
| 200 | The grid order was modified successfully. | None |
| 400 | The modification was rejected with an incorrect request parameter. | None |
---
# Restart Grid Order
URL: https://open.longbridge.com/docs/trade/grid/restart.md
Restart a suspended grid order. The grid resumes from its saved configuration and begins triggering orders again. Only a grid previously paused with [Suspend Grid Order](./suspend) can be restarted.
# Restart a suspended grid order by ID
longbridge grid restart 764609681686573056
## Request
HTTP Method POST
HTTP URL /v1/gridtrading/restart
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| -------- | ------ | -------- | -------------------------------------------- |
| order_id | string | YES | Grid order ID, example: `764609681686573056` |
### Request Example
```python
from longbridge.openapi import GridContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
# Grid REST calls go through the standalone GridContext
ctx = GridContext(config)
resp = ctx.restart("764609681686573056")
print(resp)
```
```javascript
const { Config, GridContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = GridContext.new(config)
const resp = await ctx.restart('764609681686573056')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.grid.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
GridContext ctx = GridContext.create(config)) {
ctx.restart("764609681686573056").get();
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{Config, grid::GridContext, oauth::OAuthBuilder};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = GridContext::new(config);
ctx.restart("764609681686573056").await?;
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::grid;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
GridContext ctx = GridContext::create(config);
ctx.restart("764609681686573056", [](auto res) {
if (!res) {
std::cout << "failed" << std::endl;
return;
}
std::cout << "restarted" << std::endl;
});
}
int main(int argc, char const* argv[]) {
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed" << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ------------------------------------------------------------ | ------ |
| 200 | The grid order was restarted successfully. | None |
| 400 | The request was rejected with an incorrect request parameter. | None |
---
# Submit Grid Order
URL: https://open.longbridge.com/docs/trade/grid/submit.md
Submit a grid strategy order. The grid places buy orders as the price falls and sell orders as it rises, within the `[lower_limit_price, upper_limit_price]` band anchored to `submitted_base_price`.
Before using grid trading you must record the strategy risk-disclosure consent once — see [Submit Strategy Questionnaire](./questionnaire).
# Submit a percent-triggered grid on 700.HK
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
# Validate the rule without submitting
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 --dry-run
## Request
HTTP Method POST
HTTP URL /v1/gridtrading/submit
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| ------------------- | ------ | -------- | ----------------------------------------------------------------- |
| symbol | string | YES | Security symbol, `ticker.region` format, example: `700.HK` |
| settlement_currency | string | YES | Settlement currency, example: `HKD` |
| grid_trading_rule | object | YES | The grid rule. Fields below. |
#### grid_trading_rule
| Name | Type | Required | Description |
| --------------------- | ------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| submitted_base_price | string | YES | Base price the grid is anchored to |
| upper_limit_price | string | YES | Upper price bound |
| lower_limit_price | string | YES | Lower price bound |
| trigger_price_type | int32 | YES | How trigger thresholds are interpreted
**Enum Value:**
`1` - spread (absolute)
`2` - percent |
| trigger_spread_up | string | NO | Upward trigger spread, required when `trigger_price_type` is `1` |
| trigger_spread_down | string | NO | Downward trigger spread, required when `trigger_price_type` is `1` |
| trigger_percent_up | string | NO | Upward trigger percent, required when `trigger_price_type` is `2` |
| trigger_percent_down | string | NO | Downward trigger percent, required when `trigger_price_type` is `2` |
| trigger_quantity | string | YES | Quantity per trigger |
| upper_limit_quantity | string | YES | Quantity handled when the upper bound is reached |
| lower_limit_quantity | string | YES | Quantity handled when the lower bound is reached |
| time_in_force | int32 | YES | Time in force
**Enum Value:**
`0` - Day
`1` - GTC (Good-Til-Canceled)
`6` - GTD (Good-Til-Date) |
| expire_time | int64 | NO | Expiry time (Unix timestamp, in seconds), required when `time_in_force` is `6` (GTD) |
| upper_limit_event | int32 | NO | Action when the upper bound is reached
**Enum Value:**
`1` - ignore (keep running)
`2` - close position at last price |
| lower_limit_event | int32 | NO | Action when the lower bound is reached
**Enum Value:**
`1` - ignore (keep running)
`2` - close position at last price |
| trigger_sell_depth | int32 | NO | Sell-side order-book depth (-5 ~ 5). `0` = use `grid_order_type_up` instead of a depth level |
| trigger_buy_depth | int32 | NO | Buy-side order-book depth (-5 ~ 5). `0` = use `grid_order_type_down` instead of a depth level |
| grid_order_type_up | string | NO | Sell-side order type when `trigger_sell_depth` is `0`
**Enum Value:**
`GMO` / `GLO` / `GTG` |
| grid_order_type_down | string | NO | Buy-side order type when `trigger_buy_depth` is `0`
**Enum Value:**
`GMO` / `GLO` / `GTG` |
| multiple_trigger | boolean | NO | Whether a single grid level may trigger multiple times |
| support_shortsell | boolean | NO | Whether short selling is allowed |
| rth | int32 | NO | Regular-trading-hours flag (`0` / `1` / `2`) |
### Request Example
```python
from decimal import Decimal
from longbridge.openapi import (
GridContext, Config, OAuthBuilder,
GridTradeRule, TriggerPriceType, GridTimeInForce, GridLimitEvent,
)
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
# Grid REST calls go through the standalone GridContext
ctx = GridContext(config)
rule = GridTradeRule(
Decimal(300), Decimal(360), Decimal(240), # base, upper, lower price
TriggerPriceType.Percent, Decimal(2), Decimal(2), # trigger type, up, down
Decimal(100), Decimal(200), Decimal(100), # quantity, upper qty, lower qty
GridTimeInForce.GoodTilCanceled,
upper_limit_event=GridLimitEvent.Ignore,
lower_limit_event=GridLimitEvent.Ignore,
grid_order_type_up="GMO",
grid_order_type_down="GMO",
)
resp = ctx.submit("700.HK", "HKD", rule)
print(resp)
```
```javascript
const { Config, GridContext, OAuth, Decimal, TriggerPriceType, GridTimeInForce, GridLimitEvent } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = GridContext.new(config)
const resp = await ctx.submit({
symbol: '700.HK',
settlementCurrency: 'HKD',
gridTradingRule: {
submittedBasePrice: new Decimal(300),
upperLimitPrice: new Decimal(360),
lowerLimitPrice: new Decimal(240),
triggerPriceType: TriggerPriceType.Percent,
triggerPercentUp: new Decimal(2),
triggerPercentDown: new Decimal(2),
triggerQuantity: new Decimal(100),
upperLimitQuantity: new Decimal(200),
lowerLimitQuantity: new Decimal(100),
timeInForce: GridTimeInForce.GoodTilCanceled,
upperLimitEvent: GridLimitEvent.Ignore,
lowerLimitEvent: GridLimitEvent.Ignore,
gridOrderTypeUp: 'GMO',
gridOrderTypeDown: 'GMO',
},
})
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.grid.*;
import java.math.BigDecimal;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
GridContext ctx = GridContext.create(config)) {
GridTradeRule rule = new GridTradeRule(
new BigDecimal("300"), new BigDecimal("360"), new BigDecimal("240"),
GridTrigger.percent(new BigDecimal("2"), new BigDecimal("2")),
new BigDecimal("100"), new BigDecimal("200"), new BigDecimal("100"),
GridTimeInForce.GoodTilCanceled)
.orderTypes("GMO", "GMO")
.limitEvents(GridLimitEvent.Ignore, GridLimitEvent.Ignore);
SubmitGridOrderResponse resp = ctx.submit(new SubmitGridOrderOptions("700.HK", "HKD", rule)).get();
System.out.println(resp.getOrderId());
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{
Config,
grid::{GridContext, GridTradeRule, SubmitGridOrderOptions},
oauth::OAuthBuilder,
};
use rust_decimal::Decimal;
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = GridContext::new(config);
let rule = GridTradeRule {
submitted_base_price: Some(Decimal::new(300, 0)),
upper_limit_price: Some(Decimal::new(360, 0)),
lower_limit_price: Some(Decimal::new(240, 0)),
trigger_price_type: Some(2.into()), // 1 = spread, 2 = percent
trigger_percent_up: Some(Decimal::new(2, 0)),
trigger_percent_down: Some(Decimal::new(2, 0)),
trigger_quantity: Some(Decimal::new(100, 0)),
upper_limit_quantity: Some(Decimal::new(200, 0)),
lower_limit_quantity: Some(Decimal::new(100, 0)),
time_in_force: Some(1.into()), // GTC
grid_order_type_up: Some("GMO".to_string()),
grid_order_type_down: Some("GMO".to_string()),
upper_limit_event: Some(1.into()),
lower_limit_event: Some(1.into()),
..Default::default()
};
let resp = ctx.submit(SubmitGridOrderOptions::new("700.HK", "HKD", rule)).await?;
println!("submitted grid order: {}", resp.order_id);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::grid;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
GridContext ctx = GridContext::create(config);
GridTradeRule rule;
rule.submitted_base_price = Decimal("300");
rule.upper_limit_price = Decimal("360");
rule.lower_limit_price = Decimal("240");
rule.trigger_price_type = TriggerPriceType::Percent;
rule.trigger_percent_up = Decimal("2");
rule.trigger_percent_down = Decimal("2");
rule.trigger_quantity = Decimal("100");
rule.upper_limit_quantity = Decimal("200");
rule.lower_limit_quantity = Decimal("100");
rule.time_in_force = GridTimeInForce::GoodTilCanceled;
rule.grid_order_type_up = "GMO";
rule.grid_order_type_down = "GMO";
SubmitGridOrderOptions opts{ "700.HK", "HKD", rule };
ctx.submit(opts, [](auto res) {
if (!res) {
std::cout << "failed" << std::endl;
return;
}
std::cout << "order_id: " << res->order_id << std::endl;
});
}
int main(int argc, char const* argv[]) {
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed" << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"order_id": "764609681686573056"
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ------------------------------------------------------------ | ------ |
| 200 | The grid order was submitted successfully. | None |
| 400 | The submission was rejected with an incorrect request parameter. | None |
---
# Suspend Grid Order
URL: https://open.longbridge.com/docs/trade/grid/suspend.md
Suspend a running grid order. The grid stops triggering new orders but is kept intact, so it can be resumed later with [Restart Grid Order](./restart). Use suspend when you want to pause the strategy without losing its configuration.
# Suspend a running grid order by ID
longbridge grid suspend 764609681686573056
## Request
HTTP Method POST
HTTP URL /v1/gridtrading/suspend
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| -------- | ------ | -------- | -------------------------------------------- |
| order_id | string | YES | Grid order ID, example: `764609681686573056` |
### Request Example
```python
from longbridge.openapi import GridContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
# Grid REST calls go through the standalone GridContext
ctx = GridContext(config)
resp = ctx.suspend("764609681686573056")
print(resp)
```
```javascript
const { Config, GridContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = GridContext.new(config)
const resp = await ctx.suspend('764609681686573056')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.grid.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
GridContext ctx = GridContext.create(config)) {
ctx.suspend("764609681686573056").get();
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{Config, grid::GridContext, oauth::OAuthBuilder};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = GridContext::new(config);
ctx.suspend("764609681686573056").await?;
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::grid;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
GridContext ctx = GridContext::create(config);
ctx.suspend("764609681686573056", [](auto res) {
if (!res) {
std::cout << "failed" << std::endl;
return;
}
std::cout << "suspended" << std::endl;
});
}
int main(int argc, char const* argv[]) {
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed" << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ------------------------------------------------------------ | ------ |
| 200 | The grid order was suspended successfully. | None |
| 400 | The request was rejected with an incorrect request parameter. | None |
---
# Grid Symbol Info
URL: https://open.longbridge.com/docs/trade/grid/symbol_info.md
Fetch the grid-trading information for a security: lot size, last done price, price steps, and authorization status. Use it to build a valid grid rule before calling [Submit Grid Order](./submit). The `channel_info.strategy_granted` field tells you whether the strategy risk-disclosure consent has already been recorded — if it is `false`, submit the [Strategy Questionnaire](./questionnaire) first.
# Show the grid-trading info for 700.HK
longbridge grid info 700.HK
## Request
HTTP Method GET
HTTP URL /v1/orders/info
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| ---------- | ------ | -------- | ---------------------------------------------------------- |
| symbol | string | YES | Security symbol, `ticker.region` format, example: `700.HK` |
### Request Example
```python
from longbridge.openapi import GridContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
# Grid REST calls go through the standalone GridContext
ctx = GridContext(config)
resp = ctx.symbol_info("700.HK")
print(resp)
```
```javascript
const { Config, GridContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = GridContext.new(config)
const resp = await ctx.symbolInfo('700.HK')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.grid.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
GridContext ctx = GridContext.create(config)) {
GridSymbolInfo info = ctx.symbolInfo("700.HK").get();
System.out.println(info);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{
Config,
grid::GridContext,
oauth::OAuthBuilder,
};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = GridContext::new(config);
let info = ctx.symbol_info("700.HK").await?;
println!("{info:?}");
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::grid;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
GridContext ctx = GridContext::create(config);
ctx.symbol_info("700.HK", [](auto res) {
if (!res) {
std::cout << "failed" << std::endl;
return;
}
std::cout << "last_done: " << res->last_done << std::endl;
});
}
int main(int argc, char const* argv[]) {
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed" << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"name": "TENCENT",
"last_done": "300.000",
"lot_size": "100",
"buy_lot_size": "100",
"sell_lot_size": "100",
"bid_sizes": [
{
"str_proceed": "0.010",
"end_proceed": "500.000",
"bid_size": "0.200"
}
],
"channel_info": {
"strategy_granted": true,
"support_rth": false,
"currency": "HKD",
"settlement_currency": ["HKD"]
}
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ---------------------------------------------------------------- | ------ |
| 200 | The security grid info was returned successfully. | [grid_symbol_info_rsp](#schemagrid_symbol_info_rsp) |
| 400 | The request was rejected with an incorrect request parameter. | None |
## Schemas
### grid_symbol_info_rsp
| Name | Type | Required | Description |
| ----------------------- | -------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| name | string | true | Security name |
| last_done | string | true | Latest traded price |
| lot_size | string | true | Board lot size |
| buy_lot_size | string | true | Minimum lot size for a buy order |
| sell_lot_size | string | true | Minimum lot size for a sell order |
| bid_sizes | object[] | true | Price-step tiers |
| ∟ str_proceed | string | true | Start price of the tier |
| ∟ end_proceed | string | true | End price of the tier |
| ∟ bid_size | string | true | Minimum price step within the tier |
| channel_info | object | true | Trading-channel info and authorization. `strategy_granted` indicates whether the one-time strategy risk-disclosure consent has been recorded |
| ∟ strategy_granted | boolean | true | Whether the one-time strategy risk-disclosure consent has been recorded |
| ∟ support_rth | boolean | true | Whether the security supports regular-trading-hours grids |
| ∟ currency | string | true | Trading currency |
| ∟ settlement_currency | string[] | true | Supported settlement currencies |
---
# Grid Trigger History
URL: https://open.longbridge.com/docs/trade/grid/trigger_history.md
Query the paged trigger history of a single grid order — the individual orders the grid has placed each time a trigger fired.
# Trigger history of a grid order
longbridge grid triggers 764609681686573056
## Request
HTTP Method GET
HTTP URL /v1/gridtrading/trigger_history_list
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| ------------- | ------ | -------- | ------------------------------------------------------ |
| grid_order_id | string | YES | Grid order ID, example: `764609681686573056` |
| page | int32 | NO | Page number, starting from `1` |
| limit | int32 | NO | Page size |
:::warning
This endpoint uses `grid_order_id`, **not** `order_id` like the other grid endpoints. Using `order_id` here will not resolve the grid order.
:::
### Request Example
```python
from longbridge.openapi import GridContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
# Grid REST calls go through the standalone GridContext
ctx = GridContext(config)
resp = ctx.trigger_history("764609681686573056")
print(resp)
```
```javascript
const { Config, GridContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = GridContext.new(config)
const resp = await ctx.triggerHistory({ gridOrderId: '764609681686573056' })
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.grid.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
GridContext ctx = GridContext.create(config)) {
GridTriggerHistory resp = ctx.triggerHistory(new GetGridTriggerHistoryOptions("764609681686573056")).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{
Config,
grid::{GridContext, GetGridTriggerHistoryOptions},
oauth::OAuthBuilder,
};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = GridContext::new(config);
let resp = ctx.trigger_history(GetGridTriggerHistoryOptions::new("764609681686573056")).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::grid;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
GridContext ctx = GridContext::create(config);
GetGridTriggerHistoryOptions opts{ "764609681686573056" };
ctx.trigger_history(opts, [](auto res) {
if (!res) {
std::cout << "failed" << std::endl;
return;
}
std::cout << "trigger orders: " << res->trigger_orders.size() << std::endl;
});
}
int main(int argc, char const* argv[]) {
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed" << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"trigger_orders": [
{
"id": "764610000000000001",
"status": "Filled",
"name": "TENCENT",
"symbol": "700.HK",
"price": "294",
"quantity": "100",
"executed_price": "294",
"executed_qty": "100",
"submitted_at": "2024-08-12T10:35:00+08:00",
"action": 1,
"order_type": "GMO",
"trigger_price": "294",
"msg": "",
"currency": "HKD",
"last_done": "294",
"updated_at": "2024-08-12T10:35:05+08:00",
"time_in_force": 1,
"gtd": "",
"trigger_at": "2024-08-12T10:35:00+08:00",
"trigger_status": 1
}
],
"has_more": false
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ------------------------------------------------------ | ------ |
| 200 | The trigger history was returned successfully. | [grid_trigger_history_rsp](#schemagrid_trigger_history_rsp) |
| 400 | The request was rejected with an incorrect parameter. | None |
## Schemas
### grid_trigger_history_rsp
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| trigger_orders | object[] | false | Triggered orders |
| ∟ id | string | true | Trigger order ID |
| ∟ status | string | true | Order status |
| ∟ name | string | true | Security name |
| ∟ symbol | string | true | Security symbol, `ticker.region` format |
| ∟ price | string | true | Order price |
| ∟ quantity | string | true | Order quantity |
| ∟ executed_price | string | true | Executed price |
| ∟ executed_qty | string | true | Executed quantity |
| ∟ submitted_at | string | true | Submission time, RFC3339 format |
| ∟ action | int32 | true | Buy/sell direction |
| ∟ order_type | string | true | Order type |
| ∟ trigger_price | string | true | Price that triggered this order |
| ∟ msg | string | true | Additional message |
| ∟ currency | string | true | Order currency |
| ∟ last_done | string | true | Last traded price at trigger time |
| ∟ updated_at | string | true | Last update time, RFC3339 format |
| ∟ time_in_force | int32 | true | Time in force
**Enum Value:**
`0` - Day
`1` - GTC
`6` - GTD |
| ∟ gtd | string | true | Good-Til-Date, `YYYY-MM-DD` format |
| ∟ trigger_at | string | true | Trigger time, RFC3339 format |
| ∟ trigger_status | int32 | true | Trigger status |
| has_more | boolean | false | Whether more pages are available |
---
# Close a Position
URL: https://open.longbridge.com/docs/trade/order/close_position.md
Closes an existing position by submitting a regular order in the opposite direction. There is no dedicated close-position API, and the [Submit Order](./submit) request has no open/close flag: a long position is closed with a `Sell` order, a short position is covered with a `Buy` order. The sign of the position quantity is the only thing that decides the direction.
## Prerequisites
- A live or paper account with trading permission.
- An OAuth client ID. See [Get Started](/docs/getting-started).
- The SDK for your language installed. The example below uses both `TradeContext` (positions, orders) and `QuoteContext` (trading session, last price).
## Steps
### 1. Read the position
Call [Stock Positions](../asset/stock) with the symbol you want to close and read `available_quantity`, not `quantity`. `available_quantity` already excludes shares frozen by pending orders or same-day settlement rules, so it is the amount you can actually close right now.
**Expected result:** a `StockPosition` for the symbol. If it is missing or `available_quantity` is `0`, there is nothing to close and you should stop.
### 2. Decide side and quantity from the sign
| `available_quantity` | Position | Order `side` | Order quantity |
| -------------------- | -------- | ------------ | -------------- |
| Greater than `0` | Long | `Sell` | `available_quantity` |
| Less than `0` | Short | `Buy` | `abs(available_quantity)` |
**Expected result:** an order side and a positive quantity. The same rule applies to stocks, ETFs, warrants and option contracts.
### 3. Pick the order type and submit
Use a market order during regular trading hours so the position is closed at once. US pre-market and after-hours sessions do not accept market orders, so switch to a limit order at the latest price and allow the order to run outside regular hours.
| Market | Session | `order_type` | `submitted_price` | `outside_rth` |
| ----------------- | ------------------------------- | ------------ | ----------------- | ------------- |
| HK / CN / SG | Any | `MO` | Not required | Not required |
| US | Regular hours | `MO` | Not required | Not required |
| US | Pre-market / after-hours | `LO` | Latest `last_done` | `ANY_TIME` |
| US | Overnight | `LO` | Latest `last_done` | `OVERNIGHT` |
Use [Trading Session](/docs/market/trade-session) to find the regular-hours window and compare it with the current US Eastern time. If `last_done` is missing or `0`, stop instead of submitting a limit order without a price.
Always pass a unique `client_request_id`. A close order is exactly the kind of request that gets retried after a timeout, and the idempotency key keeps a retry from closing the position twice.
**Expected result:** [Submit Order](./submit) returns an `order_id`. Track it with [Today Orders](./today_orders) or the [trade push](/docs/trade/trade-push) channel.
## Complete example
```python
from datetime import datetime
from uuid import uuid4
from zoneinfo import ZoneInfo
from longbridge.openapi import (
Config, OAuthBuilder, QuoteContext, TradeContext,
Market, TradeSession, OrderType, OrderSide, OutsideRTH, TimeInForceType,
)
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
quote_ctx = QuoteContext(config)
trade_ctx = TradeContext(config)
def us_in_regular_session() -> bool:
now = datetime.now(ZoneInfo("America/New_York")).time()
for market in quote_ctx.trading_session():
if market.market != Market.US:
continue
for session in market.trade_sessions:
if session.trade_session == TradeSession.Intraday:
return session.begin_time <= now < session.end_time
return False
def close_position(symbol: str) -> str:
# Step 1: read the position
resp = trade_ctx.stock_positions([symbol])
position = next(
(p for ch in resp.channels for p in ch.positions if p.symbol == symbol),
None,
)
if position is None or position.available_quantity == 0:
raise RuntimeError(f"{symbol}: nothing to close")
# Step 2: opposite side, absolute quantity
side = OrderSide.Sell if position.available_quantity > 0 else OrderSide.Buy
quantity = abs(position.available_quantity)
# Step 3: market order in regular hours, limit order outside US regular hours
order_type, price, outside_rth = OrderType.MO, None, None
if symbol.endswith(".US") and not us_in_regular_session():
quote = quote_ctx.quote([symbol])[0]
if quote.last_done == 0:
raise RuntimeError(f"{symbol}: no last price, cannot close outside regular hours")
order_type, price, outside_rth = OrderType.LO, quote.last_done, OutsideRTH.AnyTime
resp = trade_ctx.submit_order(
symbol,
order_type,
side,
quantity,
TimeInForceType.Day,
submitted_price=price,
outside_rth=outside_rth,
client_request_id=f"close-{symbol}-{uuid4().hex}",
remark="close position",
)
return resp.order_id
print(close_position("TSLA.US"))
```
```javascript
const {
Config, OAuth, QuoteContext, TradeContext,
Market, TradeSession, OrderType, OrderSide, OutsideRTH, TimeInForceType,
} = require('longbridge')
async function usInRegularSession(quoteCtx) {
const [hour, minute] = new Date()
.toLocaleTimeString('en-US', { timeZone: 'America/New_York', hour12: false })
.split(':')
.map(Number)
const now = hour * 60 + minute
for (const market of await quoteCtx.tradingSession()) {
if (market.market !== Market.US) continue
for (const session of market.tradeSessions) {
if (session.tradeSession === TradeSession.Intraday) {
const begin = session.beginTime.hour * 60 + session.beginTime.minute
const end = session.endTime.hour * 60 + session.endTime.minute
return now >= begin && now < end
}
}
}
return false
}
async function closePosition(quoteCtx, tradeCtx, symbol) {
// Step 1: read the position
const resp = await tradeCtx.stockPositions([symbol])
const position = resp.channels
.flatMap((ch) => ch.positions)
.find((p) => p.symbol === symbol)
if (!position || position.availableQuantity.isZero()) {
throw new Error(`${symbol}: nothing to close`)
}
// Step 2: opposite side, absolute quantity
const side = position.availableQuantity.isPositive() ? OrderSide.Sell : OrderSide.Buy
const quantity = position.availableQuantity.abs()
// Step 3: market order in regular hours, limit order outside US regular hours
let orderType = OrderType.MO
let submittedPrice
let outsideRth
if (symbol.endsWith('.US') && !(await usInRegularSession(quoteCtx))) {
const [quote] = await quoteCtx.quote([symbol])
if (quote.lastDone.isZero()) {
throw new Error(`${symbol}: no last price, cannot close outside regular hours`)
}
orderType = OrderType.LO
submittedPrice = quote.lastDone
outsideRth = OutsideRTH.AnyTime
}
const order = await tradeCtx.submitOrder({
symbol,
orderType,
side,
submittedQuantity: quantity,
timeInForce: TimeInForceType.Day,
submittedPrice,
outsideRth,
clientRequestId: `close-${symbol}-${Date.now()}`,
remark: 'close position',
})
return order.orderId
}
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const quoteCtx = QuoteContext.new(config)
const tradeCtx = TradeContext.new(config)
console.log(await closePosition(quoteCtx, tradeCtx, 'TSLA.US'))
}
main().catch(console.error)
```
```rust
// Cargo.toml: longbridge, tokio, rust_decimal, time, chrono, chrono-tz, uuid (v4), anyhow
use std::sync::Arc;
use chrono::Timelike;
use longbridge::{
oauth::OAuthBuilder,
quote::{QuoteContext, TradeSession},
trade::{
GetStockPositionsOptions, OrderSide, OrderType, OutsideRTH, SubmitOrderOptions,
TimeInForceType, TradeContext,
},
Config, Market,
};
use rust_decimal::Decimal;
async fn us_in_regular_session(quote_ctx: &QuoteContext) -> anyhow::Result {
let now = chrono::Utc::now().with_timezone(&chrono_tz::America::New_York);
let now = time::Time::from_hms(now.hour() as u8, now.minute() as u8, 0)?;
for market in quote_ctx.trading_session().await? {
if market.market != Market::US {
continue;
}
if let Some(session) = market
.trade_sessions
.iter()
.find(|s| s.trade_session == TradeSession::Intraday)
{
return Ok(session.begin_time <= now && now < session.end_time);
}
}
Ok(false)
}
async fn close_position(
quote_ctx: &QuoteContext,
trade_ctx: &TradeContext,
symbol: &str,
) -> anyhow::Result {
// Step 1: read the position
let positions = trade_ctx
.stock_positions(GetStockPositionsOptions::new().symbols([symbol]))
.await?;
let available = positions
.channels
.iter()
.flat_map(|ch| ch.positions.iter())
.find(|p| p.symbol == symbol)
.map(|p| p.available_quantity)
.unwrap_or_default();
if available.is_zero() {
anyhow::bail!("{symbol}: nothing to close");
}
// Step 2: opposite side, absolute quantity
let side = if available.is_sign_positive() { OrderSide::Sell } else { OrderSide::Buy };
let quantity = available.abs();
// Step 3: market order in regular hours, limit order outside US regular hours
let mut opts = SubmitOrderOptions::new(symbol, OrderType::MO, side, quantity, TimeInForceType::Day);
if symbol.ends_with(".US") && !us_in_regular_session(quote_ctx).await? {
let quote = quote_ctx.quote([symbol]).await?.remove(0);
if quote.last_done == Decimal::ZERO {
anyhow::bail!("{symbol}: no last price, cannot close outside regular hours");
}
opts = SubmitOrderOptions::new(symbol, OrderType::LO, side, quantity, TimeInForceType::Day)
.submitted_price(quote.last_done)
.outside_rth(OutsideRTH::AnyTime);
}
let opts = opts
.client_request_id(format!("close-{symbol}-{}", uuid::Uuid::new_v4()))
.remark("close position");
Ok(trade_ctx.submit_order(opts).await?.order_id)
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let oauth = OAuthBuilder::new("your-client-id")
.build(|url| println!("Open this URL to authorize: {url}"))
.await?;
let config = Arc::new(Config::from_oauth(oauth));
let (quote_ctx, _) = QuoteContext::new(config.clone());
let (trade_ctx, _) = TradeContext::new(config);
let order_id = close_position("e_ctx, &trade_ctx, "TSLA.US").await?;
println!("order_id: {order_id}");
Ok(())
}
```
```go
package main
import (
"context"
"fmt"
"log"
"strings"
"time"
openapi "github.com/longbridge/openapi-go"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/quote"
"github.com/longbridge/openapi-go/trade"
"github.com/shopspring/decimal"
)
func usInRegularSession(ctx context.Context, qctx *quote.QuoteContext) (bool, error) {
loc, err := time.LoadLocation("America/New_York")
if err != nil {
return false, err
}
now := time.Now().In(loc)
hhmm := int32(now.Hour()*100 + now.Minute())
sessions, err := qctx.TradingSession(ctx)
if err != nil {
return false, err
}
for _, market := range sessions {
if market.Market != openapi.MarketUS {
continue
}
for _, s := range market.TradeSession {
if s.TradeSession == quote.TradeSessionNormal {
return hhmm >= s.BegTime && hhmm < s.EndTime, nil
}
}
}
return false, nil
}
func closePosition(ctx context.Context, qctx *quote.QuoteContext, tctx *trade.TradeContext, symbol string) (string, error) {
// Step 1: read the position
channels, err := tctx.StockPositions(ctx, []string{symbol})
if err != nil {
return "", err
}
available := decimal.Zero
for _, ch := range channels {
for _, p := range ch.Positions {
if p.Symbol == symbol {
if available, err = decimal.NewFromString(p.AvailableQuantity); err != nil {
return "", err
}
}
}
}
if available.IsZero() {
return "", fmt.Errorf("%s: nothing to close", symbol)
}
// Step 2: opposite side, absolute quantity
side := trade.OrderSideSell
if available.IsNegative() {
side = trade.OrderSideBuy
}
quantity := available.Abs()
// Step 3: market order in regular hours, limit order outside US regular hours
order := &trade.SubmitOrder{
Symbol: symbol,
OrderType: trade.OrderTypeMO,
Side: side,
SubmittedQuantity: uint64(quantity.IntPart()),
TimeInForce: trade.TimeTypeDay,
Remark: "close position",
}
if strings.HasSuffix(symbol, ".US") {
regular, err := usInRegularSession(ctx, qctx)
if err != nil {
return "", err
}
if !regular {
quotes, err := qctx.Quote(ctx, []string{symbol})
if err != nil {
return "", err
}
if len(quotes) == 0 || quotes[0].LastDone == nil || quotes[0].LastDone.IsZero() {
return "", fmt.Errorf("%s: no last price, cannot close outside regular hours", symbol)
}
order.OrderType = trade.OrderTypeLO
order.SubmittedPrice = *quotes[0].LastDone
order.OutsideRTH = trade.OutsideRTHAny
}
}
return tctx.SubmitOrder(ctx, order)
}
func main() {
ctx := context.Background()
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(ctx); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
qctx, err := quote.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer qctx.Close()
tctx, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer tctx.Close()
orderID, err := closePosition(ctx, qctx, tctx, "TSLA.US")
if err != nil {
log.Fatal(err)
}
fmt.Println("order_id:", orderID)
}
```
```java
import com.longbridge.*;
import com.longbridge.quote.*;
import com.longbridge.trade.*;
import java.math.BigDecimal;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.UUID;
class Main {
static boolean usInRegularSession(QuoteContext quoteCtx) throws Exception {
LocalTime now = ZonedDateTime.now(ZoneId.of("America/New_York")).toLocalTime();
for (MarketTradingSession market : quoteCtx.getTradingSession().get()) {
if (market.getMarket() != Market.US) continue;
for (TradingSessionInfo session : market.getTradeSessions()) {
if (session.getTradeSession() == TradeSession.Intraday) {
return !now.isBefore(session.getBeginTime()) && now.isBefore(session.getEndTime());
}
}
}
return false;
}
static String closePosition(QuoteContext quoteCtx, TradeContext tradeCtx, String symbol) throws Exception {
// Step 1: read the position
StockPositionsResponse resp = tradeCtx
.getStockPositions(new GetStockPositionsOptions().setSymbols(new String[] { symbol }))
.get();
StockPosition position = Arrays.stream(resp.getChannels())
.flatMap(ch -> Arrays.stream(ch.getPositions()))
.filter(p -> p.getSymbol().equals(symbol))
.findFirst()
.orElse(null);
if (position == null || position.getAvailableQuantity().signum() == 0) {
throw new IllegalStateException(symbol + ": nothing to close");
}
// Step 2: opposite side, absolute quantity
OrderSide side = position.getAvailableQuantity().signum() > 0 ? OrderSide.Sell : OrderSide.Buy;
BigDecimal quantity = position.getAvailableQuantity().abs();
// Step 3: market order in regular hours, limit order outside US regular hours
SubmitOrderOptions opts = new SubmitOrderOptions(symbol, OrderType.MO, side, quantity, TimeInForceType.Day);
if (symbol.endsWith(".US") && !usInRegularSession(quoteCtx)) {
SecurityQuote quote = quoteCtx.getQuote(new String[] { symbol }).get()[0];
if (quote.getLastDone().signum() == 0) {
throw new IllegalStateException(symbol + ": no last price, cannot close outside regular hours");
}
opts = new SubmitOrderOptions(symbol, OrderType.LO, side, quantity, TimeInForceType.Day)
.setSubmittedPrice(quote.getLastDone())
.setOutsideRth(OutsideRTH.AnyTime);
}
opts.setClientRequestId("close-" + symbol + "-" + UUID.randomUUID())
.setRemark("close position");
return tradeCtx.submitOrder(opts).get().orderId;
}
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id")
.build(url -> System.out.println("Open this URL to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
QuoteContext quoteCtx = QuoteContext.create(config);
TradeContext tradeCtx = TradeContext.create(config)) {
System.out.println("order_id: " + closePosition(quoteCtx, tradeCtx, "TSLA.US"));
}
}
}
```
## Expected result
The function returns the `order_id` of the closing order. Once it fills, [Stock Positions](../asset/stock) reports `available_quantity` of `0` for the symbol, and the fill shows up in [Today Executions](../execution/today_executions).
## Notes
- **There is no close-only protection.** If the quantity exceeds the position, the excess opens a position in the opposite direction (a margin account will go short). Always cap the quantity at `available_quantity` from a fresh call, never at a cached number.
- **Read the position right before you submit.** Pending orders, partial fills and same-day buys all change `available_quantity`.
- **Cross-check with the estimate API.** [Estimate Maximum Purchase Quantity](./estimate_available_buy_limit) accepts `side=Sell` and returns the largest quantity the account can sell.
- **Partial close.** Multiply `available_quantity` by the ratio you want, then round down to the lot size from [Static Info](/docs/quote/pull/static). Odd lots on the HK market need `order_type=ODD`.
- **Multi-leg option positions.** Close them with [Submit Multi-leg Order](./submit_multileg) using the opposite `side` and the same leg ratios.
- **Idempotency.** Retry with the same `client_request_id` after a timeout. The server returns the original order for 10 minutes instead of creating a second one.
## Related
- [Submit Order](./submit)
- [Stock Positions](../asset/stock)
- [Trading Session](/docs/market/trade-session)
- [Q&A: How do I close a position?](/docs/qa/trade#q10-how-do-i-close-a-position)
---
# Estimate Maximum Purchase Quantity
URL: https://open.longbridge.com/docs/trade/order/estimate_available_buy_limit.md
This API is used for estimating the maximum purchase quantity for Hong Kong and US stocks, warrants, and options.
longbridge max-qty TSLA.US
## Request
HTTP Method GET
HTTP URL /v1/trade/estimate/buy_limit
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| ---------- | ------ | -------- | ----------------------------------------------------------------------------------------------------------------------- |
| symbol | string | YES | Stock code, using ticker.region format, for example: `AAPL.US` |
| order_type | string | YES | [Order Type](../trade-definition#ordertype) |
| price | string | NO | Estimated order price, for example: `388.5` |
| side | string | YES | Order side
**Enum Value**
`Buy` - Buy
`Sell` - Sell (Short selling is only supported for US stocks) |
| currency | string | NO | Settlement currency |
| order_id | string | NO | Order ID, required when estimating the maximum purchase quantity for a modified order |
### Request Example
```python
from longbridge.openapi import TradeContext, Config, OrderType, OrderSide, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.estimate_max_purchase_quantity(
symbol = "700.HK",
order_type = OrderType.LO,
side = OrderSide.Buy,
)
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncTradeContext, Config, OrderType, OrderSide, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.estimate_max_purchase_quantity(
symbol = "700.HK",
order_type = OrderType.LO,
side = OrderSide.Buy,
)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, TradeContext, OAuth, OrderType, OrderSide, Decimal } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = TradeContext.new(config)
const resp = await ctx.estimateMaxPurchaseQuantity({
symbol: '700.HK',
orderType: OrderType.LO,
side: OrderSide.Buy,
price: new Decimal('400'),
fractionalShares: false,
})
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.trade.*;
import java.math.BigDecimal;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
TradeContext ctx = TradeContext.create(config)) {
EstimateMaxPurchaseQuantityResponse resp = ctx.getEstimateMaxPurchaseQuantity(new EstimateMaxPurchaseQuantityOptions("700.HK", OrderType.LO, OrderSide.Buy).setPrice(new BigDecimal("400"))).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, trade::{TradeContext, EstimateMaxPurchaseQuantityOptions, OrderType, OrderSide}, Config};
use rust_decimal::Decimal;
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = TradeContext::new(config);
let resp = ctx.estimate_max_purchase_quantity(
EstimateMaxPurchaseQuantityOptions::new("700.HK", OrderType::LO, OrderSide::Buy)
.price(Decimal::from(400))
).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::trade;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
TradeContext ctx = TradeContext::create(config);
EstimateMaxPurchaseQuantityOptions opts{"700.HK", OrderType::LO, OrderSide::Buy, Decimal(400.0), 100};
ctx.estimate_max_purchase_quantity(opts, [](auto res) {
if (!res) { std::cout << "failed" << std::endl; return; }
std::cout << "max_cash_buy: " << res->max_cash_buy << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/trade"
"github.com/shopspring/decimal"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
tctx, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer tctx.Close()
resp, err := tctx.EstimateMaxPurchaseQuantity(context.Background(), &trade.GetEstimateMaxPurchaseQuantity{
Symbol: "AAPL.US",
OrderType: trade.OrderTypeLO,
Price: decimal.NewFromFloat(175.62),
Currency: "USD",
Side: trade.OrderSideBuy,
})
if err != nil {
log.Fatal(err)
}
fmt.Println("max_cash_buy:", resp.MaxCashBuy)
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"cash_max_qty": "100",
"margin_max_qty": "100"
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------------------------------------------------- | --------------------------------------------------------------------------- |
| 200 | Estimate Maximum Purchase Quantity Success | [estimate_available_buy_limit_rsp](#schemaestimate_available_buy_limit_rsp) |
| 400 | The query failed with an error in the request parameter. | None |
## Schemas
### estimate_available_buy_limit_rsp
Estimated Maximum Purchase Quantity
| Name | Type | Required | Description |
| -------------- | ------ | -------- | --------------------------------------------------------- |
| cash_max_qty | string | true | Cash available quantity, default value is empty string. |
| margin_max_qty | string | true | Margin available quantity, default value is empty string. |
---
# History Orders
URL: https://open.longbridge.com/docs/trade/order/history_orders.md
This API is used to get history order.
longbridge order --history
## Request
HTTP Method GET
HTTP URL /v1/trade/order/history
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| -------- | -------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| symbol | string | NO | Stock symbol, use `ticker.region` format, example: `AAPL.US` |
| status | string[] | NO | [Order status](../trade-definition#orderstatus)
example: `status=FilledStatus&status=NewStatus` |
| side | string | NO | Order side
**Enum Value:**
`Buy`
`Sell` |
| market | string | NO | Market
**Enum Value:**
`US` - United States of America Market
`HK` - Hong Kong Market |
| start_at | string | NO | Start time, formatted as a timestamp (second), example: `1650410999`.
If the start time is null, the default is the 90 days before of the end time or 90 days before of the current time. |
| end_at | string | NO | End time, formatted as a timestamp (second), example: `1650410999`.
If the end time is null, the default is the current time or 90 days after of the start time. |
### Request Example
```python
from datetime import datetime
from longbridge.openapi import TradeContext, Config, OrderStatus, OrderSide, Market, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.history_orders(
symbol = "700.HK",
status = [OrderStatus.Filled, OrderStatus.New],
side = OrderSide.Buy,
market = Market.HK,
start_at = datetime(2022, 5, 9),
end_at = datetime(2022, 5, 12),
)
print(resp)
```
```python
import asyncio
from datetime import datetime
from longbridge.openapi import AsyncTradeContext, Config, OrderStatus, OrderSide, Market, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.history_orders(
symbol = "700.HK",
status = [OrderStatus.Filled, OrderStatus.New],
side = OrderSide.Buy,
market = Market.HK,
start_at = datetime(2022, 5, 9),
end_at = datetime(2022, 5, 12),
)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, TradeContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = TradeContext.new(config)
const resp = await ctx.historyOrders({})
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.trade.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
TradeContext ctx = TradeContext.create(config)) {
Order[] resp = ctx.getHistoryOrders(null).get();
for (Order o : resp) System.out.println(o);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, trade::TradeContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = TradeContext::new(config);
let resp = ctx.history_orders(None).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::trade;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
TradeContext ctx = TradeContext::create(config);
ctx.history_orders(std::nullopt, [](auto res) {
if (!res) { std::cout << "failed" << std::endl; return; }
for (const auto& o : *res) std::cout << o.order_id << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/trade"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
tctx, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer tctx.Close()
orders, hasMore, err := tctx.HistoryOrders(context.Background(), &trade.GetHistoryOrders{})
if err != nil {
log.Fatal(err)
}
for _, o := range orders {
fmt.Println(o.OrderId)
}
_ = hasMore
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"orders": [
{
"currency": "HKD",
"executed_price": "0.000",
"executed_quantity": "0",
"expire_date": "",
"last_done": "",
"limit_offset": "",
"msg": "",
"order_id": "706388312699592704",
"order_type": "ELO",
"outside_rth": "UnknownOutsideRth",
"price": "11.900",
"quantity": "200",
"side": "Buy",
"status": "RejectedStatus",
"stock_name": "Bank of East Asia Ltd/The",
"submitted_at": "1651644897",
"symbol": "23.HK",
"tag": "Normal",
"time_in_force": "Day",
"trailing_amount": "",
"trailing_percent": "",
"trigger_at": "0",
"trigger_price": "",
"trigger_status": "NOT_USED",
"updated_at": "1651644898",
"remark": "",
"limit_depth_level": 0,
"monitor_price": "",
"trigger_count": 1,
"attached_orders": [
{
"order_id": "706388312699592705",
"attached_type_display": 2,
"trigger_price": "10.500",
"quantity": "200",
"executed_qty": "0",
"status": "NewStatus",
"updated_at": "1651644898",
"withdrawn": false,
"gtd": "",
"time_in_force": "Day",
"counter_id": "",
"trigger_status": 0,
"executed_amount": "0",
"tag": 0,
"submitted_at": "1651644897",
"executed_price": "0.000",
"force_only_rth": "RTH_ONLY",
"reviewed": false,
"activate_order_type": "MIT",
"activate_rth": "RTH_ONLY",
"submit_price": "",
"limit_depth_level": 0
}
],
"multi_leg": {
"strategy": "2",
"strategy_name": "Vertical spread",
"multileg_id": "Spread_QQQ20260731C764/767",
"code": "QQQ 260731 764/767 Vertical spread",
"legs": [
{
"symbol": "QQQ260731C764000.US",
"side": "Buy",
"position": "LONG",
"ratio_quantity": "1",
"strike_price": "764",
"expire_date": "20260731",
"contract_direction": "C"
},
{
"symbol": "QQQ260731C767000.US",
"side": "Sell",
"position": "SHORT",
"ratio_quantity": "1",
"strike_price": "767",
"expire_date": "20260731",
"contract_direction": "C"
}
]
}
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------------------------------------------------- | ----------------------------------------------- |
| 200 | Get History Orders Success | [history_orders_rsp](#schemahistory_orders_rsp) |
| 400 | The query failed with an error in the request parameter. | None |
## Schemas
### history_orders_rsp
| Name | Type | Required | Description |
| ------------------- | -------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| has_more | boolean | true | has more orders record.
The maximum number of orders per query is 1000, if the number of results exceeds 1000, then has_more will be true |
| orders | object[] | false | Order Detail |
| ∟ order_id | string | true | Order ID |
| ∟ status | string | true | [Order Status](../trade-definition#orderstatus) |
| ∟ stock_name | string | true | Stock Name |
| ∟ quantity | string | true | Submitted Quantity |
| ∟ executed_quantity | string | true | Executed Quantity.
when the order is not filled, value is 0 |
| ∟ price | string | true | Submitted Price.
when market condition order is not triggered, value is empty string |
| ∟ executed_price | string | true | Executed Price.
when the order is not filled, value is 0 |
| ∟ submitted_at | string | true | Submitted Time |
| ∟ side | string | true | Order Side
**Enum Value:**
`Buy`
`Sell` |
| ∟ symbol | string | true | Stock symbol, use `ticker.region` format, example: `AAPL.US` |
| ∟ order_type | string | true | [Order Type](../trade-definition#ordertype) |
| ∟ last_done | string | true | Last done.
when the order is not filled, value is empty string |
| ∟ trigger_price | string | true | `LIT` / `MIT` Order Trigger Price.
When the order is not `LIT` / `MIT` order, value is empty string |
| ∟ msg | string | true | Rejected message or remark, default value is empty string. |
| ∟ tag | string | true | Order tag
**Enum Value**
`Normal` - Normal Order
`Gtc` - Long term Order
`Grey` - Grey Order |
| ∟ time_in_force | string | true | Time in force Type
**Enum Value:**
`Day` - Day Order
`GTC` - Good Til Canceled Order
`GTD` - Good Til Date Order |
| ∟ expire_date | string | true | Long term order expire date, format: `YYYY-MM-DD`, example: `2022-12-05`.
When not a long term order, default value is empty string |
| ∟ updated_at | string | true | Last updated time, formatted as a timestamp (second) |
| ∟ trigger_at | string | true | Conditional order trigger time. formatted as a timestamp (second) |
| ∟ trailing_amount | string | true | `TSLPAMT` order trailing amount.
When the order is not `TSLPAMT` order, value is empty string |
| ∟ trailing_percent | string | true | `TSLPPCT` order trailing percent.
When the order is not `TSLPPCT` order, value is empty string |
| ∟ limit_offset | string | true | `TSLPPCT` order limit offset amount.
When the order is not `TSLPPCT` order, value is empty string |
| ∟ trigger_status | string | true | Conditional Order Trigger Status
When an order is not a conditional order or a conditional order is not triggered, the trigger status is NOT_USED
**Enum Value**
`NOT_USED`
`DEACTIVE`
`ACTIVE`
`RELEASED` |
| ∟ currency | string | true | Currency |
| ∟ outside_rth | string | true | Enable or disable outside regular trading hours
Default is `UnknownOutsideRth` when the order is not a US stock
**Enum Value:**
`RTH_ONLY` - Regular trading hour only
`ANY_TIME` - Any time
`OVERNIGHT` - Overnight" |
| ∟ remark | string | true | Remark |
| ∟ limit_depth_level | int32 | true | Specifies the bid/ask depth level |
| ∟ monitor_price | string | true | Monitoring price |
| ∟ trigger_count | int32 | true | Number of triggers |
| ∟ attached_orders | object[] | false | List of attached order details |
| ∟∟ order_id | string | true | Attached order ID |
| ∟∟ attached_type_display | int32 | true | Attached order type.
**Enum Value:**
`1` - Take Profit
`2` - Stop Loss |
| ∟∟ trigger_price | string | true | Trigger price |
| ∟∟ quantity | string | true | Order quantity |
| ∟∟ executed_qty | string | true | Executed quantity |
| ∟∟ status | string | true | Order status |
| ∟∟ updated_at | string | true | Last updated time, formatted as a timestamp (second) |
| ∟∟ withdrawn | boolean | true | Whether the order has been withdrawn |
| ∟∟ gtd | string | true | GTD expiration date, format: `YYYY-MM-DD` |
| ∟∟ time_in_force | string | true | Time in force Type
**Enum Value:**
`Day` - Day Order
`GTC` - Good Til Canceled Order
`GTD` - Good Til Date Order |
| ∟∟ counter_id | string | true | Counter order ID |
| ∟∟ trigger_status | int32 | true | Conditional order trigger status after the attached order is activated.
`0` - Not activated
`1` - Monitoring
`2` - Cancelled
`4` - Triggered |
| ∟∟ executed_amount | string | true | Executed amount |
| ∟∟ tag | int32 | true | Order tag |
| ∟∟ submitted_at | string | true | Submitted time, formatted as a timestamp (second) |
| ∟∟ executed_price | string | true | Executed price |
| ∟∟ force_only_rth | string | true | Whether execution is restricted to regular trading hours only |
| ∟∟ reviewed | boolean | true | Whether the order has been reviewed|
| ∟∟ activate_order_type | string | true | Order type submitted after triggering, e.g. `LIT` (limit-if-touched) or `MIT` (market-if-touched) |
| ∟∟ activate_rth | string | true | Whether the order submitted after triggering allows pre/post market trading |
| ∟∟ submit_price | string | true | Submitted price |
| ∟∟ limit_depth_level | int32 | true | Specifies the bid/ask depth level |
| ∟ multi_leg | object | false | Multi-leg strategy information. Only returned for multi-leg option combination orders; otherwise not returned. |
| ∟∟ strategy | string | false | Multi-leg strategy
**Enum Value:**
`0` - CoveredCall (Covered stock)
`1` - CoveredPut (Covered stock)
`2` - VerticalCallSpread (Vertical spread)
`3` - VerticalPutSpread (Vertical spread)
`4` - Collar
`5` - Straddle
`6` - Strangle
`7` - CalendarCallSpread (Calendar)
`8` - CalendarPutSpread (Calendar) |
| ∟∟ strategy_name | string | false | Strategy name |
| ∟∟ multileg_id | string | false | Multi-leg combination ID |
| ∟∟ code | string | false | Multi-leg combination code |
| ∟∟ legs | object[] | false | Legs of the combination order |
| ∟∟∟ symbol | string | false | Option symbol, use `ticker.region` format, example: `QQQ260731C764000.US` |
| ∟∟∟ side | string | false | Order Side
**Enum Value:**
`Buy`
`Sell` |
| ∟∟∟ position | string | false | Position direction
**Enum Value:**
`LONG`
`SHORT` |
| ∟∟∟ ratio_quantity | string | false | Leg ratio quantity |
| ∟∟∟ strike_price | string | false | Strike price |
| ∟∟∟ expire_date | string | false | Option expiry date, format: `YYYYMMDD` |
| ∟∟∟ contract_direction | string | false | Contract type
**Enum Value:**
`C` - Call
`P` - Put |
---
# Order Details
URL: https://open.longbridge.com/docs/trade/order/order_detail.md
This API is used for order detail query
# Replace the order ID below with your actual order ID
longbridge order detail 693664675163312128
## Request
HTTP Method GET
HTTP URL /v1/trade/order
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| ----------- | ------ | -------- | ------------------------------------------------------------------------- |
| order_id | string | YES | Order ID for specifying order ID query, for example: `701276261045858304` |
| is_attached | bool | NO | Whether `order_id` refers to an attached order |
### Request Example
```python
from longbridge.openapi import TradeContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.order_detail(
order_id = "701276261045858304",
is_attached = False,
)
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncTradeContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.order_detail(
order_id = "701276261045858304",
is_attached = False,
)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, TradeContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = TradeContext.new(config)
const resp = await ctx.orderDetail('701276261045858304')
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.trade.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
TradeContext ctx = TradeContext.create(config)) {
OrderDetail resp = ctx.getOrderDetail("701276261045858304").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, trade::TradeContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = TradeContext::new(config);
let resp = ctx.order_detail("701276261045858304").await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::trade;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
TradeContext ctx = TradeContext::create(config);
ctx.order_detail("701276261045858304", [](auto res) {
if (!res) { std::cout << "failed" << std::endl; return; }
std::cout << res->order_id << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/trade"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
tctx, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer tctx.Close()
detail, err := tctx.OrderDetail(context.Background(), "701276261045858304")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", detail)
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"order_id": "828940451093708800",
"status": "FilledStatus",
"stock_name": "Apple",
"quantity": "10",
"executed_quantity": "10",
"price": "200.000",
"executed_price": "164.660",
"submitted_at": "1680863604",
"side": "Buy",
"symbol": "AAPL.US",
"order_type": "LO",
"last_done": "164.660",
"trigger_price": "0.0000",
"msg": "",
"tag": "Normal",
"time_in_force": "Day",
"expire_date": "2023-04-10",
"updated_at": "1681113000",
"trigger_at": "0",
"trailing_amount": "",
"trailing_percent": "",
"limit_offset": "",
"limit_depth_level": 0,
"monitor_price": "",
"trigger_count": 1,
"trigger_status": "NOT_USED",
"outside_rth": "ANY_TIME",
"currency": "USD",
"remark": "1680863603.927165",
"free_status": "None",
"free_amount": "",
"free_currency": "",
"deductions_status": "NONE",
"deductions_amount": "",
"deductions_currency": "",
"platform_deducted_status": "NONE",
"platform_deducted_amount": "",
"platform_deducted_currency": "",
"history": [
{
"price": "164.6600",
"quantity": "10",
"status": "FilledStatus",
"msg": "Execution of 10",
"time": "1681113000"
},
{
"price": "200.0000",
"quantity": "10",
"status": "NewStatus",
"msg": "",
"time": "1681113000"
}
],
"charge_detail": {
"items": [
{
"code": "BROKER_FEES",
"name": "Broker Fees",
"fees": []
},
{
"code": "THIRD_FEES",
"name": "Third-party Fees",
"fees": []
}
],
"total_amount": "0",
"currency": "USD"
},
"attached_orders": [
{
"order_id": "706388312699592705",
"attached_type_display": 2,
"trigger_price": "10.500",
"quantity": "200",
"executed_qty": "0",
"status": "NewStatus",
"updated_at": "1651644898",
"withdrawn": false,
"gtd": "",
"time_in_force": "Day",
"counter_id": "",
"trigger_status": 0,
"executed_amount": "0",
"tag": 0,
"submitted_at": "1651644897",
"executed_price": "0.000",
"force_only_rth": "RTH_ONLY",
"reviewed": false,
"activate_order_type": "MIT",
"activate_rth": "RTH_ONLY",
"submit_price": "",
"limit_depth_level": 0
}
],
"multi_leg": {
"strategy": "2",
"strategy_name": "Vertical spread",
"multileg_id": "Spread_QQQ20260731C764/767",
"code": "QQQ 260731 764/767 Vertical spread",
"legs": [
{
"symbol": "QQQ260731C764000.US",
"side": "Buy",
"position": "LONG",
"ratio_quantity": "1",
"strike_price": "764",
"expire_date": "20260731",
"contract_direction": "C"
},
{
"symbol": "QQQ260731C767000.US",
"side": "Sell",
"position": "SHORT",
"ratio_quantity": "1",
"strike_price": "767",
"expire_date": "20260731",
"contract_direction": "C"
}
]
}
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------------------------------- | ------------------------------------------- |
| 200 | Order detail query successful | [order_detail_rsp](#schemaorder_detail_rsp) |
| 400 | Query failed, request parameter error. | None |
## Schemas
### order_detail_rsp
Order Information
| Name | Type | Required | Description |
| -------------------------- | -------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| order_id | string | true | Order ID |
| status | string | true | [Order Status](../trade-definition#orderstatus) |
| stock_name | string | true | Stock Name |
| quantity | string | true | Order Quantity |
| executed_quantity | string | true | Executed Quantity
When the order is not executed, it is 0 |
| price | string | true | Order Price
When the market price conditional order is not triggered, it is an empty string |
| executed_price | string | true | Execution Price
When the order is not executed, it is 0 |
| submitted_at | string | true | Submitted Time |
| side | string | true | Order Side
**Enum Value:**
`Buy`
`Sell` |
| symbol | string | true | Stock symbol, use `ticker.region` format, example: `AAPL.US` |
| order_type | string | true | [Order Type](../trade-definition#ordertype) |
| last_done | string | true | Last done.
when the order is not filled, value is empty string |
| trigger_price | string | true | `LIT` / `MIT` Order Trigger Price.
When the order is not `LIT` / `MIT` order, value is empty string |
| msg | string | true | Rejected message or remark, default value is empty string. |
| tag | string | true | Order tag
**Enum Value**
`Normal` - Normal Order
`Gtc` - Long term Order
`Grey` - Grey Order |
| time_in_force | string | true | Time in force Type
**Enum Value:**
`Day` - Day Order
`GTC` - Good Til Canceled Order
`GTD` - Good Til Date Order |
| expire_date | string | true | Long term order expire date, format: `YYYY-MM-DD`, example: `2022-12-05`.
When not a long term order, default value is empty string |
| updated_at | string | true | Last updated time, formatted as a timestamp (second) |
| trigger_at | string | true | Conditional order trigger time. formatted as a timestamp (second) |
| trailing_amount | string | true | `TSLPAMT` order trailing amount.
When the order is not `TSLPAMT` order, value is empty string |
| trailing_percent | string | true | `TSLPPCT` order trailing percent.
When the order is not `TSLPPCT` order, value is empty string |
| limit_offset | string | true | `TSLPPCT` order limit offset amount.
When the order is not `TSLPPCT` order, value is empty string |
| trigger_status | string | true | Conditional Order Trigger Status
When an order is not a conditional order or a conditional order is not triggered, the trigger status is NOT_USED
**Enum Value**
`NOT_USED`
`DEACTIVE`
`ACTIVE`
`RELEASED` |
| currency | string | true | Currency |
| outside_rth | string | true | Enable or disable outside regular trading hours
Default is `UnknownOutsideRth` when the order is not a US stock
**Enum Value:**
`RTH_ONLY` - Regular trading hour only
`ANY_TIME` - Any time
`OVERNIGHT` - Overnight" |
| remark | string | true | Remark |
| free_status | string | true | Commission-free Status, default value is None
**Enum Value:**
`None` - None
`Calculated` - Commission-free amount to be calculated
`Pending` - Pending commission-free
`Ready` - Commission-free applied |
| free_amount | string | true | Commission-free amount, default value is empty string. |
| free_currency | string | true | Commission-free currency, default value is empty string. |
| deductions_status | string | true | Deduction status/Cashback Status, default value is NONE
**Enum Value:**
`NONE` - Pending Settlement
`NO_DATA` - Settled with no data
`PENDING` - Settled and pending distribution
`DONE` - Settled and distributed |
| deductions_amount | string | true | Deduction amount, default value is empty string. |
| deductions_currency | string | true | Deduction currency, default value is empty string. |
| platform_deducted_status | string | true | Platform fee deduction status/Cashback Status, default value is NONE
**Enum Value:**
`NONE` - Pending Settlement
`NO_DATA` - Settled with no data
`PENDING` - Settled and pending distribution
`DONE` - Settled and distributed |
| platform_deducted_amount | string | true | Platform fee deduction amount, default value is empty string. |
| platform_deducted_currency | string | true | Platform fee deduction currency, default value is empty string. |
| history | object[] | true | Order history details |
| ∟ price | string | true | Executed price for executed orders, submitted price for expired, canceled, rejected orders, etc. |
| ∟ quantity | string | true | Executed quantity for executed orders, remaining quantity for expired, canceled, rejected orders, etc. |
| ∟ status | string | true | Order status |
| ∟ msg | string | true | Execution or error message |
| ∟ time | string | true | Occurrence time |
| charge_detail | object | true | Order charges |
| ∟ total_amount | string | true | Total charges amount |
| ∟ currency | string | true | Settlement currency |
| ∟ items | object[] | true | Order charge details |
| ∟∟ code | string | true | Charge category code
**Enum Value:**
`UNKNOWN`
`BROKER_FEES`
`THIRD_FEES` |
| ∟∟ name | string | true | Charge category name |
| ∟∟ fees | object[] | true | Charge details |
| ∟∟∟ code | string | true | Charge code |
| ∟∟∟ name | string | true | Charge name |
| ∟∟∟ amount | string | true | Charge amount |
| ∟∟∟ currency | string | true | Charge currency |
| ∟ limit_depth_level | int32 | true | Specifies the bid/ask depth level |
| ∟ monitor_price | string | true | Monitoring price |
| ∟ trigger_count | int32 | true | Number of triggers |
| ∟ attached_orders | object[] | false | List of attached order details |
| ∟∟ order_id | string | true | Attached order ID |
| ∟∟ attached_type_display | int32 | true | Attached order type.
**Enum Value:**
`1` - Take Profit
`2` - Stop Loss |
| ∟∟ trigger_price | string | true | Trigger price |
| ∟∟ quantity | string | true | Order quantity |
| ∟∟ executed_qty | string | true | Executed quantity |
| ∟∟ status | string | true | Order status |
| ∟∟ updated_at | string | true | Last updated time, formatted as a timestamp (second) |
| ∟∟ withdrawn | boolean | true | Whether the order has been withdrawn |
| ∟∟ gtd | string | true | GTD expiration date, format: `YYYY-MM-DD` |
| ∟∟ time_in_force | string | true | Time in force Type
**Enum Value:**
`Day` - Day Order
`GTC` - Good Til Canceled Order
`GTD` - Good Til Date Order |
| ∟∟ counter_id | string | true | Counter order ID |
| ∟∟ trigger_status | int32 | true | Conditional order trigger status after the attached order is activated.
`0` - Not activated
`1` - Monitoring
`2` - Cancelled
`4` - Triggered |
| ∟∟ executed_amount | string | true | Executed amount |
| ∟∟ tag | int32 | true | Order tag |
| ∟∟ submitted_at | string | true | Submitted time, formatted as a timestamp (second) |
| ∟∟ executed_price | string | true | Executed price |
| ∟∟ force_only_rth | string | true | Whether execution is restricted to regular trading hours only |
| ∟∟ reviewed | boolean | true | Whether the order has been reviewed |
| ∟∟ activate_order_type | string | true | Order type submitted after triggering, e.g. `LIT` (limit-if-touched) or `MIT` (market-if-touched) |
| ∟∟ activate_rth | string | true | Whether the order submitted after triggering allows pre/post market trading |
| ∟∟ submit_price | string | true | Submitted price |
| ∟∟ limit_depth_level | int32 | true | Specifies the bid/ask depth level |
| multi_leg | object | false | Multi-leg strategy information. Only returned for multi-leg option combination orders; otherwise not returned. |
| ∟ strategy | string | false | Multi-leg strategy
**Enum Value:**
`0` - CoveredCall (Covered stock)
`1` - CoveredPut (Covered stock)
`2` - VerticalCallSpread (Vertical spread)
`3` - VerticalPutSpread (Vertical spread)
`4` - Collar
`5` - Straddle
`6` - Strangle
`7` - CalendarCallSpread (Calendar)
`8` - CalendarPutSpread (Calendar) |
| ∟ strategy_name | string | false | Strategy name |
| ∟ multileg_id | string | false | Multi-leg combination ID |
| ∟ code | string | false | Multi-leg combination code |
| ∟ legs | object[] | false | Legs of the combination order |
| ∟∟ symbol | string | false | Option symbol, use `ticker.region` format, example: `QQQ260731C764000.US` |
| ∟∟ side | string | false | Order Side
**Enum Value:**
`Buy`
`Sell` |
| ∟∟ position | string | false | Position direction
**Enum Value:**
`LONG`
`SHORT` |
| ∟∟ ratio_quantity | string | false | Leg ratio quantity |
| ∟∟ strike_price | string | false | Strike price |
| ∟∟ expire_date | string | false | Option expiry date, format: `YYYYMMDD` |
| ∟∟ contract_direction | string | false | Contract type
**Enum Value:**
`C` - Call
`P` - Put |
---
# Replace Order
URL: https://open.longbridge.com/docs/trade/order/replace.md
This API is used to replace order, modify quantity or price.
# Replace the order ID below with your actual order ID
longbridge order replace 693664675163312128 --qty 200 --price 255.00
## Request
HTTP Method PUT
HTTP URL /v1/trade/order
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| ----------------- | ------ | -------- | ------------------------------------------------------------------------------------------------------ |
| order_id | string | YES | Order ID |
| quantity | string | YES | Replaced quantity, example: `100` |
| price | string | NO | Replaced price, example: `388.5`
`LO` / `ELO` / `ALO` / `ODD` / `LIT` Order Required |
| trigger_price | string | NO | Trigger price, example: `388.5`
`LIT` / `MIT` Order Required |
| limit_offset | string | NO | Limit offset amount
`TSLPAMT` / `TSLPPCT` Order Required when`limit_depth_level` is set to 0 |
| trailing_amount | string | NO | Trailing amount
`TSLPAMT` Order Required |
| trailing_percent | string | NO | Trailing percent
`TSLPPCT` Order Required |
| remark | string | NO | Remark (Maximum 64 characters) |
| limit_depth_level | int32 | NO | Specifies the bid/ask depth level. `TSLPAMT` / `TSLPPCT` Order Required |
| monitor_price | string | NO | Monitoring price. `TSLPAMT` / `TSLPPCT` Order Required |
| trigger_count | int32 | NO | Number of triggers. `LIT` / `MIT` / `TSLPAMT` / `TSLPPCT` Order Required |
| attached_params | object | NO | Attached order parameters (take-profit / stop-loss) |
| attached_params.attached_order_type | string | NO | Attached order type
**Enum Value:**
`PROFIT_TAKER` - Take Profit
`STOP_LOSS` - Stop Loss
`BRACKET` - Bracket Order |
| attached_params.profit_taker_price | string | NO | Take-profit trigger price |
| attached_params.stop_loss_price | string | NO | Stop-loss trigger price |
| attached_params.time_in_force | string | NO | Attached order time in force type
**Enum Value:**
`Day` - Day Order
`GTC` - Good Til Canceled Order
`GTD` - Good Til Date Order (inherits the main order's `expire_date` in this case) |
| attached_params.expire_time | int64 | NO | Expire time (Unix timestamp, in seconds) |
| attached_params.profit_taker_id | int64 | NO | Take-profit order ID, fill in when modifying an existing take-profit order |
| attached_params.stop_loss_id | int64 | NO | Stop-loss order ID, fill in when modifying an existing stop-loss order |
| attached_params.cancel_all_attached | bool | NO | Whether to cancel all attached orders |
| attached_params.main_id | int64 | NO | Main order ID |
| attached_params.quantity | string | NO | Attached order quantity |
| attached_params.market_price | string | NO | Market price |
| attached_params.activate_order_type | string | NO | Order type submitted after triggering, e.g. `LIT` (limit-if-touched) or `MIT` (market-if-touched) |
| attached_params.profit_taker_submit_price | string | NO | Take-profit limit order submitted price, required when `activate_order_type` is `LIT` |
| attached_params.stop_loss_submit_price | string | NO | Stop-loss limit order submitted price, required when `activate_order_type` is `LIT` |
| attached_params.activate_rth | string | NO | Whether the order submitted after triggering allows pre/post market trading
**Enum Value:**
`RTH_ONLY` - Regular trading hours only
`ANY_TIME` - Any time |
| attached_params.profit_taker_depth_level | int32 | NO | Specifies the bid/ask depth level for the take-profit limit order submitted price, valid when `activate_order_type` is `LIT` |
| attached_params.stop_loss_depth_level | int32 | NO | Specifies the bid/ask depth level for the stop-loss limit order submitted price, valid when `activate_order_type` is `LIT` |
### Request Example
```python
from decimal import Decimal
from longbridge.openapi import TradeContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
ctx.replace_order(
order_id = "709043056541253632",
quantity = Decimal(100),
price = Decimal(50),
)
```
```python
import asyncio
from decimal import Decimal
from longbridge.openapi import AsyncTradeContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
ctx.replace_order(
order_id = "709043056541253632",
quantity = Decimal(100),
price = Decimal(50),
)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, TradeContext, OAuth, Decimal } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = TradeContext.new(config)
await ctx.replaceOrder({ orderId: '701276261045858304', quantity: new Decimal(400), price: new Decimal(60) })
console.log('replaced')
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.trade.*;
import java.math.BigDecimal;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
TradeContext ctx = TradeContext.create(config)) {
ctx.replaceOrder(new ReplaceOrderOptions("701276261045858304", new BigDecimal("400")).setPrice(new BigDecimal("60"))).get();
System.out.println("replaced");
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, trade::{TradeContext, ReplaceOrderOptions}, Config};
use rust_decimal::Decimal;
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = TradeContext::new(config);
ctx.replace_order(
ReplaceOrderOptions::new("701276261045858304", Decimal::from(400))
.price(Decimal::from(60))
).await?;
println!("replaced");
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::trade;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
TradeContext ctx = TradeContext::create(config);
ReplaceOrderOptions opts{"701276261045858304", 400, Decimal(60.0)};
ctx.replace_order(opts, [](auto res) {
if (!res) { std::cout << "failed" << std::endl; return; }
std::cout << "replaced" << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/trade"
"github.com/shopspring/decimal"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
tctx, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer tctx.Close()
err = tctx.ReplaceOrder(context.Background(), &trade.ReplaceOrder{
OrderId: "701276261045858304",
Quantity: 400,
Price: decimal.NewFromFloat(60),
})
if err != nil {
log.Fatal(err)
}
fmt.Println("replaced")
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ------------------------------------------------------------- | ------ |
| 200 | The submission was successful and the order was commissioned. | None |
| 400 | The replace was rejected with an incorrect request parameter. | None |
---
# Submit Order
URL: https://open.longbridge.com/docs/trade/order/submit.md
This API is used to submit order for HK and US stocks, warrant and option.
longbridge order buy TSLA.US 100 --price 250.00
longbridge order sell TSLA.US 100 --price 260.00
## Request
HTTP Method POST
HTTP URL /v1/trade/order
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| ------------------ | ------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| symbol | string | YES | Stock symbol, use `ticker.region` format, example: `AAPL.US` |
| order_type | string | YES | [Order Type](../trade-definition#ordertype) |
| submitted_price | string | NO | Submitted price, example: `388.5`
`LO` / `ELO` / `ALO` / `ODD` / `LIT` Order Required |
| submitted_quantity | string | YES | Submitted quantity, example: `100`
US stocks accept fractional quantities, such as `0.05`. Fractional US orders must set `outside_rth` to `RTH_ONLY`; otherwise the order is rejected with error code `603200`. |
| trigger_price | string | NO | Trigger price, example: `388.5`
`LIT` / `MIT` Order Required |
| limit_offset | string | NO | Limit offset amount
`TSLPAMT` / `TSLPPCT` Order Required when`limit_depth_level` is set to 0 |
| trailing_amount | string | NO | Trailing amount
`TSLPAMT` Order Required |
| trailing_percent | string | NO | Trailing percent
`TSLPPCT` Order Required |
| expire_date | string | NO | Long term order expire date, format `YYYY-MM-DD`, example: `2022-12-05`
Required when `time_in_force` is `GTD` |
| side | string | YES | Order Side
**Enum Value:**
`Buy`
`Sell` |
| outside_rth | string | NO | Enable or disable outside regular trading hours
**Enum Value:**
`RTH_ONLY` - regular trading hour only
`ANY_TIME` - any time
`OVERNIGHT` - Overnight
`OPTION_PRE_MARKET` - Overnight option |
| time_in_force | string | YES | Time in force Type
**Enum Value:**
`Day` - Day Order
`GTC` - Good Til Canceled Order
`GTD` - Good Til Date Order |
| remark | string | NO | remark (Maximum 255 characters) |
| limit_depth_level | int32 | NO | Specifies the bid/ask depth level. Value range is -5 ~ 0 ~ 5.
Negative numbers indicate bid levels (e.g., -1 means best bid level 1),
positive numbers indicate ask levels (e.g., 1 means best ask level 1).
When set to 0, the `limit_offset` parameter takes effect.
Valid for `TSLPAMT` / `TSLPPCT` orders. |
| monitor_price | string | NO | Monitoring price.
Monitoring starts only after reaching this price, updating the reference price.
Valid for `TSLPAMT` / `TSLPPCT` orders. |
| trigger_count | int32 | NO | Number of triggers. Value range is 0 ~ 3.
Specifies that within 1 minute, the order will only be placed after being triggered multiple times.
Valid for `LIT` / `MIT` / `TSLPAMT` / `TSLPPCT` orders. |
| client_request_id | string | NO | Idempotent request ID for preventing duplicate order submissions. The server caches this request ID for 10 minutes. If a request with the same ID is received within this period, it returns the same response without creating a duplicate order. Must be a unique identifier (e.g., UUID). |
| attached_params | object | NO | Attached order parameters (take-profit / stop-loss) |
| attached_params.attached_order_type | string | NO | Attached order type
**Enum Value:**
`PROFIT_TAKER` - Take Profit
`STOP_LOSS` - Stop Loss
`BRACKET` - Bracket Order |
| attached_params.profit_taker_price | string | NO | Take-profit trigger price |
| attached_params.stop_loss_price | string | NO | Stop-loss trigger price |
| attached_params.time_in_force | string | NO | Attached order time in force type
**Enum Value:**
`Day` - Day Order
`GTC` - Good Til Canceled Order
`GTD` - Good Til Date Order (inherits the main order's `expire_date` in this case) |
| attached_params.expire_time | int64 | NO | Expire time (Unix timestamp, in seconds) |
| attached_params.activate_order_type | string | NO | Order type submitted after triggering, e.g. `LIT` (limit-if-touched) or `MIT` (market-if-touched) |
| attached_params.profit_taker_submit_price | string | NO | Take-profit limit order submitted price, required when `activate_order_type` is `LIT` |
| attached_params.stop_loss_submit_price | string | NO | Stop-loss limit order submitted price, required when `activate_order_type` is `LIT` |
| attached_params.activate_rth | string | NO | Whether the order submitted after triggering allows pre/post market trading
**Enum Value:**
`RTH_ONLY` - Regular trading hours only
`ANY_TIME` - Any time |
| attached_params.profit_taker_depth_level | int32 | NO | Specifies the bid/ask depth level for the take-profit limit order submitted price, valid when `activate_order_type` is `LIT` |
| attached_params.stop_loss_depth_level | int32 | NO | Specifies the bid/ask depth level for the stop-loss limit order submitted price, valid when `activate_order_type` is `LIT` |
### Idempotency
To ensure orders are not duplicated due to network retries or client failures, you can use the `client_request_id` parameter:
- **Purpose**: Prevents duplicate order creation when the same request is retried
- **Cache Duration**: 10 minutes (server-side)
- **Format**: Any unique string per request (e.g., UUID, or a client-generated identifier)
- **Behavior**: If the same `client_request_id` is received within 10 minutes, the server returns the cached response from the original request without creating a new order
#### Idempotency Example
```
First request: client_request_id="abc123-uuid-request" → Creates order with ID 12345
Retry (same ID within 10 min): client_request_id="abc123-uuid-request" → Returns existing order ID 12345 (no duplicate)
New request: client_request_id="xyz789-uuid-request" → Creates new order with different ID
```
#### When Omitting client_request_id
If you do not provide `client_request_id` (or pass an empty value), the request will still succeed and create an order normally. However, **idempotency protection will be skipped**, meaning:
- Each request (even identical ones) will create a separate order
- Network retries or accidental duplicate requests may result in duplicate orders
- No server-side caching of the request will be performed
It is strongly recommended to always provide a unique `client_request_id` for critical order submissions to prevent unintended duplicates.
### Request Example
```python
from decimal import Decimal
from longbridge.openapi import TradeContext, Config, OrderType, OrderSide, TimeInForceType, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
# Create a context for trade APIs
ctx = TradeContext(config)
# Submit order
resp = ctx.submit_order("700.HK", OrderType.LO, OrderSide.Buy, Decimal(500), TimeInForceType.Day, submitted_price=Decimal(50), remark="Hello from Python SDK")
print(resp)
```
```python
import asyncio
from decimal import Decimal
from longbridge.openapi import AsyncTradeContext, Config, OrderType, OrderSide, TimeInForceType, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
# Create a context for trade APIs
ctx = AsyncTradeContext.create(config)
# Submit order
resp = await ctx.submit_order("700.HK", OrderType.LO, OrderSide.Buy, Decimal(500), TimeInForceType.Day, submitted_price=Decimal(50), remark="Hello from Python SDK")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, TradeContext, OAuth, OrderType, OrderSide, TimeInForceType, Decimal } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = TradeContext.new(config)
const resp = await ctx.submitOrder({
symbol: '700.HK',
orderType: OrderType.LO,
side: OrderSide.Buy,
submittedQuantity: new Decimal(500),
timeInForce: TimeInForceType.Day,
submittedPrice: new Decimal(50),
remark: 'Hello',
})
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.trade.*;
import java.math.BigDecimal;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
TradeContext ctx = TradeContext.create(config)) {
SubmitOrderResponse resp = ctx.submitOrder(new SubmitOrderOptions("700.HK", OrderType.LO, OrderSide.Buy, new BigDecimal("500"), TimeInForceType.Day).setSubmittedPrice(new BigDecimal("50")).setRemark("Hello")).get();
System.out.println(resp.orderId);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, trade::{TradeContext, SubmitOrderOptions, OrderType, OrderSide, TimeInForceType}, Config};
use rust_decimal::Decimal;
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = TradeContext::new(config);
let resp = ctx.submit_order(
SubmitOrderOptions::new("700.HK", OrderType::LO, OrderSide::Buy, Decimal::from(500), TimeInForceType::Day)
.submitted_price(Decimal::from(50))
.remark("Hello")
).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::trade;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
TradeContext ctx = TradeContext::create(config);
SubmitOrderOptions opts{"700.HK", OrderType::LO, OrderSide::Buy, 200, TimeInForceType::Day, Decimal(50.0), std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt, std::nullopt};
ctx.submit_order(opts, [](auto res) {
if (!res) { std::cout << "failed" << std::endl; return; }
std::cout << "order_id: " << res->order_id << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/trade"
"github.com/shopspring/decimal"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
tctx, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer tctx.Close()
orderID, err := tctx.SubmitOrder(context.Background(), &trade.SubmitOrder{
Symbol: "700.HK",
OrderType: trade.OrderTypeLO,
Side: trade.OrderSideBuy,
SubmittedQuantity: 500,
SubmittedPrice: decimal.NewFromFloat(50),
TimeInForce: trade.TimeTypeDay,
Remark: "Hello from Go SDK",
})
if err != nil {
log.Fatal(err)
}
fmt.Println("order_id:", orderID)
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"order_id": 683615454870679600
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ------------------------------------------------------------- | ------ |
| 200 | The submission was successful and the order was commissioned. | None |
| 400 | The submit was rejected with an incorrect request parameter. | None |
---
# Submit Multi-leg Order
URL: https://open.longbridge.com/docs/trade/order/submit_multileg.md
This API is used to submit a multi-leg option combination order (such as vertical spreads, straddles, strangles, collars, etc.). All legs are submitted together as a single strategy order.
## Request
HTTP Method POST
HTTP URL /v1/trade/order/multileg
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| ------------------ | -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| side | string | YES | Order Side
**Enum Value:**
`Buy`
`Sell` |
| order_type | string | YES | [Order Type](../trade-definition#ordertype) |
| submitted_price | string | NO | Submitted price, example: `1.5`
Required for limit order types such as `LO` |
| submitted_quantity | string | YES | Submitted quantity (number of combinations), example: `1` |
| strategy | string | YES | Multi-leg strategy
**Enum Value:**
`CoveredCall` - Covered stock
`CoveredPut` - Covered stock
`VerticalCallSpread` - Vertical spread
`VerticalPutSpread` - Vertical spread
`Collar` - Collar
`Straddle` - Straddle
`Strangle` - Strangle
`CalendarCallSpread` - Calendar
`CalendarPutSpread` - Calendar |
| legs | object[] | YES | Legs of the combination order |
| ∟ symbol | string | YES | Option symbol, use `ticker.region` format, example: `QQQ260731C764000.US` |
| ∟ ratio_quantity | string | YES | Leg ratio quantity, example: `1` |
| remark | string | NO | Remark (Maximum 255 characters) |
| client_request_id | string | NO | Client request ID, used for idempotency (Maximum 64 characters) |
### Request Example
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"order_id": "683615454870679600"
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ------------------------------------------------------------- | ------ |
| 200 | The submission was successful and the order was commissioned. | None |
| 400 | The submit was rejected with an incorrect request parameter. | None |
---
# Today Orders
URL: https://open.longbridge.com/docs/trade/order/today_orders.md
This API is used to get today order or get order by order id.
longbridge order
## Request
HTTP Method GET
HTTP URL /v1/trade/order/today
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| -------- | -------- | -------- | --------------------------------------------------------------------------------------------------------- |
| symbol | string | NO | Stock symbol, use `ticker.region` format, example: `AAPL.US` |
| status | string[] | NO | [Order status](../trade-definition#orderstatus)
example: `status=FilledStatus&status=NewStatus` |
| side | string | NO | Order side
**Enum Value:**
`Buy`
`Sell` |
| market | string | NO | Market
**Enum Value:**
`US` - United States of America Market
`HK` - Hong Kong Market |
| order_id | string | NO | Order ID, example: `701276261045858304` |
| is_attached | bool | NO | Whether `order_id` refers to an attached order, returns the attached order information if `true` |
### Request Example
```python
from longbridge.openapi import TradeContext, Config, OrderStatus, OrderSide, Market, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
resp = ctx.today_orders(
symbol = "700.HK",
status = [OrderStatus.Filled, OrderStatus.New],
side = OrderSide.Buy,
market = Market.HK,
)
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncTradeContext, Config, OrderStatus, OrderSide, Market, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
resp = await ctx.today_orders(
symbol = "700.HK",
status = [OrderStatus.Filled, OrderStatus.New],
side = OrderSide.Buy,
market = Market.HK,
)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, TradeContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = TradeContext.new(config)
const resp = await ctx.todayOrders({})
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.trade.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
TradeContext ctx = TradeContext.create(config)) {
Order[] resp = ctx.getTodayOrders(null).get();
for (Order o : resp) System.out.println(o);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, trade::TradeContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = TradeContext::new(config);
let resp = ctx.today_orders(None).await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::trade;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
TradeContext ctx = TradeContext::create(config);
ctx.today_orders(std::nullopt, [](auto res) {
if (!res) { std::cout << "failed" << std::endl; return; }
for (const auto& o : *res) std::cout << o.order_id << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/trade"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
tctx, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer tctx.Close()
orders, err := tctx.TodayOrders(context.Background(), &trade.GetTodayOrders{})
if err != nil {
log.Fatal(err)
}
for _, o := range orders {
fmt.Println(o.OrderId)
}
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"orders": [
{
"currency": "HKD",
"executed_price": "0.000",
"executed_quantity": "0",
"expire_date": "",
"last_done": "",
"limit_offset": "",
"msg": "",
"order_id": "706388312699592704",
"order_type": "ELO",
"outside_rth": "UnknownOutsideRth",
"price": "11.900",
"quantity": "200",
"side": "Buy",
"status": "RejectedStatus",
"stock_name": "Bank of East Asia Ltd/The",
"submitted_at": "1651644897",
"symbol": "23.HK",
"tag": "Normal",
"time_in_force": "Day",
"trailing_amount": "",
"trailing_percent": "",
"trigger_at": "0",
"trigger_price": "",
"trigger_status": "NOT_USED",
"updated_at": "1651644898",
"remark": "",
"limit_depth_level": 0,
"monitor_price": "",
"trigger_count": 1,
"attached_orders": [
{
"order_id": "706388312699592705",
"attached_type_display": 2,
"trigger_price": "10.500",
"quantity": "200",
"executed_qty": "0",
"status": "NewStatus",
"updated_at": "1651644898",
"withdrawn": false,
"gtd": "",
"time_in_force": "Day",
"counter_id": "",
"trigger_status": 0,
"executed_amount": "0",
"tag": 0,
"submitted_at": "1651644897",
"executed_price": "0.000",
"force_only_rth": "RTH_ONLY",
"reviewed": false,
"activate_order_type": "MIT",
"activate_rth": "RTH_ONLY",
"submit_price": "",
"limit_depth_level": 0
}
],
"multi_leg": {
"strategy": "2",
"strategy_name": "Vertical spread",
"multileg_id": "Spread_QQQ20260731C764/767",
"code": "QQQ 260731 764/767 Vertical spread",
"legs": [
{
"symbol": "QQQ260731C764000.US",
"side": "Buy",
"position": "LONG",
"ratio_quantity": "1",
"strike_price": "764",
"expire_date": "20260731",
"contract_direction": "C"
},
{
"symbol": "QQQ260731C767000.US",
"side": "Sell",
"position": "SHORT",
"ratio_quantity": "1",
"strike_price": "767",
"expire_date": "20260731",
"contract_direction": "C"
}
]
}
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | -------------------------------------------------------- | ------------------------------------------- |
| 200 | Get Today Orders Success | [today_orders_rsp](#schematoday_orders_rsp) |
| 400 | The query failed with an error in the request parameter. | None |
## Schemas
### today_orders_rsp
| Name | Type | Required | Description |
| ------------------- | -------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| orders | object[] | false | Order Detail |
| ∟ order_id | string | true | Order ID |
| ∟ status | string | true | [Order Status](../trade-definition#orderstatus) |
| ∟ stock_name | string | true | Stock Name |
| ∟ quantity | string | true | Submitted Quantity |
| ∟ executed_quantity | string | true | Executed Quantity.
when the order is not filled, value is 0 |
| ∟ price | string | true | Submitted Price.
when market condition order is not triggered, value is empty string |
| ∟ executed_price | string | true | Executed Price.
when the order is not filled, value is 0 |
| ∟ submitted_at | string | true | Submitted Time |
| ∟ side | string | true | Order Side
**Enum Value:**
`Buy`
`Sell` |
| ∟ symbol | string | true | Stock symbol, use `ticker.region` format, example: `AAPL.US` |
| ∟ order_type | string | true | [Order Type](../trade-definition#ordertype) |
| ∟ last_done | string | true | Last done.
when the order is not filled, value is empty string |
| ∟ trigger_price | string | true | `LIT` / `MIT` Order Trigger Price.
When the order is not `LIT` / `MIT` order, value is empty string |
| ∟ msg | string | true | Rejected message or remark, default value is empty string. |
| ∟ tag | string | true | Order tag
**Enum Value**
`Normal` - Normal Order
`Gtc` - Long term Order
`Grey` - Grey Order |
| ∟ time_in_force | string | true | Time in force Type
**Enum Value:**
`Day` - Day Order
`GTC` - Good Til Canceled Order
`GTD` - Good Til Date Order |
| ∟ expire_date | string | true | Long term order expire date, format: `YYYY-MM-DD`, example: `2022-12-05`.
When not a long term order, default value is empty string |
| ∟ updated_at | string | true | Last updated time, formatted as a timestamp (second) |
| ∟ trigger_at | string | true | Conditional order trigger time. formatted as a timestamp (second) |
| ∟ trailing_amount | string | true | `TSLPAMT` order trailing amount.
When the order is not `TSLPAMT` order, value is empty string |
| ∟ trailing_percent | string | true | `TSLPPCT` order trailing percent.
When the order is not `TSLPPCT` order, value is empty string |
| ∟ limit_offset | string | true | `TSLPAMT` / `TSLPPCT` order limit offset amount.
When the order is not `TSLPAMT` / `TSLPPCT` order, value is empty string |
| ∟ trigger_status | string | true | Conditional Order Trigger Status
When an order is not a conditional order or a conditional order is not triggered, the trigger status is NOT_USED
**Enum Value**
`NOT_USED`
`DEACTIVE`
`ACTIVE`
`RELEASED` |
| ∟ currency | string | true | Currency |
| ∟ outside_rth | string | true | Enable or disable outside regular trading hours
Default is `UnknownOutsideRth` when the order is not a US stock
**Enum Value:**
`RTH_ONLY` - Regular trading hour only
`ANY_TIME` - Any time
`OVERNIGHT` - Overnight" |
| ∟ remark | string | true | Remark |
| ∟ limit_depth_level | int32 | true | Specifies the bid/ask depth level |
| ∟ monitor_price | string | true | Monitoring price |
| ∟ trigger_count | int32 | true | Number of triggers |
| ∟ attached_orders | object[] | false | List of attached order details |
| ∟∟ order_id | string | true | Attached order ID |
| ∟∟ attached_type_display | int32 | true | Attached order type.
**Enum Value:**
`1` - Take Profit
`2` - Stop Loss |
| ∟∟ trigger_price | string | true | Trigger price |
| ∟∟ quantity | string | true | Order quantity |
| ∟∟ executed_qty | string | true | Executed quantity |
| ∟∟ status | string | true | Order status |
| ∟∟ updated_at | string | true | Last updated time, formatted as a timestamp (second) |
| ∟∟ withdrawn | boolean | true | Whether the order has been withdrawn |
| ∟∟ gtd | string | true | GTD expiration date, format: `YYYY-MM-DD` |
| ∟∟ time_in_force | string | true | Time in force Type
**Enum Value:**
`Day` - Day Order
`GTC` - Good Til Canceled Order
`GTD` - Good Til Date Order |
| ∟∟ counter_id | string | true | Counter order ID |
| ∟∟ trigger_status | int32 | true | Conditional order trigger status after the attached order is activated.
`0` - Not activated
`1` - Monitoring
`2` - Cancelled
`4` - Triggered |
| ∟∟ executed_amount | string | true | Executed amount |
| ∟∟ tag | int32 | true | Order tag |
| ∟∟ submitted_at | string | true | Submitted time, formatted as a timestamp (second) |
| ∟∟ executed_price | string | true | Executed price |
| ∟∟ force_only_rth | string | true | Whether execution is restricted to regular trading hours only |
| ∟∟ reviewed | boolean | true | Whether the order has been reviewed |
| ∟∟ activate_order_type | string | true | Order type submitted after triggering, e.g. `LIT` (limit-if-touched) or `MIT` (market-if-touched) |
| ∟∟ activate_rth | string | true | Whether the order submitted after triggering allows pre/post market trading |
| ∟∟ submit_price | string | true | Submitted price |
| ∟∟ limit_depth_level | int32 | true | Specifies the bid/ask depth level |
| ∟ multi_leg | object | false | Multi-leg strategy information. Only returned for multi-leg option combination orders; otherwise not returned. |
| ∟∟ strategy | string | false | Multi-leg strategy
**Enum Value:**
`0` - CoveredCall (Covered stock)
`1` - CoveredPut (Covered stock)
`2` - VerticalCallSpread (Vertical spread)
`3` - VerticalPutSpread (Vertical spread)
`4` - Collar
`5` - Straddle
`6` - Strangle
`7` - CalendarCallSpread (Calendar)
`8` - CalendarPutSpread (Calendar) |
| ∟∟ strategy_name | string | false | Strategy name |
| ∟∟ multileg_id | string | false | Multi-leg combination ID |
| ∟∟ code | string | false | Multi-leg combination code |
| ∟∟ legs | object[] | false | Legs of the combination order |
| ∟∟∟ symbol | string | false | Option symbol, use `ticker.region` format, example: `QQQ260731C764000.US` |
| ∟∟∟ side | string | false | Order Side
**Enum Value:**
`Buy`
`Sell` |
| ∟∟∟ position | string | false | Position direction
**Enum Value:**
`LONG`
`SHORT` |
| ∟∟∟ ratio_quantity | string | false | Leg ratio quantity |
| ∟∟∟ strike_price | string | false | Strike price |
| ∟∟∟ expire_date | string | false | Option expiry date, format: `YYYYMMDD` |
| ∟∟∟ contract_direction | string | false | Contract type
**Enum Value:**
`C` - Call
`P` - Put |
---
# Cancel Order
URL: https://open.longbridge.com/docs/trade/order/withdraw.md
This API is used to withdraw an open order.
# Replace the order ID below with your actual order ID
longbridge order cancel 693664675163312128
## Request
HTTP Method DELETE
HTTP URL /v1/trade/order
### Parameters
> Content-Type: application/json; charset=utf-8
| Name | Type | Required | Description |
| -------- | ------ | -------- | ----------- |
| order_id | string | YES | Order ID |
| is_attached | bool | NO | Whether `order_id` refers to an attached order |
### Request Example
```python
from longbridge.openapi import TradeContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = TradeContext(config)
ctx.cancel_order("709043056541253632")
```
```python
import asyncio
from longbridge.openapi import AsyncTradeContext, Config, OAuthBuilder
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncTradeContext.create(config)
ctx.cancel_order("709043056541253632")
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, TradeContext, OAuth } = require('longbridge')
async function main() {
const oauth = await OAuth.build('your-client-id', (_, url) => {
console.log('Open this URL to authorize: ' + url)
})
const config = Config.fromOAuth(oauth)
const ctx = TradeContext.new(config)
await ctx.cancelOrder('701276261045858304')
console.log('cancelled')
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.trade.*;
class Main {
public static void main(String[] args) throws Exception {
try (OAuth oauth = new OAuthBuilder("your-client-id").build(url -> System.out.println("Open to authorize: " + url)).get();
Config config = Config.fromOAuth(oauth);
TradeContext ctx = TradeContext.create(config)) {
ctx.cancelOrder("701276261045858304").get();
System.out.println("cancelled");
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, trade::TradeContext, Config};
#[tokio::main]
async fn main() -> Result<(), Box> {
let oauth = OAuthBuilder::new("your-client-id").build(|url| println!("Open this URL to authorize: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let (ctx, _) = TradeContext::new(config);
ctx.cancel_order("701276261045858304").await?;
println!("cancelled");
Ok(())
}
```
```cpp
#include
#include
#ifdef WIN32
#include
#endif
using namespace longbridge;
using namespace longbridge::trade;
static void
run(const OAuth& oauth)
{
Config config = Config::from_oauth(oauth);
TradeContext ctx = TradeContext::create(config);
ctx.cancel_order("701276261045858304", [](auto res) {
if (!res) { std::cout << "failed" << std::endl; return; }
std::cout << "cancelled" << std::endl;
});
}
int main(int argc, char const* argv[]) {
#ifdef WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
const std::string client_id = "your-client-id";
OAuthBuilder(client_id).build(
[](const std::string& url) {
std::cout << "Open this URL to authorize: " << url << std::endl;
},
[](auto res) {
if (!res) {
std::cout << "authorization failed: " << *res.status().message() << std::endl;
return;
}
run(*res);
});
std::cin.get();
return 0;
}
```
```go
package main
import (
"context"
"fmt"
"log"
"github.com/longbridge/openapi-go/config"
"github.com/longbridge/openapi-go/oauth"
"github.com/longbridge/openapi-go/trade"
)
func main() {
o := oauth.New("your-client-id").
OnOpenURL(func(url string) { fmt.Println("Open this URL to authorize:", url) })
if err := o.Build(context.Background()); err != nil {
log.Fatal(err)
}
conf, err := config.New(config.WithOAuthClient(o))
if err != nil {
log.Fatal(err)
}
tctx, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer tctx.Close()
err = tctx.WithdrawOrder(context.Background(), "701276261045858304")
if err != nil {
log.Fatal(err)
}
fmt.Println("cancelled")
}
```
## Response
### Response Headers
- Content-Type: application/json
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ---------------------------------------------------------------- | ------ |
| 200 | The submission was successful and the order was commissioned. | None |
| 400 | The withdrawal was rejected with an incorrect request parameter. | None |
---
# Overview
URL: https://open.longbridge.com/docs/trade/trade-overview.md
# Trade Overview
:::info
Cmd: `16`
:::
Protobuf definition:
```protobuf
// Sub is Sub command content, command is 16
message Sub {
repeated string topics = 1;
}
// SubResponse is response of Sub Request
message SubResponse {
message Fail {
string topic = 1;
string reason = 2;
}
repeated string success = 1; // success topics
repeated Fail fail = 2; // failed topics
repeated string current = 3; // curent subscriptions after subscribe
}
```
Current support topics:
- private - private notification for trade
## Cancel Subscribe
:::info
Cmd: `17`
:::
Protobuf defination:
```protobuf
// Unsub is Unsub command content, command is 17
message Unsub {
repeated string topics = 1;
}
// UnsubResponse is response of Unsub request
message UnsubResponse {
repeated string current = 3; // current subscriptions after cancel subscribe
}
```
## Push Notification
After we `subscribe` to the trade gateway, we can get real-time trade updates from the trade gateway. The trade gateway will push the corresponding push message to the client. The SDK's `set_on_order_changed` (In Go is: `OnTrade`) can set the callback function of the push message. When the client receives the trade push message, the callback function will be called.
:::info
Cmd: `18`
:::
Protobuf defination:
```protobuf
// Dispatch type
enum DispatchType {
DISPATCH_UNDEFINED = 0;
DISPATCH_DIRECT = 1;
DISPATCH_BROADCAST = 2;
}
enum ContentType {
CONTENT_UNDEFINED = 0;
CONTENT_JSON = 1;
CONTENT_PROTO = 2;
}
// Notification is push message, command is 18
message Notification {
string topic = 1;
ContentType content_type = 2;
DispatchType dispatch_type = 3;
bytes data = 4;
}
```
## Grid Order Changes
Grid trading master-order changes are delivered on the **same `private` topic** as regular order changes. After you `subscribe` to the private topic, the trade gateway pushes a `gridtrading_order` event whenever a grid master order changes (created, suspended, restarted, triggered, or canceled). Set the grid order changed callback to receive them.
The event carries the following fields:
| Name | Type | Description |
| ---- | ---- | ---- |
| order_id | string | Grid master order ID |
| status | string | Order status |
| symbol | string | Security symbol (e.g. `700.HK`) |
| suspend_reason | string | Suspend reason, if any |
| submitted_base_price | string | Submitted base price |
| current_base_price | string | Current base price |
| upper_limit_price | string | Upper price bound |
| lower_limit_price | string | Lower price bound |
| trigger_price_type | int32 | `1` = spread, `2` = percent |
| trigger_quantity | string | Quantity per trigger |
| settlement_currency | string | Settlement currency |
| time_in_force | int32 | `0` = Day, `1` = GTC, `6` = GTD |
| rth | int32 | Regular-trading-hours flag |
| grid_order_type_up | string | Sell-side order type when depth is 0 |
| grid_order_type_down | string | Buy-side order type when depth is 0 |
---
# Pricing
URL: https://open.longbridge.com/pricing.md
---
# SDK
URL: https://open.longbridge.com/sdk.md
:::warning Package Renamed
The SDK package has been renamed from `longport` to `longbridge`. The old `longport` package is deprecated. If you were previously using `longport`, please uninstall it before installing the new package.
:::
## Longbridge OpenAPI SDK for Python
[https://github.com/longbridge/openapi/tree/master/python](https://github.com/longbridge/openapi/tree/master/python)
### Install SDK
You can install the SDK via Pip, or directly visit the [PyPI](https://pypi.org/project/longbridge/) page to download.
```bash
$ pip install longbridge
```
> NOTE: In macOS system, the `pip` command default is Python 2. You may use `pip3` for use Python 3 version of PyPI.
### API Documents
- https://longbridge.github.io/openapi/python/index.html
### Examples
- https://github.com/longbridge/openapi/tree/master/examples/python
## Longbridge OpenAPI SDK for Node.js
[https://github.com/longbridge/openapi/tree/master/nodejs](https://github.com/longbridge/openapi/tree/master/nodejs)
### Install SDK
You can install the SDK via Npm.
```bash
$ npm install longbridge --save
```
[https://www.npmjs.com/package/longbridge](https://www.npmjs.com/package/longbridge)
### API Documents
- https://longbridge.github.io/openapi/nodejs/index.html
### Examples
- https://github.com/longbridge/openapi/tree/master/examples/nodejs
## Longbridge OpenAPI SDK for Rust
[https://github.com/longbridge/openapi/tree/master/rust](https://github.com/longbridge/openapi/tree/master/rust)
### Install SDK
Add the following line to your `Cargo.toml` file
```toml
[dependencies]
longbridge = "4.0.5"
```
[https://crates.io/crates/longbridge](https://crates.io/crates/longbridge)
### API Documents
- https://longbridge.github.io/openapi/rust/longbridge/index.html
### Examples
- https://github.com/longbridge/openapi/tree/master/examples/rust
## Longbridge OpenAPI SDK for Java
[https://github.com/longbridge/openapi/tree/master/java](https://github.com/longbridge/openapi/tree/master/java)
### Install SDK
Add the following line to your `pom.xml` file
```xml
io.github.longbridge
openapi-sdk
4.0.5
```
[https://search.maven.org/artifact/io.github.longbridge/openapi](https://search.maven.org/artifact/io.github.longbridge/openapi)
### API Documents
- https://longbridge.github.io/openapi/java/index.html
### Examples
- https://github.com/longbridge/openapi/tree/master/examples/java
## Longbridge OpenAPI SDK for Go
[https://github.com/longbridge/openapi-go](https://github.com/longbridge/openapi-go)
### Install SDK
- Go version >= 1.17
In your project directory, run:
```bash
$ go get github.com/longbridge/openapi-go
```
[https://pkg.go.dev/github.com/longbridge/openapi-go](https://pkg.go.dev/github.com/longbridge/openapi-go)
### Examples
- https://github.com/longbridge/openapi-go/tree/main/examples
## Longbridge OpenAPI SDK for C/C++
[https://github.com/longbridge/openapi/tree/master/cpp](https://github.com/longbridge/openapi/tree/master/cpp)
### Download
- [4.0.5](https://static.lbctrl.com/openapi-sdk/openapi-cpp-sdk-4.0.5.tar.gz)
### API Documents
- https://longbridge.github.io/openapi/cpp/index.html
### Examples
- https://github.com/longbridge/openapi/tree/master/examples/cpp
---
# Skill
URL: https://open.longbridge.com/skill.md
---
# Skill Installation Guide
URL: https://open.longbridge.com/skill/install.md
# Longbridge Skill Installation Guide
Once installed, you can say things like this to your AI assistant and get real answers:
- _"Screen US and HK stocks: market cap above $50B, P/E below 25, recent MACD golden cross — ranked by market cap"_
- _"NVDA just reported — compare actuals vs analyst estimates, break down revenue by segment, and check if valuation is reasonable"_
- _"Set a trailing stop on TSLA: trigger a sell if it drops more than 8%, show me the order details before executing"_
- _"Review my portfolio this month: P&L trend, biggest winner, worst drag, US vs HK allocation"_
- _"Analyze my account and quantify its exposure to AI, semiconductors, and internet-related stocks."_
- _"Based on my 5-year long-term DCA plan, I'm due to buy this month's QQQ and SPY within the next two days. Can you check the recent market conditions and let me know if the timing looks reasonable?"_
---
The quickest way to get started is with a terminal-based AI tool — Claude Code, Codex, opencode, or OpenClaw. Install the CLI, authenticate once, and the AI runs `longbridge` commands on your behalf.
If you'd rather not install local software, connect via MCP instead — just add a URL to your AI tool's config.
Either way, also install the Skill: a set of instruction files that tells your AI what Longbridge can do and how to use it.
---
## Step 1 — Connect to the Longbridge platform
CLI and MCP are both ways to access the Longbridge Developers platform. Pick one:
- **CLI** — best experience; the AI runs `longbridge` commands directly in your terminal; requires installing software on your system
- **MCP** — easier to connect; just add a URL to your AI tool's config; no local install needed
### Method A — CLI (recommended)
Works with Claude Code, Codex (Work locally), opencode, OpenClaw, Gemini CLI, Warp, and any tool that can run shell commands.
**Install the CLI:**
```bash
# macOS (requires Homebrew — install at https://brew.sh if not already installed)
brew install --cask longbridge/tap/longbridge-terminal
# macOS / Linux
curl -sSL https://open.longbridge.com/longbridge/longbridge-terminal/install | sh
```
**Windows** ([Scoop](https://scoop.sh)):
```powershell
scoop install https://open.longbridge.com/longbridge/longbridge-terminal/longbridge.json
```
**Windows** (PowerShell):
```powershell
iwr https://open.longbridge.com/longbridge/longbridge-terminal/install.ps1 | iex
```
**Authenticate:**
```bash
longbridge auth login
```
Already have a one-time authorization code from [open.longbridge.com/connect](https://open.longbridge.com/connect)? Redeem it directly — no browser needed:
```bash
longbridge auth login --auth-code 1234567890
```
That's it. The AI can now call `longbridge` commands on your behalf.
**Claude Code users:** The first time Claude runs a `longbridge` command, it will ask for permission. To allow all Longbridge commands without repeated prompts, add this to `.claude/settings.json` in your project (create the file if it doesn't exist):
```json
{
"permissions": {
"allow": ["Bash(longbridge *)"]
}
}
```
> See the [CLI reference](/docs/cli) for the full command list and installation details.
### Method B — MCP
Works with Claude Desktop, Cursor, Zed, Gemini CLI, Warp, and any tool that supports MCP.
Add the following as a remote MCP server in your AI tool:
```
https://mcp.longbridge.com
```
For clients that use a JSON config file (Claude Desktop, Cursor, Zed, Gemini CLI, etc.), add this to your MCP config:
```json
{
"mcpServers": {
"longbridge": {
"url": "https://mcp.longbridge.com"
}
}
}
```
> Users in mainland China can use the accelerated endpoint: `https://mcp.longbridge.cn`
Where to find the MCP configuration in each client:
| Client | Where to configure |
| -------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| Claude Desktop | Edit `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows) |
| Cursor | Settings → MCP Servers → Add Remote MCP Server |
| Zed | `context_servers` key in `~/.config/zed/settings.json` |
| Gemini CLI | `mcpServers` key in `~/.gemini/settings.json` (use `httpUrl`, not `url`) |
| Warp | Settings → Agents → MCP servers → + Add |
The first time you ask a Longbridge question, your client will open a browser tab for OAuth authorization — no API key required.
---
## Step 2 — Install the Skill
The Skill is a set of instruction files that tell your AI assistant what Longbridge can do.
**Via Claude Code plugin (recommended for Claude Code users):**
In Claude Code, run these two commands:
```text
/plugin marketplace add longbridge/skills
/plugin install longbridge@longbridge-skills
```
This installs all Longbridge skills through the Claude Code plugin system and keeps them up to date automatically.
**Via Codex plugin (recommended for Codex users):**
In Codex, run these two commands:
```text
codex plugin marketplace add longbridge/skills
codex plugin add longbridge@longbridge-skills
```
This installs all Longbridge skills through the Codex plugin system and keeps them up to date automatically.
**Via npx / bunx (global install):**
```bash
# Node.js
npx skills add longbridge/skills -g
# Bun
bunx skills add longbridge/skills -g
```
> Requires [Node.js](https://nodejs.org) or [Bun](https://bun.sh).
**Or download the ZIP and install manually:**
Download [longbridge-all.zip](https://open.longbridge.com/skill/longbridge-all.zip) and unzip it, then place the files in your AI tool's Skill directory (Claude Code: `.claude/skills/`, Cursor: paste into the Rules editor, other tools: see the README).
**OpenClaw** — send this message in chat and it handles everything automatically:
```
Install the Longbridge Developers Skill from this zip file:
https://open.longbridge.com/skill/longbridge-all.zip
```
---
## Known restrictions by tool
Some environments have network whitelists or sandboxing that block CLI installation and MCP server connections. If things aren't working, check here first.
### Claude Desktop — use the Code tab
**Chat and Cowork modes** in Claude Desktop have network restrictions that prevent CLI installation and MCP server connections. Do not try to install from either of these modes — it will not work no matter how many times you retry.
Switch to the **Code** tab in Claude Desktop (this is Claude Code embedded in the app). From the Code tab, you have full terminal access — you can install the CLI, connect MCP, and install the Skill all in one session.
### Codex — select "Work locally"
Codex in **Cloud** mode has the same network whitelist restrictions. When starting a new session, select **Work locally** instead of Cloud. This gives the agent full access to your shell and network.
### Claude.ai and ChatGPT.com (web)
Browser-based interfaces have no access to your local system. They cannot run shell commands or connect to external MCP servers.
For Claude, use [Claude Desktop](https://claude.ai/download) and switch to the **Code** tab.
---
## Verify installation
After installing, ask your AI assistant:
```
Use Longbridge to get the current quote for AAPL
```
If it returns live data, you're all set.
> **Tip:** If the Skill isn't triggered automatically, prefix your request with `/longbridge` to force it — for example: `/longbridge get the current quote for AAPL`.
---
## Troubleshooting
**AI says it can't find the Longbridge tool**
Some clients require a restart or a new conversation to load the Skill. Confirm the installation is complete, then try again in a new session.
**Prompted for authorization when querying data**
Run `longbridge auth login` in your terminal and complete the OAuth flow.
**Trading operations not working**
Confirm your account has OpenAPI trading permissions enabled and is eligible to trade in the target market (HK / US).
**Revoking Authorization**
To remove the authorization, go to your Longbridge account → Security Settings → manage authorized apps; it can then no longer be renewed, but tokens already issued remain valid until they expire. To sign out on this machine, run `longbridge auth logout` (see [Sign Out](/docs/getting-started#oauth-signout)).
---
URL: https://open.longbridge.com/docs/api.md
# Longbridge OpenAPI Reference
Machine-readable reference for all REST and WebSocket endpoints.
## Overview
This page is reorganized as a practical **OAuth 2.0 access flow** for new integrations.
> **Tip:** Prefer using SDKs for faster integration: https://open.longbridge.com/sdk
## Notes
| Precautions | Reference |
| -------------------------------------------- | --------------------------------------------------------------------- |
| Prefer SDKs over raw HTTP when possible | [SDK Quick Start](/docs/getting-started) |
| Enable required OpenAPI services first | [How to enable OpenAPI](/docs/#how-to-enable-openapi) |
| Understand permissions and restrictions | [Permissions and restrictions](/docs/#permissions-and-restrictions) |
| Check common error codes for troubleshooting | [Error Codes](/docs/api?page=error-codes) |
## OAuth 2.0 (Default)
For new integrations, OAuth 2.0 is the default path.
API-key signature mode can remain as a fallback for legacy compatibility, but it is not the default.
### Discovery endpoints
- Production: `https://openapi.longbridge.com/.well-known/oauth-authorization-server`
- China: `https://openapi.longbridge.cn/.well-known/oauth-authorization-server`
Supported grant types (from discovery):
- `authorization_code`
- `refresh_token`
## OAuth 2.0 authorization flow
### Register OAuth client
If there is no UI for client creation in your environment, register dynamically:
```shell
curl -X POST https://openapi.longbridge.com/oauth2/register \
-H "Content-Type: application/json" \
-d '{
"client_name": "my-openapi-app",
"redirect_uris": ["https://your-app.com/callback"],
"grant_types": ["authorization_code", "refresh_token"],
"response_types": ["code"]
}'
```
> Registration may return only `client_id` (public client, no `client_secret`). In this case, use PKCE and do not send `client_secret` in token requests.
### Build authorization URL and get `code`
```text
https://openapi.longbridge.com/oauth2/authorize
?response_type=code
&client_id=YOUR_CLIENT_ID
&redirect_uri=YOUR_REDIRECT_URI
&scope=3
&state=YOUR_RANDOM_STATE
&code_challenge=YOUR_CODE_CHALLENGE
&code_challenge_method=S256
```
After user consent, callback receives:
```text
YOUR_REDIRECT_URI?code=AUTH_CODE&state=YOUR_RANDOM_STATE
```
### Exchange `code` for `access_token`
```shell
curl -X POST https://openapi.longbridge.com/oauth2/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=authorization_code" \
-d "client_id=YOUR_CLIENT_ID" \
-d "redirect_uri=YOUR_REDIRECT_URI" \
-d "code=AUTH_CODE" \
-d "code_verifier=YOUR_CODE_VERIFIER"
# only when your client has secret:
# -d "client_secret=YOUR_CLIENT_SECRET"
```
### Call API with Bearer token (TSLA.US example)
```shell
curl -X GET "https://openapi.longbridge.com/v1/quote/get_security_list?market=US&category=Overnight" \
-H "Authorization: Bearer ACCESS_TOKEN"
```
Real response (excerpt, keeping `TSLA.US` row):
```json
{
"code": 0,
"message": "success",
"data": {
"list": [
{
"symbol": "TSLA.US",
"name_cn": "特斯拉",
"name_hk": "",
"name_en": ""
}
]
}
}
```
### Refresh token
Use OAuth token endpoint for refresh (details in Refresh Token section below):
```bash
curl -X POST https://openapi.longbridge.com/oauth2/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=refresh_token" \
-d "client_id=YOUR_CLIENT_ID" \
-d "refresh_token=REFRESH_TOKEN"
# only when your client has secret:
# -d "client_secret=YOUR_CLIENT_SECRET"
```
## Relationship with legacy docs
- This page: OAuth 2.0 main flow for new integrations.
- Refresh Token section below: refresh step details only, to avoid duplication.
---
# Refresh Token (OAuth 2.0)
This page focuses only on the OAuth 2.0 **refresh token** step.
- If you have not completed the full flow yet, read the Authentication section above first.
- This page does not repeat client registration / authorization code steps.
## Recommended refresh method (OAuth 2.0)
Use OAuth token endpoint:
- `POST https://openapi.longbridge.com/oauth2/token`
- or China: `POST https://openapi.longbridge.cn/oauth2/token`
### Request parameters (`application/x-www-form-urlencoded`)
| Name | Required | Description |
| --- | --- | --- |
| grant_type | Yes | Must be `refresh_token` |
| client_id | Yes | OAuth client id |
| refresh_token | Yes | Previously issued refresh token |
| client_secret | Optional | Required only for confidential clients; omit for public clients |
### Refresh example
```bash
curl -X POST https://openapi.longbridge.com/oauth2/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=refresh_token" \
-d "client_id=YOUR_CLIENT_ID" \
-d "refresh_token=YOUR_REFRESH_TOKEN"
# only when your client has secret:
# -d "client_secret=YOUR_CLIENT_SECRET"
```
### Response example
```json
{
"access_token": "...",
"refresh_token": "...",
"expires_in": 2592000,
"token_type": "Bearer"
}
```
## Compatibility note
Legacy `/v1/token/refresh` remains for backward compatibility.
For new integrations, use OAuth 2.0 token endpoint as default.
## Authentication
Longbridge OpenAPI authenticates every HTTP request with three credentials plus an
HMAC-SHA256 signature.
## Credentials
| Credential | Description | Where to get it |
| ---------- | ----------- | --------------- |
| **App Key** | Public application identifier. Sent as the `X-Api-Key` header. | [OpenAPI console](https://open.longbridge.com/account) |
| **App Secret** | Private key used only to compute the request signature. **Never sent over the wire.** | OpenAPI console |
| **Access Token** | Per-user token. Sent as the `Authorization` header. | OpenAPI console (or the token-refresh API) |
> Prefer an SDK: the Rust/Python/Node.js/Java/C++/Go SDKs compute the signature for you
> from these three values. The raw-HTTP examples below are for building a client by hand.
## Request headers
Every request carries these headers:
| Header | Value |
| ------ | ----- |
| `Authorization` | `` (the access token, not a Bearer token) |
| `X-Api-Key` | `` |
| `X-Timestamp` | Current unix time in **seconds** |
| `X-Api-Signature` | `HMAC-SHA256 SignedHeaders=authorization;x-api-key;x-timestamp, Signature=` |
## Computing `X-Api-Signature`
1. Build the signed-headers string:
```text
authorization:
x-api-key:
x-timestamp:
```
2. Build the string to sign (`|`-separated), where `sha1(...)` is a lowercase hex SHA-1
digest and the trailing body hash is present only when there is a request body:
```text
{METHOD}|{PATH}|{QUERY}|{signed_values}|authorization;x-api-key;x-timestamp|{sha1(body)}
```
3. Sign it:
```text
payload = "HMAC-SHA256|" + sha1(string_to_sign)
signature = hex( HMAC_SHA256(payload, App Secret) )
```
4. Send `X-Api-Signature: HMAC-SHA256 SignedHeaders=authorization;x-api-key;x-timestamp, Signature={signature}`.
### Reference signing implementation
Compute the four API-Key headers from your credentials. Other languages follow the same steps.
> The per-endpoint **Request Example** tabs default to **OAuth 2.0** (`Authorization: Bearer `).
> To use API-Key auth instead, drop the `Authorization: Bearer …` header and add the four signed
> headers returned by `sign(...)` above.
## Real-Time Market Data
> **Note:** Real-time market data is **not** part of this HTTP REST API. Quotes, depth, broker queues and trade ticks are delivered over a persistent **WebSocket / TCP** connection to a dedicated gateway. This page documents that protocol end-to-end — you do not need to leave it.
## Overview
The HTTP REST API on this site covers trading, account management and historical/snapshot queries. Real-time streaming is a separate, connection-oriented protocol:
| Data | Access |
|------|--------|
| Orders, account, watchlist, snapshots | HTTP REST (this reference) |
| Real-time quote / depth / brokers / trades | WebSocket or TCP gateway |
> The official SDKs (Rust/Python/Node.js/Java/C++/Go) implement this whole protocol — connect, auth, heartbeat, subscribe and decode — for you: https://open.longbridge.com/sdk . The reference below is for building a client by hand.
## Gateway hosts
| Feed | Region | WebSocket | TCP |
|------|--------|-----------|-----|
| Quote | Global | `wss://openapi-quote.longbridge.com` | `openapi-quote.longbridge.com:2020` |
| Quote | Mainland China | `wss://openapi-quote.longbridge.cn` | `openapi-quote.longbridge.cn:2020` |
| Trade | Global | `wss://openapi-trade.longbridge.com` | `openapi-trade.longbridge.com:2020` |
| Trade | Mainland China | `wss://openapi-trade.longbridge.cn` | `openapi-trade.longbridge.cn:2020` |
Payloads are Protobuf and integers are **big-endian**. The TCP port is `2020` for every host.
## 1. Get a connection OTP
A socket connection authenticates with a one-time password (OTP) fetched from the REST API:
```
GET /v1/socket/token
Authorization:
```
Response `data`:
| Field | Type | Meaning |
|-------|------|---------|
| `otp` | string | One-time password, used as the auth token below |
| `limit` | int | Max concurrent connections |
| `online` | int | Current online connections |
```json
{ "code": 0, "message": "", "data": { "otp": "xxxxxxxx", "online": 1, "limit": 10 } }
```
The OTP is single-use — it is consumed the moment you auth.
## 2. Handshake
The handshake negotiates three fixed values: protocol `version` = `1`, `codec` = `1` (Protobuf) and `platform` = `9` (OpenAPI).
- **WebSocket** — pass them as query params: `wss://openapi-quote.longbridge.com?version=1&codec=1&platform=9`
- **TCP** — send a 2-byte handshake packing the negotiated values: byte 1 = `codec << 4 | ver`, byte 2 = `reserve << 4 | platform` (so `version` and `platform` sit in the low nibble, matching the `type`-in-low-nibble packet header below). For `ver=1, codec=1, platform=9` that is `0x11 0x09` (`0b00010001 0b00001001`).
## 3. Packet framing
Every packet begins with a 1-byte header. `type` occupies the **low 4 bits**; the flags sit above it:
| Bit(s) | Field | Meaning |
|--------|-------|---------|
| 0–3 | `type` | `1` request · `2` response · `3` push |
| 4 | `verify` | `1` = nonce + signature present |
| 5 | `gzip` | `1` = body is gzip-compressed |
| 6–7 | `reserve` | — |
So a plain request header byte is `0x01` (type 1, no verify/gzip); set bit 4 (`0x10`) for `verify` or bit 5 (`0x20`) for `gzip`.
**Request** (`type=1`): `cmd_code` (1B) · `request_id` (4B uint32, unique per connection) · `timeout` (2B ms, ≤ 60000) · `body_len` (3B) · `body` (protobuf) · then `nonce` (8B) + `signature` (16B) when `verify=1`.
**Response** (`type=2`): `cmd_code` (1B) · `request_id` (4B, matches the request) · `status` (1B) · `body_len` (3B) · `body` · (`nonce` + `signature` when `verify=1`).
**Push** (`type=3`): `cmd_code` (1B) · `body_len` (3B) · `body` · (`nonce` + `signature` when `verify=1`). No `request_id` / `status`.
Response `status`: `0` OK · `1` server timeout (408) · `3` bad request (400) · `5` unauthenticated (401) · `7` server error (500). `body_len` maxes out at 16 MB.
## 4. Control commands
Connection-level `cmd_code`s:
| Code | Command | Purpose |
|------|---------|---------|
| `0` | Close | Server-sent push right before it closes the connection |
| `1` | Heartbeat | Keep-alive; echo the body back (`Heartbeat { int64 timestamp }`) |
| `2` | Auth | First packet after the handshake |
| `3` | Reconnect | Re-auth with a session id, no new OTP required |
**Auth** — send `cmd_code=2` with `AuthRequest { string token = 1 }`, where `token` is the OTP from step 1. The server replies `AuthResponse { string session_id = 1; int64 expires = 2 }`. Keep `session_id` to `Reconnect` (`ReconnectRequest { string session_id }`) without fetching a new OTP.
Close reason codes (`Close.Code`): `0` HeartbeatTimeout · `1` ServerError · `2` ServerShutdown · `3` UnpackError · `4` AuthError · `5` SessExpired · `6` ConnectDuplicate.
Protobuf: https://github.com/longbridge/openapi-protobufs/blob/main/control/control.proto
## Commands
After authenticating, send business commands over the same connection. Every quote pull, subscription, push and trade command — with its cmd code, protobuf request/response, field tables and native call example — is documented under the **WebSocket** groups in the sidebar (**Quote → Pull / Subscription / Push**, **Trade → Notification**).
## Reference implementation
Prefer the SDK: https://open.longbridge.com/sdk . To parse the protocol by hand, see the Go reference implementation: https://github.com/longbridge/openapi-protocol/tree/main/go
## Error Codes
| HTTP Status | Code | Message | Description |
| ----------- | ------ | ---------------------- | ------------------------------------------------------------------ |
| 403 | 403201 | signature invalid | signature is invalid |
| 403 | 403202 | duplicate request | Repeat request, same request without replacement `x-timestamp` |
| 403 | 403203 | apikey illegal | `App Key` is illegal |
| 403 | 403205 | ip is not allowed | IP address is not authorized to access |
| 403 | 403308 | Target API's scope is not in authorized scopes | The OAuth token was not granted the scope this API needs (for example `account.read`, `trade.read` or `trade.write`). Authorize again and grant that scope; see [OAuth Scopes](/docs/getting-started#oauth-scopes). It can also appear when the account has no securities account or trading permission for the market involved. |
| 401 | 401003 | token expired | Access token expired. Legacy API Key: obtain a new token from [https://open.longbridge.com/](https://open.longbridge.com/). OAuth: use the refresh token flow. |
| 429 | 429001 | ip request ratelimit | Too frequent requests as a same IP address, please try again later |
| 429 | 429002 | api request is limited | Too frequent requests on an API, please try again later |
| 500 | 500000 | internal error | server internal error, please contact customer support |
## Quote
### Stocks
#### Query Tradable Securities List
`GET` `/v1/quote/get_security_list`
> **Quote Permission Required · Free**
> Included with OpenAPI activation — no extra purchase needed.
> _OpenAPI quote perms are separate from App/Web perms_
Query the list of tradable securities filtered by market and category. Primarily used to
retrieve securities eligible for extended-hours (pre-market / after-hours) trading sessions.
Both `market` and `category` are required parameters.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `market` | string | Yes | Market code. One of `US`, `HK`. |
| `category` | string | Yes | Security category filter for the target trading session (e.g. `overnight` for US overnight-tradable securities). |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/get_security_list?market=&category=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `list` | object[] | Yes | Matched securities. |
| `└ symbol` | string | Yes | Security symbol, e.g. `AAPL.US`. |
| `└ name_cn` | string | No | Simplified Chinese name. |
| `└ name_hk` | string | No | Traditional Chinese name. |
| `└ name_en` | string | No | English name. |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"list": [
{
"symbol": "AAPL.US",
"name_cn": "苹果",
"name_hk": "蘋果",
"name_en": "Apple Inc."
}
]
}
}
```
#### Static Info
`WS` `request · cmd 10`
> **Quote Permission Required · Free**
> Included with OpenAPI activation — no extra purchase needed.
> _OpenAPI quote perms are separate from App/Web perms_
This API is used to obtain the basic information of securities.
```protobuf
message MultiSecurityRequest {
repeated string symbol = 1;
}
message SecurityStaticInfoResponse {
repeated StaticInfo secu_static_info = 1;
}
```
##### Request Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string[] | Yes | Security code list, in ticker.region format; max 500 symbols per request |
##### Response Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `secu_static_info` | object[] | No | Securities Basic Information |
| `└ symbol` | string | No | Security code |
| `└ name_cn` | string | No | Security name (zh-CN) |
| `└ name_en` | string | No | Security name (en) |
| `└ name_hk` | string | No | Security name (zh-HK) |
| `└ exchange` | string | No | Exchange which the security belongs to |
| `└ currency` | string | No | Trading currency (CNY/USD/SGD/HKD) |
| `└ lot_size` | int32 | No | Lot size |
| `└ total_shares` | int64 | No | Total shares |
| `└ circulating_shares` | int64 | No | Circulating shares |
| `└ hk_shares` | int64 | No | HK shares (only HK stocks) |
| `└ eps` | string | No | Earnings per share |
| `└ eps_ttm` | string | No | Earnings per share (TTM) |
| `└ bps` | string | No | Net assets per share |
| `└ dividend_yield` | string | No | Dividend yield |
| `└ stock_derivatives` | int32[] | No | Types of supported derivatives (1-Option, 2-Warrant) |
| `└ board` | string | No | The board to which the security belongs |
##### Response JSON Example
```json
{
"secu_static_info": [
{
"symbol": "700.HK",
"name_cn": "腾讯控股",
"name_en": "TENCENT",
"exchange": "SEHK",
"currency": "HKD",
"lot_size": 100,
"total_shares": 9612464038,
"eps": "28.4394",
"board": "HKEquity"
}
]
}
```
#### Quotes
`WS` `request · cmd 11`
> **Quote Permission Required · Free**
> US stocks: US LV1 included free by default, covering pre-market, regular, after-hours, and overnight sessions. To receive overnight data, enable it via LONGBRIDGE_ENABLE_OVERNIGHT=true (see Q6 & Q7 in the Broker FAQ).
> HK stocks: LV1 real-time quotes included by default.
> US options: no permission by default — purchase "OPRA US Options Quotes (OpenAPI)" in the Quote Store.
> _OpenAPI quote perms are separate from App/Web perms_
This API is used to obtain the real-time quotes of securities, and supports all types of securities. To view these real-time data streams aggregated into live indices, sector heatmaps, and macro market overviews, you can reference the [Longbridge Global Markets](https://longbridge.com/en/markets).
```protobuf
message MultiSecurityRequest {
repeated string symbol = 1;
}
message SecurityQuoteResponse {
repeated SecurityQuote secu_quote = 1;
}
```
##### Request Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string[] | Yes | Security code list, in ticker.region format; max 500 symbols per request |
##### Response Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `secu_quote` | object[] | No | Securities quote |
| `└ symbol` | string | No | Security code |
| `└ last_done` | string | No | Latest price |
| `└ prev_close` | string | No | Yesterday's close |
| `└ open` | string | No | Open |
| `└ high` | string | No | High |
| `└ low` | string | No | Low |
| `└ timestamp` | int64 | No | Time of latest price |
| `└ volume` | int64 | No | Volume |
| `└ turnover` | string | No | Turnover |
| `└ trade_status` | int32 | No | Security trading status |
| `└ pre_market_quote` | object | No | Quote of US pre market |
| ` └ last_done` | string | No | Latest price |
| ` └ timestamp` | int64 | No | Time of latest price |
| ` └ volume` | int64 | No | Volume |
| ` └ turnover` | string | No | Turnover |
| ` └ high` | string | No | High |
| ` └ low` | string | No | Low |
| ` └ prev_close` | string | No | Close of the last trade session |
| `└ post_market_quote` | object | No | Quote of US post market |
| ` └ last_done` | string | No | Latest price |
| ` └ timestamp` | int64 | No | Time of latest price |
| ` └ volume` | int64 | No | Volume |
| ` └ turnover` | string | No | Turnover |
| ` └ high` | string | No | High |
| ` └ low` | string | No | Low |
| ` └ prev_close` | string | No | Close of the last trade session |
| `└ over_night_quote` | object | No | Quote of US overnight market; requires enable_overnight, returns null otherwise (US stocks only) |
| ` └ last_done` | string | No | Latest price |
| ` └ timestamp` | int64 | No | Time of latest price |
| ` └ volume` | int64 | No | Volume |
| ` └ turnover` | string | No | Turnover |
| ` └ high` | string | No | High |
| ` └ low` | string | No | Low |
| ` └ prev_close` | string | No | Close of the last trade session |
##### Response JSON Example
```json
{
"secu_quote": [
{
"symbol": "700.HK",
"last_done": "338.000",
"prev_close": "334.800",
"open": "340.600",
"high": "340.600",
"low": "333.000",
"timestamp": 1651115955,
"volume": 7310881,
"turnover": "2461463161.000"
}
]
}
```
#### Depth
`WS` `request · cmd 14`
> **Quote Permission Required · Free**
> US stocks: US LV1 1-level bid/ask included free by default (pre-market, regular, after-hours, and overnight sessions).
> HK stocks: LV1 1-level bid/ask included by default; 10-level order book requires "LV2 Advanced Quotes - Plus (OpenAPI)".
> US options: no permission by default — purchase "OPRA US Options Quotes (OpenAPI)".
> _OpenAPI quote perms are separate from App/Web perms_
This API is used to obtain the depth data of security.
```protobuf
message SecurityRequest {
string symbol = 1;
}
message SecurityDepthResponse {
string symbol = 1;
repeated Depth ask = 2;
repeated Depth bid = 3;
}
```
##### Request Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security code, in ticker.region format, e.g. 700.HK |
##### Response Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | No | Security code |
| `ask` | object[] | No | Ask depth |
| `└ position` | int32 | No | Position |
| `└ price` | string | No | Price |
| `└ volume` | int64 | No | Volume |
| `└ order_num` | int64 | No | Number of orders |
| `bid` | object[] | No | Bid depth |
| `└ position` | int32 | No | Position |
| `└ price` | string | No | Price |
| `└ volume` | int64 | No | Volume |
| `└ order_num` | int64 | No | Number of orders |
##### Response JSON Example
```json
{
"symbol": "700.HK",
"ask": [
{
"position": 1,
"price": "335.000",
"volume": 500,
"order_num": 1
}
],
"bid": [
{
"position": 1,
"price": "334.800",
"volume": 69400,
"order_num": 13
}
]
}
```
#### Broker Queue
`WS` `request · cmd 15`
> **Quote Permission Required · HK only · LV2 Advanced**
> HK-specific data: provides the top 40 bid/ask broker queues.
> No permission included by default — purchase "LV2 Advanced Quotes - Plus (OpenAPI)" in the Quote Store.
> _OpenAPI quote perms are separate from App/Web perms_
:::warning Longbridge HK / SG accounts only
This method is available to Longbridge HK / SG accounts only. It works with any supported symbol, including US stocks.
:::
This API is used to obtain the real-time broker queue data of security.
```protobuf
message SecurityRequest {
string symbol = 1;
}
message SecurityBrokersResponse {
string symbol = 1;
repeated Brokers ask_brokers = 2;
repeated Brokers bid_brokers = 3;
}
```
##### Request Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security code, in ticker.region format, e.g. 700.HK |
##### Response Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | No | Security code |
| `ask_brokers` | object[] | No | Ask brokers |
| `└ position` | int32 | No | Position |
| `└ broker_ids` | int32[] | No | Broker IDs, obtained through the Get Broker IDs API |
| `bid_brokers` | object[] | No | Bid brokers |
| `└ position` | int32 | No | Position |
| `└ broker_ids` | int32[] | No | Broker IDs, obtained through the Get Broker IDs API |
##### Response JSON Example
```json
{
"symbol": "700.HK",
"ask_brokers": [
{
"position": 1,
"broker_ids": [
7358,
9057,
9028,
7364
]
}
],
"bid_brokers": [
{
"position": 1,
"broker_ids": [
6996,
5465,
8026,
8304,
4978
]
}
]
}
```
#### Broker IDs
`WS` `request · cmd 16`
This API is used to obtain participant IDs data (which can be synchronized once a day).
```protobuf
message ParticipantBrokerIdsResponse {
repeated ParticipantInfo participant_broker_numbers = 1;
}
message ParticipantInfo {
repeated int32 broker_ids = 1;
string participant_name_cn = 2;
string participant_name_en = 3;
string participant_name_hk = 4;
}
```
##### Response Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `participant_broker_numbers` | object[] | No | participant data |
| `└ broker_ids` | int32[] | No | broker IDs |
| `└ participant_name_cn` | string | No | participant name (zh-CN) |
| `└ participant_name_en` | string | No | participant name (en) |
| `└ participant_name_hk` | string | No | participant name (zh-HK) |
##### Response JSON Example
```json
{
"participant_broker_numbers": [
{
"broker_ids": [
7738,
7739
],
"participant_name_cn": "华兴金融 (香港)",
"participant_name_en": "China Renaissance(HK)",
"participant_name_hk": "華興金融 (香港)"
}
]
}
```
#### Trades
`WS` `request · cmd 17`
> **Quote Permission Required · Free**
> US stocks: US LV1 included free by default (last ~1,000 ticks across pre-market, regular, after-hours, and overnight sessions).
> HK stocks: LV1 included by default (last ~1,000 ticks).
> US options: no permission by default — purchase "OPRA US Options Quotes (OpenAPI)".
> _OpenAPI quote perms are separate from App/Web perms_
This API is used to obtain the trades data of security.
```protobuf
message SecurityTradeRequest {
string symbol = 1;
int32 count = 2;
}
message SecurityTradeResponse {
string symbol = 1;
repeated Trade trades = 2;
}
```
##### Request Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security code, in ticker.region format, e.g. 700.HK |
| `count` | int32 | Yes | Count of trades; max 1000 per request |
##### Response Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | No | Security code |
| `trades` | object[] | No | Trades data |
| `└ price` | string | No | Price |
| `└ volume` | int64 | No | Volume |
| `└ timestamp` | int64 | No | Time of trading |
| `└ trade_type` | string | No | Trade type |
| `└ direction` | int32 | No | Trade direction (0-neutral, 1-down, 2-up) |
| `└ trade_session` | int32 | No | Trade session |
##### Response JSON Example
```json
{
"symbol": "AAPL.US",
"trades": [
{
"price": "158.760",
"volume": 1,
"timestamp": 1651103979,
"trade_type": "I",
"direction": 0,
"trade_session": 2
}
]
}
```
#### Intraday
`WS` `request · cmd 18`
> **Quote Permission Required · Free**
> US stocks: US LV1 included free by default (pre-market, regular, after-hours, and overnight sessions).
> HK stocks: LV1 real-time quotes included by default.
> US options: no permission by default — purchase "OPRA US Options Quotes (OpenAPI)".
> _OpenAPI quote perms are separate from App/Web perms_
This API is used to obtain the intraday data of security.
```protobuf
message SecurityIntradayRequest {
string symbol = 1;
}
message SecurityIntradayResponse {
string symbol = 1;
repeated Line lines = 2;
}
```
##### Request Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security code, in ticker.region format, e.g. 700.HK |
##### Response Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | No | Security code, e.g. AAPL.US |
| `lines` | object[] | No | Intraday line data |
| `└ price` | string | No | Close price of the minute |
| `└ timestamp` | int64 | No | Start time stamp of the minute |
| `└ volume` | int64 | No | Volume |
| `└ turnover` | string | No | Turnover |
| `└ avg_price` | string | No | Average price |
##### Response JSON Example
```json
{
"symbol": "700.HK",
"lines": [
{
"price": "330.400",
"timestamp": 1651023000,
"volume": 375870,
"turnover": "123949699.000",
"avg_price": "329.767470"
}
]
}
```
#### Candlesticks
`WS` `request · cmd 19`
> **Quote Permission Required · Free**
> Quota-based access: 100–3,000 unique symbols per calendar month depending on account tier (resets monthly; see quota table in the docs).
> US stocks: US LV1 included free by default (pre-market, regular, after-hours, and overnight sessions).
> HK stocks: LV1 included by default.
> US options: no permission by default — purchase "OPRA US Options Quotes (OpenAPI)".
> _OpenAPI quote perms are separate from App/Web perms_
This API is used to obtain the candlestick data of security.
```protobuf
message SecurityCandlestickRequest {
string symbol = 1;
Period period = 2;
int32 count = 3;
AdjustType adjust_type = 4;
int32 trade_session = 5;
}
message SecurityCandlestickResponse {
string symbol = 1;
repeated Candlestick candlesticks = 2;
}
```
##### Request Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security code, in ticker.region format, e.g. 700.HK |
| `period` | int32 | Yes | Candlestick period |
| `count` | int32 | Yes | Count of candlestick; max 1000 |
| `adjust_type` | int32 | Yes | Adjustment type |
| `trade_session` | int32 | No | Trading session, 0: intraday, 100: All (pre, intraday, post, overnight) |
##### Response Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | No | Security code, e.g. AAPL.US |
| `candlesticks` | object[] | No | Candlestick data |
| `└ close` | string | No | Close price |
| `└ open` | string | No | Open price |
| `└ low` | string | No | Low price |
| `└ high` | string | No | High price |
| `└ volume` | int64 | No | Volume |
| `└ turnover` | string | No | Turnover |
| `└ timestamp` | int64 | No | Timestamp |
| `└ trade_session` | int32 | No | Trade session |
##### Response JSON Example
```json
{
"symbol": "700.HK",
"candlesticks": [
{
"close": "362.000",
"open": "364.600",
"low": "361.600",
"high": "368.800",
"volume": 10853604,
"turnover": "3954556819.000",
"timestamp": 1650384000
}
]
}
```
#### History Candlesticks
`WS` `request · cmd 27`
> **Quote Permission Required · Free**
> Quota-based access: 100–3,000 unique symbols per calendar month depending on account tier (resets monthly; see quota table in the docs).
> US stocks: US LV1 included free by default (pre-market, regular, after-hours, and overnight sessions).
> HK stocks: LV1 included by default.
> US options: no permission by default — purchase "OPRA US Options Quotes (OpenAPI)".
> _OpenAPI quote perms are separate from App/Web perms_
This API is used to obtain the history candlestick data of security.
```protobuf
message SecurityHistoryCandlestickRequest {
string symbol = 1;
Period period = 2;
AdjustType adjust_type = 3;
HistoryCandlestickQueryType query_type = 4;
OffsetQuery offset_request = 5;
DateQuery date_request = 6;
}
message SecurityCandlestickResponse {
string symbol = 1;
repeated Candlestick candlesticks = 2;
}
```
##### Request Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security code, in ticker.region format, e.g. 700.HK |
| `period` | int32 | Yes | Candlestick period |
| `adjust_type` | int32 | Yes | Adjustment type |
| `query_type` | int32 | Yes | Type of query (1-by offset, 2-by date) |
| `date_request` | object | No | Required when querying by date |
| `└ start_date` | string | No | Date of query begin, in YYYYMMDD format |
| `└ end_date` | string | No | Date of query end, in YYYYMMDD format |
| `offset_request` | object | No | Required when querying by offset |
| `└ direction` | int32 | Yes | Query direction (0-historical, 1-latest) |
| `└ date` | string | No | Query date, in YYYYMMDD format; default latest trading day |
| `└ minute` | string | No | Query time, in HHMM format; only valid for minute-level data |
| `└ count` | int32 | No | Count of candlestick, range [1,1000]; default 10 |
| `trade_session` | int32 | No | Trading session, 0: intraday, 100: All (pre, intraday, post, overnight) |
##### Response Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | No | Security code, e.g. AAPL.US |
| `candlesticks` | object[] | No | Candlestick data |
| `└ close` | string | No | Close price |
| `└ open` | string | No | Open price |
| `└ low` | string | No | Low price |
| `└ high` | string | No | High price |
| `└ volume` | int64 | No | Volume |
| `└ turnover` | string | No | Turnover |
| `└ timestamp` | int64 | No | Timestamp |
| `└ trade_session` | int32 | No | Trade session |
##### Response JSON Example
```json
{
"symbol": "700.HK",
"candlesticks": [
{
"close": "362.000",
"open": "364.600",
"low": "361.600",
"high": "368.800",
"volume": 10853604,
"turnover": "3954556819.000",
"timestamp": 1650384000
}
]
}
```
### Options
#### Volume
`GET` `/v1/quote/option-volume-stats`
Get real-time call/put volume snapshot for today.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | US stock symbol, e.g. `AAPL.US`, `TSLA.US` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/option-volume-stats?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `c` | string | No | Total call option volume. |
| `p` | string | No | Total put option volume. |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"symbol": "AAPL.US",
"call_volume": 284512,
"put_volume": 195830
}
}
```
#### Daily Volume
`GET` `/v1/quote/option-volume-stats/daily`
Get historical daily call/put volume and open interest data for a US stock's options.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Underlying US stock symbol, e.g. `AAPL.US`, `TSLA.US` |
| `timestamp` | integer | No | Start Unix timestamp (seconds); `0` returns the most recent (default `0`) |
| `count` | integer | No | Number of trading days to return (default `30`) |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/option-volume-stats/daily?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `stats` | object[] | Yes | Daily volume records. |
| `└ symbol` | string | Yes | Security symbol, e.g. `AAPL.US`. |
| `└ timestamp` | string | Yes | Record date (Unix seconds). |
| `└ total_call_volume` | string | Yes | Call volume on that day. |
| `└ total_put_volume` | string | Yes | Put volume on that day. |
| `└ total_call_open_interest` | string | Yes | Call open interest. |
| `└ total_put_open_interest` | string | Yes | Put open interest. |
| `└ total_volume` | string | Yes | Total options volume. |
| `└ total_open_interest` | string | Yes | Total options open interest. |
| `└ put_call_volume_ratio` | string | Yes | Put/call volume ratio. |
| `└ put_call_open_interest_ratio` | string | Yes | Put/call open interest ratio. |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"symbol": "AAPL.US",
"stats": [
{
"symbol": "AAPL.US",
"date": "2026-05-07",
"call_volume": 284512,
"put_volume": 195830,
"call_open_interest": 1824500,
"put_open_interest": 1532100,
"total_volume": 480342,
"total_open_interest": 3356600,
"pc_vol": 0.6886,
"pc_oi": 0.8398
}
]
}
}
```
#### Option Quotes
`WS` `request · cmd 12`
> **Quote Permission Required · OPRA**
> No US options quote permission by default for new funded accounts.
> Purchase "OPRA US Options Quotes (OpenAPI)" in the Quote Store to access US options real-time data.
> _OpenAPI quote perms are separate from App/Web perms_
This API is used to obtain the real-time quotes of US stock options, including the option-specific data.
```protobuf
message MultiSecurityRequest {
repeated string symbol = 1;
}
message OptionQuoteResponse {
repeated OptionQuote secu_quote = 1;
}
```
##### Request Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string[] | Yes | Security code list. obtain the symbol of the options through the optionchain API, for example: [BABA230120C160000.US]. Max 500 symbols per request |
##### Response Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `secu_quote` | object[] | No | Options quote |
| `└ symbol` | string | No | Security code |
| `└ last_done` | string | No | Latest price |
| `└ prev_close` | string | No | Yesterday's close |
| `└ open` | string | No | Open |
| `└ high` | string | No | High |
| `└ low` | string | No | Low |
| `└ timestamp` | int64 | No | Time of latest price |
| `└ volume` | int64 | No | Volume |
| `└ turnover` | string | No | Turnover |
| `└ trade_status` | int32 | No | Security trading status, see TradeStatus |
| `└ option_extend` | object | No | Option extend quote |
| ` └ implied_volatility` | string | No | Implied volatility |
| ` └ open_interest` | int64 | No | Number of open positions |
| ` └ expiry_date` | string | No | Expiry date, in YYMMDD format |
| ` └ strike_price` | string | No | Strike price |
| ` └ contract_multiplier` | string | No | Contract multiplier |
| ` └ contract_type` | string | No | Option type: A - American, U - Europe |
| ` └ contract_size` | string | No | Contract size |
| ` └ direction` | string | No | Direction: P - put, C - call |
| ` └ historical_volatility` | string | No | Underlying security historical volatility of the option |
| ` └ underlying_symbol` | string | No | Underlying security symbol of the option |
##### Response JSON Example
```json
{
"secu_quote": [
{
"symbol": "AAPL220429P162500.US",
"last_done": "7.78",
"prev_close": "4.13",
"timestamp": 1651003200,
"volume": 3082,
"turnover": "1813434.00",
"option_extend": {
"implied_volatility": "0.592",
"open_interest": 11463,
"expiry_date": "20220429",
"strike_price": "162.50",
"contract_type": "A",
"direction": "P",
"underlying_symbol": "AAPL.US"
}
}
]
}
```
#### Option Chain Expiry Dates
`WS` `request · cmd 20`
This API is used to obtain the the list of expiration dates of option chain
```protobuf
message SecurityRequest {
string symbol = 1;
}
message OptionChainDateListResponse {
repeated string expiry_date = 1;
}
```
##### Request Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security code, in ticker.region format, for example: 700.HK |
##### Response Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `expiry_date` | string[] | No | option chain expiry dates list, in YYMMDD format |
##### Response JSON Example
```json
{
"expiry_date": [
"20220422",
"20220429",
"20220506"
]
}
```
#### Option Chain Info
`WS` `request · cmd 21`
This API is used to obtain a list of option securities by the option chain expiry date.
```protobuf
message OptionChainDateStrikeInfoRequest {
string symbol = 1;
string expiry_date = 2;
}
message OptionChainDateStrikeInfoResponse {
repeated StrikePriceInfo strike_price_info = 1;
}
```
##### Request Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security code, in ticker.region format, for example: 700.HK |
| `expiry_date` | string | Yes | Option expiry date, in YYMMDD format, for example: 20220429, obtained by Option Expiry Date API |
##### Response Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `strike_price_info` | object[] | No | Option security info |
| `└ price` | string | No | Strike price |
| `└ call_symbol` | string | No | Security code of call option |
| `└ put_symbol` | string | No | Security code of put option |
| `└ standard` | bool | No | Is standard |
##### Response JSON Example
```json
{
"strike_price_info": [
{
"price": "100",
"call_symbol": "AAPL220429C100000.US",
"put_symbol": "AAPL220429P100000.US",
"standard": true
}
]
}
```
### Analytics
#### Query Signals
`GET` `/v1/signals`
Query strategy signals, filtered by symbol, strategy, catalyst and time range. Each signal is a strategy’s take on a security, triggered by a catalyst fact.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol_name` | string | No | Filter by security symbol, e.g. `AAPL.US` or `700.HK`. If omitted, returns signals for all symbols. |
| `strategy_id` | string | No | Filter by strategy id, e.g. `buffett-value`. Preferred over the deprecated `strategy_name`; takes precedence when both are provided. |
| `strategy_name` | string | No | Filter by strategy name. Deprecated in favour of `strategy_id`. If omitted, returns signals from all strategies. |
| `catalyst_name` | string | No | Filter by the name of the factor that triggered the signal, e.g. `EARNINGS_RELEASED` or `macd_12_26_9` — the triggering fact’s `factors[].name`, not the display label. If omitted, any catalyst name is returned. |
| `catalyst_type` | string | No | Filter by the catalyst type that triggered the signal, e.g. `News`, `Fundamental`, `Technical`. If omitted, any catalyst type is returned. |
| `start_time` | string | No | Only return signals created at or after this time. RFC3339 (a Unix timestamp is also accepted). If omitted, no lower bound. |
| `end_time` | string | No | Only return signals created at or before this time. RFC3339 (a Unix timestamp is also accepted). If omitted, no upper bound. |
| `limit` | integer | No | Maximum number of results to return. Defaults to 20. |
| `offset` | integer | No | Number of results to skip for pagination. Defaults to 0. |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/signals' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `signals` | object[] | No | Signals on this page |
| `└ id` | string | No | Signal ID, e.g. `sign_992_1a00c9425c3_48ab` |
| `└ stock_symbol` | string | No | Security symbol, e.g. `700.HK`. |
| `└ symbol` | string | No | Security symbol, e.g. `992.HK` |
| `└ company_name` | string | No | Company name |
| `└ title` | string | No | Signal headline |
| `└ strategy_name` | string | No | Strategy name that produced the signal |
| `└ strategy_id` | string | No | Strategy ID that produced the signal |
| `└ expression` | string | No | Strategy expression, e.g. `992.HK:GROWTH:long` |
| `└ created_at` | string | No | Creation time (RFC3339) |
| `└ updated_at` | string | No | Last update time (RFC3339) |
| `└ status` | integer | No | Lifecycle status: `0` Pending, `1` Active, `2` Deleted, `3` AiFailed, `4` FilteredByManual, `5` AiSubmitFailed |
| `└ json_data` | string | No | Full analysis behind the signal as a JSON document (strategy fit scores, valuation scenarios, evidence sources, related fact IDs). Carried verbatim because its shape is strategy-specific. |
| `└ key_fact_id` | string | No | ID of the fact that triggered the signal |
| `└ key_catalyst` | string | No | Display label of the catalyst that triggered the signal, e.g. `Q1 Revenue Surge` |
| `└ analysis_price` | integer | No | Price the analysis was based on |
| `└ conservative_price` | integer | No | Conservative-scenario target price |
| `└ benchmark_price` | integer | No | Benchmark-scenario target price |
| `└ optimistic_price` | integer | No | Optimistic-scenario target price |
| `└ outlook` | string | No | Outlook the strategy takes on the security: `Strong bullish`, `Bullish`, `Neutral`, `Bearish`, `Strong bearish` |
| `└ summary` | string | No | Natural-language summary of the signal, in Markdown |
| `└ market` | string | No | Market the security trades in, e.g. `HK` |
| `└ outlook_desc` | string | No | Outlook label localized in the caller’s language |
| `└ display_control` | integer | No | Display control flag. |
| `└ recommend_by` | string | No | Who recommended the signal; empty for strategy-generated signals |
| `└ risk_level` | string | No | Risk control level. Option:, `0` - safe, `1` - medium risk, `2` - early warning, `3` - danger |
| `total` | integer | No | Total number of signals matching the filters, for paging with `offset` |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"signals": [
{
"id": "sign_992_1a00c9425c3_48ab",
"symbol": "992.HK",
"company_name": "Lenovo Group",
"market": "HK",
"title": "Momentum breakout",
"summary": "RSI crossed above 70 ...",
"strategy_id": "growth-momentum",
"strategy_name": "Growth Momentum",
"expression": "992.HK:GROWTH:long",
"key_fact_id": "technical_rsi_14_short_1783674041337603409",
"key_catalyst": "RSI Breakout",
"analysis_price": 10.5,
"conservative_price": 11,
"benchmark_price": 12.5,
"optimistic_price": 14,
"outlook": "Bullish",
"outlook_desc": "Bullish",
"status": 1,
"json_data": "{}",
"created_at": "2026-06-01T09:30:00Z",
"updated_at": "2026-06-01T09:30:00Z"
}
],
"total": 1
}
}
```
#### Get Signal Detail
`GET` `/v1/signals/{signal_id}`
Get one signal by ID, including the full analysis in `json_data`.
##### Parameters
###### Path Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `signal_id` | string | Yes | Signal ID, e.g. `sign_992_1a00c9425c3_48ab`. |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/signals/' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `signal` | object | Yes | The signal record |
| `└ id` | string | Yes | Signal ID |
| `└ symbol` | string | No | Security symbol |
| `└ title` | string | No | Signal headline |
| `└ summary` | string | No | Natural-language summary (Markdown) |
| `└ outlook` | string | No | Outlook: `Strong bullish`, `Bullish`, `Neutral`, `Bearish`, `Strong bearish` |
| `└ json_data` | string | No | Full strategy analysis as a JSON document, carried verbatim |
| `└ created_at` | string | Yes | Creation time (RFC3339) |
| `└ updated_at` | string | Yes | Last update time (RFC3339) |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"signal": {
"id": "sign_992_1a00c9425c3_48ab",
"symbol": "992.HK",
"title": "Momentum breakout",
"summary": "RSI crossed above 70 ...",
"outlook": "Bullish",
"json_data": "{\"core_conclusion\":{\"outlook_enum\":2}}",
"created_at": "2026-06-01T09:30:00Z",
"updated_at": "2026-06-01T09:30:00Z"
}
}
}
```
#### List Security Facts
`GET` `/v1/facts/security_facts`
List the fact (catalyst) events for one security — anomaly detections, factor readings, data sources and natural-language summaries. Facts are what strategies react to: a signal names the fact that triggered it in `key_fact_id`.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | The security to query, e.g. `AAPL.US` or `700.HK`. Required. |
| `begin_time` | string | No | Start of the query window (RFC3339). If omitted, includes the earliest available data. |
| `end_time` | string | No | End of the query window (RFC3339). If omitted, returns the latest data. |
| `limit` | integer | No | Maximum number of facts to return. When more facts fall inside the range, only the latest `limit` are returned. Defaults to 100. |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/facts/security_facts?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `facts` | object[] | No | Fact (catalyst) events for the security |
| `└ fact_id` | string | No | Fact ID, e.g. `technical_rsi_14_short_1783674041337603409` |
| `└ fact_type` | string | No | Kind of fact: `News`, `Fundamental`, `Technical` |
| `└ occur_time` | string | No | When the fact occurred (RFC3339) |
| `└ direction` | string | No | Side the fact points to: `long`, `short`, `neutral` |
| `└ data_source` | object[] | No | Where the fact came from (`source_name`, `type`, `url`, `icon`) |
| `└ ∟ type` | string | No | `"platform"` for preset strategies |
| `└ ∟ source_name` | string | No | Data source name. |
| `└ ∟ url` | string | No | Original image URL |
| `└ ∟ icon` | string | No | Icon URL |
| `└ nl_info` | object | No | Natural-language rendering of the fact (`title`, `sub_title`, `summary`, `invest_anal`, `eli_explain`) |
| `└ ∟ title` | string | No | Topic title |
| `└ ∟ sub_title` | string | No | Sub-title. |
| `└ ∟ summary` | string | No | Natural-language summary of the signal, in Markdown |
| `└ ∟ invest_anal` | string | No | Investment analysis. |
| `└ ∟ eli_explain` | string | No | Plain-language explanation. |
| `└ symbols_info` | object[] | No | Securities the fact is about (`symbol`, `security_name`) |
| `└ ∟ symbol` | string | No | Security symbol |
| `└ ∟ security_name` | string | No | Security name. |
| `└ factors` | object[] | No | Factors that contributed to the fact (`name`, `factor_groups`, `long_short_direction`, `trigger_condition`, `anomaly_detection`) |
| `└ ∟ name` | string | No | Security name. |
| `└ ∟ factor_groups` | array | No | Factor groups. |
| `└ ∟ long_short_direction` | string | No | Long/short direction. |
| `└ ∟ anomaly_detection` | object | No | Anomaly detection info. |
| `└ ∟ ∟ test_method` | string | No | Test method. |
| `└ ∟ ∟ anomaly_result` | string | No | Anomaly detection result. |
| `└ ∟ ∟ thresholds` | object | No | Threshold values. |
| `└ ∟ ∟ ∟ low` | string | No | 5-year low |
| `└ ∟ ∟ ∟ medium` | string | No | Medium bound. |
| `└ ∟ ∟ ∟ high` | string | No | 5-year high |
| `└ ∟ ∟ significance_level` | string | No | Statistical significance level. |
| `└ ∟ trigger_condition` | string | No | Trigger condition. |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"facts": [
{
"fact_id": "technical_rsi_14_short_1783674041337603409",
"fact_type": "Technical",
"direction": "short",
"occur_time": "2026-06-01T00:00:00Z",
"symbols_info": [
{
"symbol": "AAPL.US",
"security_name": "Apple"
}
],
"factors": [
{
"name": "rsi_14",
"factor_groups": [
"MOMENTUM"
],
"long_short_direction": "short",
"trigger_condition": "RSI > 70",
"anomaly_detection": {
"anomaly_result": "",
"significance_level": "",
"test_method": "",
"thresholds": {
"low": "",
"medium": "",
"high": ""
}
}
}
],
"data_source": [
{
"source_name": "Nasdaq",
"type": "Technical",
"url": "",
"icon": ""
}
],
"nl_info": {
"title": "RSI overbought",
"sub_title": "",
"summary": "[]",
"invest_anal": "[]",
"eli_explain": "[]"
}
}
]
}
}
```
#### Short Positions (HK)
`GET` `/v1/quote/short-positions/hk`
Get short interest data for US or HK securities. Market is auto-detected from the symbol suffix: `.HK` → HKEX short position data (daily); others → US FINRA short interest data (bi-monthly).
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `TSLA.US` or `700.HK` |
| `count` | integer | No | Number of records to return (1–100, default: 20) |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/short-positions/hk?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | No | Security symbol, e.g. `700.HK`. |
| `update_timestamp` | string | No | Last update time (Unix seconds). |
| `data` | object[] | No | Daily HKEX short-position records. |
| `└ timestamp` | string | No | Record date (Unix seconds). |
| `└ amount` | string | No | Short-sold shares that day. |
| `└ balance` | string | No | Outstanding short-position value. |
| `└ rate` | string | No | Short-position ratio. |
| `└ cost` | string | No | Average short-position price. |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": [
{
"timestamp": "2022-03-15T04:00:00Z",
"current_shares_short": "111286790",
"avg_daily_share_volume": "95077016",
"days_to_cover": "1.17",
"rate": "0.0068",
"close": ""
}
]
}
```
#### Short Positions (US)
`GET` `/v1/quote/short-positions/us`
Get short interest data for US or HK securities. Market is auto-detected from the symbol suffix: `.HK` → HKEX short position data (daily); others → US FINRA short interest data (bi-monthly).
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `TSLA.US` or `700.HK` |
| `count` | integer | No | Number of records to return (1–100, default: 20) |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/short-positions/us?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | No | Security symbol, e.g. `AAPL.US`. |
| `data` | object[] | No | Bi-monthly FINRA short-interest records. |
| `└ timestamp` | string | No | Settlement date (Unix seconds). |
| `└ rate` | string | No | Short interest as a fraction of float. |
| `└ avg_daily_share_volume` | string | No | Average daily share volume. |
| `└ current_shares_short` | string | No | Current shares sold short. |
| `└ days_to_cover` | string | No | Days to cover (short interest / avg volume). |
| `└ close` | string | No | Closing price. |
| `sources` | integer | No | Number of contributing data sources. |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": [
{
"timestamp": "2022-03-15T04:00:00Z",
"current_shares_short": "111286790",
"avg_daily_share_volume": "95077016",
"days_to_cover": "1.17",
"rate": "0.0068",
"close": ""
}
]
}
```
#### Daily Short Sale Volume (HK)
`GET` `/v1/quote/short-trades/hk`
Get daily short sale volume data for a security. Supports US stocks (FINRA/NASDAQ) and HK stocks (HKEX). US data is updated bi-weekly; HK data is updated each trading day.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol; supports US (e.g. `TSLA.US`) and HK (e.g. `700.HK`) |
| `count` | integer | No | Number of records to return (1–100, default 20) |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/short-trades/hk?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | No | Security symbol, e.g. `700.HK`. |
| `data` | object[] | No | Daily HKEX short-sale records. |
| `└ timestamp` | string | No | Trade date (Unix seconds). |
| `└ amount` | string | No | Short-sale turnover that day. |
| `└ balance` | string | No | Short-sale balance. |
| `└ close` | string | No | Closing price. |
| `└ rate` | string | No | Short-sale ratio. |
| `└ total_amount` | string | No | Total market turnover. |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": [
{
"timestamp": "2026-05-15T04:00:00Z",
"nus_amount": "5748485",
"ny_amount": "0",
"total_amount": "15778974",
"rate": "0.3643",
"close": "300.230"
}
]
}
```
#### Daily Short Sale Volume (US)
`GET` `/v1/quote/short-trades/us`
Get daily short sale volume data for a security. Supports US stocks (FINRA/NASDAQ) and HK stocks (HKEX). US data is updated bi-weekly; HK data is updated each trading day.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol; supports US (e.g. `TSLA.US`) and HK (e.g. `700.HK`) |
| `count` | integer | No | Number of records to return (1–100, default 20) |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/short-trades/us?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | No | Security symbol, e.g. `AAPL.US`. |
| `data` | object[] | No | Daily US short-sale volume records. |
| `└ timestamp` | string | No | Trade date (Unix seconds). |
| `└ nus_amount` | string | No | Non-exchange (off-exchange) short volume. |
| `└ total_amount` | string | No | Total short volume. |
| `└ ny_amount` | string | No | NYSE short volume. |
| `└ close` | string | No | Closing price. |
| `└ rate` | string | No | Short-volume ratio. |
| `sources` | integer | No | Number of contributing data sources. |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": [
{
"timestamp": "2026-05-15T04:00:00Z",
"nus_amount": "5748485",
"ny_amount": "0",
"total_amount": "15778974",
"rate": "0.3643",
"close": "300.230"
}
]
}
```
#### Get Filings by Symbol
`GET` `/v1/quote/filings`
> **Quote Permission Required · Free**
> Included with OpenAPI activation — no extra purchase needed.
> _OpenAPI quote perms are separate from App/Web perms_
Get the list of regulatory filings or disclosure documents for the specified symbol.
Each filing includes a title, file name, download URLs, and publication timestamp.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol to query filings for (e.g. `AAPL.US`, `700.HK`). |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/filings?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `items` | object[] | No | Filings for the security. |
| `└ id` | string | No | Filing ID. |
| `└ title` | string | No | Filing title. |
| `└ file_name` | string | No | File name. |
| `└ file_urls` | array | No | Source document URLs. |
| `└ publish_at` | string | No | Publish time (Unix timestamp). |
| `└ description` | string | No | Filing description. |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"items": [
{
"id": "627391979864985729",
"title": "Apple | 4 - Apple Inc. (0000320193) (Issuer)",
"description": "",
"file_name": "4 - Apple Inc. (0000320193) (Issuer)",
"file_urls": [
"https://www.sec.gov/Archives/edgar/data/320193/.../wk-form4_1773786674.xml"
],
"publish_at": "1773786677"
}
]
}
}
```
#### Capital Flow (Intraday)
`WS` `request · cmd 24`
> **Quote Permission Required · Free**
> Included with OpenAPI activation — no extra purchase needed.
> _OpenAPI quote perms are separate from App/Web perms_
This API is used to obtain the daily capital flow intraday of security.
```protobuf
message CapitalFlowIntradayRequest {
string symbol = 1;
}
message CapitalFlowIntradayResponse {
string symbol = 1;
repeated CapitalFlowLine capital_flow_lines = 2;
}
```
##### Request Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security code, in ticker.region format, for example: 700.HK |
##### Response Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | No | Security code |
| `capital_flow_lines` | object[] | No | Capital flow data |
| `└ inflow` | string | No | Inflow capital data |
| `└ timestamp` | int64 | No | Start time stamp of the minute |
##### Response JSON Example
```json
{
"symbol": "700.HK",
"capital_flow_lines": [
{
"inflow": "-310255860.000",
"timestamp": "1655106960"
}
]
}
```
#### Capital Distribution
`WS` `request · cmd 25`
> **Quote Permission Required · Free**
> Included with OpenAPI activation — no extra purchase needed.
> _OpenAPI quote perms are separate from App/Web perms_
This API is used to obtain the daily capital distribution of security.
```protobuf
message SecurityRequest {
string symbol = 1;
}
message CapitalDistributionResponse {
string symbol = 1;
int64 timestamp = 2;
CapitalDistribution capital_in = 3;
CapitalDistribution capital_out = 4;
}
```
##### Request Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security code, in ticker.region format, for example: 700.HK |
##### Response Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | No | Security code |
| `timestamp` | int64 | No | Data update time |
| `capital_in` | object[] | No | Inflow capital data |
| `└ large` | string | No | large order |
| `└ medium` | string | No | medium order |
| `└ small` | string | No | small order |
| `capital_out` | object[] | No | Outflow capital data |
| `└ large` | string | No | large order |
| `└ medium` | string | No | medium order |
| `└ small` | string | No | small order |
##### Response JSON Example
```json
{
"symbol": "700.HK",
"timestamp": "1655107800",
"capital_in": {
"large": "935389700.000",
"medium": "2056032380.000",
"small": "828715920.000"
},
"capital_out": {
"large": "1175331560.000",
"medium": "2271829740.000",
"small": "751648940.000"
}
}
```
#### Calc Indexes
`WS` `request · cmd 26`
> **Quote Permission Required · Free**
> Included with OpenAPI activation — no extra purchase needed.
> _OpenAPI quote perms are separate from App/Web perms_
This API is used to obtain the calculate indexes of securities.
```protobuf
message SecurityCalcQuoteRequest {
repeated string symbols = 1;
repeated CalcIndex calc_index = 2;
}
message SecurityCalcQuoteResponse {
repeated SecurityCalcIndex security_calc_index = 1;
}
```
##### Request Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbols` | string[] | Yes | Security code list, in ticker.region format, for example: [700.HK]. Max 500 symbols per request |
| `calc_index` | int32[] | Yes | Calc indexes, for example: [1,2,3], see CalcIndex |
##### Response Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `security_calc_index` | object[] | No | Security Index Data |
| `└ symbol` | string | No | Security code |
| `└ last_done` | string | No | Latest price |
| `└ change_val` | string | No | Change value |
| `└ change_rate` | string | No | Change ratio (ratio field, excludes %) |
| `└ volume` | int64 | No | Volume |
| `└ turnover` | string | No | Turnover |
| `└ ytd_change_rate` | string | No | Year-to-date change ratio (ratio field, excludes %) |
| `└ turnover_rate` | string | No | Turnover rate (ratio field, excludes %) |
| `└ total_market_value` | string | No | Total market value |
| `└ capital_flow` | string | No | Capital flow |
| `└ amplitude` | string | No | Amplitude (ratio field, excludes %) |
| `└ volume_ratio` | string | No | Volume ratio |
| `└ pe_ttm_ratio` | string | No | PE (TTM) |
| `└ pb_ratio` | string | No | PB |
| `└ dividend_ratio_ttm` | string | No | Dividend ratio (TTM) |
| `└ five_day_change_rate` | string | No | Five days change ratio (ratio field, excludes %) |
| `└ ten_day_change_rate` | string | No | Ten days change ratio (ratio field, excludes %) |
| `└ half_year_change_rate` | string | No | Half year change ratio (ratio field, excludes %) |
| `└ five_minutes_change_rate` | string | No | Five minutes change ratio (ratio field, excludes %) |
| `└ expiry_date` | string | No | Expiry date |
| `└ strike_price` | string | No | Strike price |
| `└ upper_strike_price` | string | No | Upper bound price |
| `└ lower_strike_price` | string | No | Lower bound price |
| `└ outstanding_qty` | int64 | No | Outstanding quantity |
| `└ outstanding_ratio` | string | No | Outstanding ratio (ratio field, excludes %) |
| `└ premium` | string | No | Premium (ratio field, excludes %) |
| `└ itm_otm` | string | No | In/out of the bound (ratio field, excludes %) |
| `└ implied_volatility` | string | No | Implied volatility (ratio field, excludes %) |
| `└ warrant_delta` | string | No | Warrant delta |
| `└ call_price` | string | No | Call price |
| `└ to_call_price` | string | No | Price interval from the call price (ratio field, excludes %) |
| `└ effective_leverage` | string | No | Effective leverage |
| `└ leverage_ratio` | string | No | Leverage ratio |
| `└ conversion_ratio` | string | No | Conversion ratio |
| `└ balance_point` | string | No | Breakeven point |
| `└ open_interest` | int64 | No | Open interest |
| `└ delta` | string | No | Delta |
| `└ gamma` | string | No | Gamma |
| `└ theta` | string | No | Theta. Raw value divided by 100 for standard per-share per-day value |
| `└ vega` | string | No | Vega. Raw value divided by 100 for standard per-share per-1%-IV value |
| `└ rho` | string | No | Rho. Raw value divided by 100 for standard per-share per-1%-rate value |
##### Response JSON Example
```json
{
"security_calc_index": [
{
"symbol": "AAPL.US",
"last_done": "131.880",
"change_val": "-5.2500",
"change_rate": "-3.83",
"volume": "122207099",
"turnover": "16269088361.000"
}
]
}
```
### Watchlist
#### Update Pinned
`POST` `/v1/watchlist/pinned`
Pin or unpin a security within a watchlist group to control its display order.
##### Parameters
###### Request Body
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `mode` | string | Yes | Operation mode: `add` (pin to top) or `remove` (unpin) |
| `securities` | array | Yes | Security symbols to pin/unpin, e.g. `["AAPL.US", "700.HK"]` (must already be in the watchlist) |
##### Request Example
```bash
curl --request POST \
--url 'https://openapi.longbridge.com/v1/watchlist/pinned' \
--header 'Authorization: Bearer ' \
--header 'Content-Type: application/json' \
--data '{"id":"","symbol":"","is_pinned":false}'
```
##### Response
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {}
}
```
#### Watchlist Groups
`GET` `/v1/watchlist/groups`
> **Quote Permission Required · Free**
> Included with OpenAPI activation — no extra purchase needed.
> _OpenAPI quote perms are separate from App/Web perms_
Get Watchlist groups
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/watchlist/groups' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `groups` | object[] | No | Groups |
| `└ id` | integer | Yes | Group ID |
| `└ name` | string | Yes | Name |
| `└ securities` | object[] | Yes | Security |
###### Response JSON Example
```json
{
"code": 0,
"data": {
"groups": [
{
"id": 28020,
"name": "all",
"securities": [
{
"symbol": "700.HK",
"market": "HK",
"name": "Tencent",
"watched_price": "364.4",
"watched_at": 1652855022,
"is_pinned": true
}
]
}
]
}
}
```
#### Create Group
`POST` `/v1/watchlist/groups`
> **Quote Permission Required · Free**
> Included with OpenAPI activation — no extra purchase needed.
> _OpenAPI quote perms are separate from App/Web perms_
Create watched group
##### Parameters
###### Request Body
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `name` | string | Yes | Watchlist group name. |
| `securities` | array | No | Optional list of security symbols to pre-populate the group, e.g. `["AAPL.US","700.HK"]`. |
##### Request Example
```bash
curl --request POST \
--url 'https://openapi.longbridge.com/v1/watchlist/groups' \
--header 'Authorization: Bearer ' \
--header 'Content-Type: application/json' \
--data '{"name":"","securities":[]}'
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | integer | No | Group ID |
###### Response JSON Example
```json
{
"code": 0,
"data": {
"id": 10086
}
}
```
#### Manage Group Securities
`PUT` `/v1/watchlist/groups`
> **Quote Permission Required · Free**
> Included with OpenAPI activation — no extra purchase needed.
> _OpenAPI quote perms are separate from App/Web perms_
Update watched group
##### Parameters
###### Request Body
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | integer | Yes | Watchlist group ID. |
| `name` | string | No | New group name. |
| `securities` | array | No | Security symbols to add/remove/replace, per `mode`. |
| `mode` | string | Yes | Securities update mode: `add`, `remove`, or `replace`. |
##### Request Example
```bash
curl --request PUT \
--url 'https://openapi.longbridge.com/v1/watchlist/groups' \
--header 'Authorization: Bearer ' \
--header 'Content-Type: application/json' \
--data '{"id":0,"name":"","securities":[],"mode":""}'
```
##### Response
###### Response JSON Example
```json
{
"code": 0
}
```
#### Delete Group
`DELETE` `/v1/watchlist/groups`
> **Quote Permission Required · Free**
> Included with OpenAPI activation — no extra purchase needed.
> _OpenAPI quote perms are separate from App/Web perms_
Delete watched group
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | integer | Yes | Group ID, for example `10086`. |
| `purge` | boolean | Yes | Whether to clear the securities in the group. If set to `true`, the securities in the group will be unfollowed. If set to `false`, the securities in the group will remain in the `All` group. |
##### Request Example
```bash
curl --request DELETE \
--url 'https://openapi.longbridge.com/v1/watchlist/groups?id=&purge=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response JSON Example
```json
{
"code": 0
}
```
### Warrants
#### Warrant Quotes
`WS` `request · cmd 13`
> **Quote Permission Required · Free**
> Included with OpenAPI activation — no extra purchase needed.
> _OpenAPI quote perms are separate from App/Web perms_
This API is used to obtain the real-time quotes of HK warrants, including the warrant-specific data.
```protobuf
message MultiSecurityRequest {
repeated string symbol = 1;
}
message WarrantQuoteResponse {
repeated WarrantQuote secu_quote = 2;
}
```
##### Request Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string[] | Yes | Security code list, in ticker.region format, for example: [13447.HK]. Max 500 symbols per request |
##### Response Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `secu_quote` | object[] | No | Warrants quote |
| `└ symbol` | string | No | Security code |
| `└ last_done` | string | No | Latest price |
| `└ prev_close` | string | No | Yesterday's close |
| `└ open` | string | No | Open |
| `└ high` | string | No | High |
| `└ low` | string | No | Low |
| `└ timestamp` | int64 | No | Time of latest price |
| `└ volume` | int64 | No | Volume |
| `└ turnover` | string | No | Turnover |
| `└ trade_status` | int32 | No | Security trading status, see TradeStatus |
| `└ warrant_extend` | object | No | Warrant extend quote |
| ` └ implied_volatility` | string | No | Implied volatility |
| ` └ expiry_date` | string | No | Expiry date, in YYMMDD format |
| ` └ last_trade_date` | string | No | Last tradable date, in YYMMDD format |
| ` └ outstanding_ratio` | string | No | Outstanding ratio |
| ` └ outstanding_qty` | int64 | No | Outstanding quantity |
| ` └ conversion_ratio` | string | No | Conversion ratio |
| ` └ category` | string | No | Warrant type: Call, Put, Bull, Bear, Inline |
| ` └ strike_price` | string | No | Strike price |
| ` └ upper_strike_price` | string | No | Upper bound price |
| ` └ lower_strike_price` | string | No | Lower bound price |
| ` └ call_price` | string | No | Call price |
| ` └ underlying_symbol` | string | No | Underlying security symbol of the option |
##### Response JSON Example
```json
{
"secu_quote": [
{
"symbol": "66642.HK",
"last_done": "0.345",
"prev_close": "0.365",
"timestamp": 1651130421,
"volume": 200000,
"turnover": "69000.000",
"warrant_extend": {
"implied_volatility": "0.319",
"expiry_date": "20220830",
"category": "Bear",
"strike_price": "23200.000",
"underlying_symbol": "HSI.HK"
}
}
]
}
```
#### Warrant Issuers
`WS` `request · cmd 22`
> **Quote Permission Required · Free**
> Included with OpenAPI activation — no extra purchase needed.
> _OpenAPI quote perms are separate from App/Web perms_
This API is used to obtain the warrant issuer IDs data (which can be synchronized once a day).
```protobuf
message IssuerInfoResponse {
repeated IssuerInfo issuer_info = 1;
}
message IssuerInfo {
int32 id = 1;
string name_cn = 2;
string name_en = 3;
string name_hk = 4;
}
```
##### Response Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `issuer_info` | object[] | No | Issuer information |
| `└ id` | int32 | No | Issuer ID |
| `└ name_cn` | string | No | Issuer Name (zh-CN) |
| `└ name_en` | string | No | Issuer Name (en) |
| `└ name_hk` | string | No | Issuer Name (zh-HK) |
##### Response JSON Example
```json
{
"issuer_info": [
{
"id": 15,
"name_cn": "瑞银",
"name_en": "UB",
"name_hk": "瑞銀"
}
]
}
```
#### Warrant Screener
`WS` `request · cmd 23`
> **Quote Permission Required · Free**
> Included with OpenAPI activation — no extra purchase needed.
> _OpenAPI quote perms are separate from App/Web perms_
This API is used to obtain the quotes of HK warrants, and supports sorting and filtering.
```protobuf
message WarrantFilterListRequest {
string symbol = 1;
FilterConfig filter_config = 2;
int32 language = 3;
}
message WarrantFilterListResponse {
repeated FilterWarrant warrant_list = 1;
int32 total_count = 2;
}
```
##### Request Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security code, in ticker.region format, for example: 700.HK |
| `filter_config` | object | Yes | Filter conditions |
| `└ sort_by` | int32 | Yes | Which data to sort by, for example: 0, see the OrderSequence field of the response data |
| `└ sort_order` | int32 | Yes | Order: 0 - Ascending, 1 - Descending |
| `└ sort_offset` | int32 | Yes | The first data offset of paging, for example: 0 |
| `└ sort_count` | int32 | Yes | Number of items per page, for example: 20, no pagination when filling in 0 |
| `└ type` | int32[] | No | Filter warrant type: 0 Call, 1 Put, 2 Bull, 3 Bear, 4 Inline |
| `└ issuer` | int32[] | No | Filter issuer example: [12,14], obtain Issuer ID through API |
| `└ expiry_date` | int32[] | No | Filter expiry date: 1 <3 months, 2 3-6 months, 3 6-12 months, 4 >12 months |
| `└ price_type` | int32[] | No | Filter in/out of bounds: 1 In bounds, 2 Out bounds |
| `└ status` | int32[] | No | Filter status: 2 Suspend trading, 3 Prepare List, 4 Normal |
| `language` | int32 | Yes | Language: 0 zh-CN, 1 en, 2 zh-HK |
##### Response Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `warrant_list` | object[] | No | Filtered warrant data list |
| `└ symbol` | string | No | Security code |
| `└ name` | string | No | Security name |
| `└ last_done` | string | No | Latest price |
| `└ change_rate` | string | No | Quote change rate |
| `└ change_val` | string | No | Quote change |
| `└ volume` | int64 | No | Volume |
| `└ turnover` | string | No | Turnover |
| `└ expiry_date` | string | No | Expiry date, in YYMMDD format |
| `└ strike_price` | string | No | Strike price |
| `└ upper_strike_price` | string | No | Upper bound price |
| `└ lower_strike_price` | string | No | Lower bound price |
| `└ outstanding_qty` | string | No | Outstanding quantity |
| `└ outstanding_ratio` | string | No | Outstanding ratio |
| `└ premium` | string | No | Premium |
| `└ itm_otm` | string | No | In/out of the bound |
| `└ implied_volatility` | string | No | Implied volatility |
| `└ delta` | string | No | Greek value Delta |
| `└ call_price` | string | No | Call price |
| `└ to_call_price` | string | No | Price interval from the call price |
| `└ effective_leverage` | string | No | Effective leverage |
| `└ leverage_ratio` | string | No | Leverage ratio |
| `└ conversion_ratio` | string | No | Conversion ratio |
| `└ balance_point` | string | No | Breakeven point |
| `└ status` | int32 | No | Status: 2 Suspend trading, 3 Prepare List, 4 Normal |
| `total_count` | int32 | No | Total number of eligible |
##### Response JSON Example
```json
{
"warrant_list": [
{
"symbol": "13157.HK",
"name": "MBTENCT@EP2207A",
"last_done": "2.26",
"change_rate": "-0.0216",
"expiry_date": "20220705",
"strike_price": "442.233",
"status": 4
}
],
"total_count": 1197
}
```
### Subscribe
#### Get Subscriptions
`WS` `request · cmd 5`
> **Quote Permission Required · Free**
> Included with OpenAPI activation — no extra purchase needed.
> _OpenAPI quote perms are separate from App/Web perms_
This API is used to obtain the subscription information.
```protobuf
message SubscriptionRequest {
}
message SubscriptionResponse {
repeated SubTypeList sub_list = 1;
}
message SubTypeList {
string symbol = 1;
repeated SubType sub_type = 2;
}
```
##### Response Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `sub_list` | object[] | No | Subscribed data |
| `└ symbol` | string | No | Security code |
| `└ sub_type` | int32[] | No | Subscription type, see SubType |
##### Response JSON Example
```json
{
"sub_list": [
{
"symbol": "700.HK",
"sub_type": [
1,
2,
3
]
},
{
"symbol": "AAPL.US",
"sub_type": [
2
]
}
]
}
```
#### Subscribe Quote
`WS` `request · cmd 6`
> **Quote Permission Required · Free**
> Included with OpenAPI activation — no extra purchase needed.
> _OpenAPI quote perms are separate from App/Web perms_
This API is used to subscribe quote.
```protobuf
message SubscribeRequest {
repeated string symbol = 1;
repeated SubType sub_type = 2;
bool is_first_push = 3;
}
message SubscriptionResponse {
repeated SubTypeList sub_list = 1;
}
```
##### Request Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string[] | Yes | Security code list, for example: [700.HK]. Max 500 symbols per request; max 500 subscriptions per user |
| `sub_type` | int32[] | Yes | Subscription type, for example: [1,2], see SubType |
| `is_first_push` | bool | Yes | Whether to perform a data push immediately after subscribing (trade not supported) |
##### Response Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `sub_list` | object[] | No | Subscription list |
| `└ symbol` | string | No | Security code |
| `└ sub_type` | int32[] | No | Subscription type, see SubType |
##### Response JSON Example
```json
{
"sub_list": [
{
"symbol": "700.HK",
"sub_type": [
1,
2,
3
]
},
{
"symbol": "AAPL.US",
"sub_type": [
2
]
}
]
}
```
#### Unsubscribe
`WS` `request · cmd 7`
> **Quote Permission Required · Free**
> Included with OpenAPI activation — no extra purchase needed.
> _OpenAPI quote perms are separate from App/Web perms_
This API is used to unsubscribe quote.
```protobuf
message UnsubscribeRequest {
repeated string symbol = 1;
repeated SubType sub_type = 2;
bool unsub_all = 3;
}
message UnsubscribeResponse {
}
```
##### Request Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string[] | Yes | Security code list, for example: [700.HK]. Max 500 symbols per request |
| `sub_type` | int32[] | Yes | Subscription type list, for example: [1,2], see SubType |
| `unsub_all` | bool | Yes | Is unsubscribe all; empty symbol unsubscribes all, otherwise all types of these symbols |
##### Response JSON Example
```json
{}
```
#### Quote
`WS` `push · cmd 101`
> **Quote Permission Required · Free**
> US stocks: US LV1 included free by default, covering pre-market, regular, after-hours, and overnight sessions. To receive overnight data, enable it via LONGBRIDGE_ENABLE_OVERNIGHT=true (see Q6 & Q7 in the Broker FAQ).
> HK stocks: LV1 real-time quotes included by default.
> US options: no permission by default — purchase "OPRA US Options Quotes (OpenAPI)" in the Quote Store.
> _OpenAPI quote perms are separate from App/Web perms_
Real-time quote push of the subscribed security. In the pushed data structure, only the fields that have changed will be filled with data.
```protobuf
message PushQuote {
string symbol = 1;
int64 sequence = 2;
string last_done = 3;
string open = 4;
string high = 5;
string low = 6;
int64 timestamp = 7;
int64 volume = 8;
string turnover = 9;
TradeStatus trade_status = 10;
TradeSession trade_session = 11;
}
```
##### Push Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | No | Security code, for example: AAPL.US |
| `sequence` | int64 | No | Sequence number |
| `last_done` | string | No | Latest price |
| `open` | string | No | Open |
| `high` | string | No | High |
| `low` | string | No | Low |
| `timestamp` | int64 | No | Time of latest price |
| `volume` | int64 | No | Volume |
| `turnover` | string | No | Turnover |
| `trade_status` | int32 | No | Security trading status, see TradeStatus |
| `trade_session` | int32 | No | Trade session, see TradeSession |
| `current_volume` | int32 | No | Increase volume between pushes |
| `current_turnover` | string | No | Increase turnover between pushes |
| `tag` | int32 | No | Price tag: 0 real-time quote, 1 revised data after market close |
##### Response JSON Example
```json
{
"symbol": "AAPL.US",
"sequence": 160808750000000,
"last_done": "156.570",
"open": "155.910",
"high": "159.790",
"low": "155.380",
"timestamp": 1651089600,
"volume": 88063191,
"turnover": "13865092584.000",
"trade_status": 0,
"trade_session": 0
}
```
#### Depth
`WS` `push · cmd 102`
> **Quote Permission Required · Free**
> US stocks: US LV1 1-level bid/ask included free by default (pre-market, regular, after-hours, and overnight sessions).
> HK stocks: LV1 1-level bid/ask included by default; 10-level order book requires "LV2 Advanced Quotes - Plus (OpenAPI)".
> US options: no permission by default — purchase "OPRA US Options Quotes (OpenAPI)".
> _OpenAPI quote perms are separate from App/Web perms_
Real-time depth data push of the subscribed security.
```protobuf
message PushDepth {
string symbol = 1;
int64 sequence = 2;
repeated Depth ask = 3;
repeated Depth bid = 4;
}
```
##### Push Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | No | Security code, for example: AAPL.US |
| `sequence` | int64 | No | Sequence number |
| `ask` | object[] | No | Ask depth |
| `└ position` | int32 | No | Position |
| `└ price` | string | No | Price |
| `└ volume` | int64 | No | Volume |
| `└ order_num` | int64 | No | Number of orders |
| `bid` | object[] | No | Bid depth |
| `└ position` | int32 | No | Position |
| `└ price` | string | No | Price |
| `└ volume` | int64 | No | Volume |
| `└ order_num` | int64 | No | Number of orders |
##### Response JSON Example
```json
{
"symbol": "700.HK",
"sequence": 160808750000000,
"ask": [
{
"position": 1,
"price": "335.000",
"volume": 500,
"order_num": 1
}
],
"bid": [
{
"position": 1,
"price": "334.800",
"volume": 69400,
"order_num": 13
}
]
}
```
#### Brokers
`WS` `push · cmd 103`
> **Quote Permission Required · HK only · LV2 Advanced**
> HK-specific data: provides the top 40 bid/ask broker queues.
> No permission included by default — purchase "LV2 Advanced Quotes - Plus (OpenAPI)" in the Quote Store.
> _OpenAPI quote perms are separate from App/Web perms_
:::warning Longbridge HK / SG accounts only
This method is available to Longbridge HK / SG accounts only. It works with any supported symbol, including US stocks.
:::
Real-time brokers data push of the subscribed security.
```protobuf
message PushBrokers {
string symbol = 1;
int64 sequence = 2;
repeated Brokers ask_brokers = 3;
repeated Brokers bid_brokers = 4;
}
```
##### Push Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | No | Security code, for example: AAPL.US |
| `sequence` | int64 | No | Sequence number |
| `ask_brokers` | object[] | No | Ask brokers |
| `└ position` | int32 | No | Position |
| `└ broker_ids` | int32[] | No | Broker ID |
| `bid_brokers` | object[] | No | Bid brokers |
| `└ position` | int32 | No | Position |
| `└ broker_ids` | int32[] | No | Broker ID |
##### Response JSON Example
```json
{
"symbol": "700.HK",
"sequence": 160808750000000,
"ask_brokers": [
{
"position": 1,
"broker_ids": [
7358,
9057,
9028,
7364
]
}
],
"bid_brokers": [
{
"position": 1,
"broker_ids": [
6996,
5465,
8026,
8304,
4978
]
}
]
}
```
#### Trades
`WS` `push · cmd 104`
> **Quote Permission Required · Free**
> US stocks: US LV1 included free by default (last ~1,000 ticks across pre-market, regular, after-hours, and overnight sessions).
> HK stocks: LV1 included by default (last ~1,000 ticks).
> US options: no permission by default — purchase "OPRA US Options Quotes (OpenAPI)".
> _OpenAPI quote perms are separate from App/Web perms_
Real-time trades data push of the subscribed security.
```protobuf
message PushTrade {
string symbol = 1;
int64 sequence = 2;
repeated Trade trade = 3;
}
```
##### Push Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | No | Security code, for example: AAPL.US |
| `sequence` | int64 | No | Sequence number |
| `trades` | object[] | No | Trades data |
| `└ price` | string | No | Price |
| `└ volume` | int64 | No | Volume |
| `└ timestamp` | int64 | No | Time of trading |
| `└ trade_type` | string | No | Trade type |
| `└ direction` | int32 | No | Trade direction: 0 neutral, 1 down, 2 up |
| `└ trade_session` | int32 | No | Trade session, see TradeSession |
##### Response JSON Example
```json
{
"symbol": "700.HK",
"sequence": 160808750000000,
"trade": [
{
"price": "158.760",
"volume": 1,
"timestamp": 1651103979,
"trade_type": "I",
"direction": 0,
"trade_session": 2
}
]
}
```
#### Candlesticks
`WS` `push · cmd 105`
> **Quote Permission Required · Free**
> US stocks: US LV1 real-time quotes included free by default.
> HK stocks: LV1 real-time quotes included by default.
> Candlestick push requires the same permission as quote subscription.
> _OpenAPI quote perms are separate from App/Web perms_
Real-time candlestick (K-line) data push for subscribed securities. The callback fires whenever the current candlestick updates (Realtime mode) or when a candlestick period closes (Confirmed mode).
:::tip
This page covers the **push** API (`subscribe_candlesticks`). To pull historical candlestick data on demand, see [Candlestick - Pull](/quote/stocks/candlestick).
:::
```protobuf
message PushCandlestick {
string symbol = 1;
Period period = 2;
Candlestick candlestick = 3;
}
```
##### Push Fields
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | No | Security code, for example: AAPL.US |
| `period` | int32 | No | Candlestick period, see Period |
| `candlestick` | object | No | Candlestick data |
| `└ close` | string | No | Close price |
| `└ open` | string | No | Open price |
| `└ high` | string | No | High price |
| `└ low` | string | No | Low price |
| `└ volume` | int64 | No | Volume |
| `└ turnover` | string | No | Turnover |
| `└ timestamp` | int64 | No | Candlestick time (Unix timestamp) |
| `└ trade_session` | int32 | No | Trade session, see TradeSession |
##### Response JSON Example
```json
{
"symbol": "700.HK",
"period": 1,
"candlestick": {
"close": "162.500",
"open": "160.000",
"high": "163.000",
"low": "159.800",
"volume": 123456,
"turnover": "19987654.000",
"timestamp": 1651103700,
"trade_session": 0
}
}
```
## Fundamental
### Fundamentals
#### ETF Asset Allocation
`GET` `/v1/quote/etf-asset-allocation`
Get ETF asset allocation, grouped by element type: holdings, regional, asset class and industry.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | ETF symbol, e.g. `QQQ.US`. |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/etf-asset-allocation?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `info` | object[] | No | Asset allocation groups (one per element type) |
| `└ report_date` | string | No | Report date, e.g. `20260601` |
| `└ asset_type` | integer | No | Element type of this group (holdings / regional / asset class / industry) |
| `└ lists` | object[] | No | Elements in this group |
| `└ ∟ name` | string | No | Element name |
| `└ ∟ position_ratio` | string | No | Position ratio, e.g. `0.0861114` |
| `└ ∟ name_locales` | string | No | Localized name (raw string; see `name_locales_map` for the locale map). |
| `└ ∟ name_locales_map` | object | No | Localized names (locale → name, e.g. `zh-CN` → `英伟达`) |
| `└ ∟ ∟ en` | string | No | English name. |
| `└ ∟ ∟ zh-CN` | string | No | Simplified Chinese name. |
| `└ ∟ ∟ zh-HK` | string | No | Traditional Chinese name. |
| `└ ∟ code` | string | No | Security code (holdings only), e.g. `NVDA` |
| `└ ∟ symbol` | string | No | Security symbol (holdings only), e.g. `NVDA.US` |
| `└ ∟ holding_detail` | string | No | Holding detail (holdings only) |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"info": [
{
"report_date": "20260601",
"asset_type": "holdings",
"lists": [
{
"name": "NVIDIA",
"code": "NVDA",
"position_ratio": "0.0861114",
"symbol": "NVDA.US",
"name_locales_map": {
"zh-CN": "英伟达"
}
}
]
}
]
}
}
```
#### Institutional Rating Views Timeline
`GET` `/v1/quote/ratings/institutional`
Get the monthly institutional rating (buy/hold/sell) distribution timeline, newest first.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `AAPL.US` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/ratings/institutional?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `elist` | object[] | No | Monthly rating distribution list, newest first |
| `└ buy` | string | No | Number of Buy ratings |
| `└ over` | string | No | Number of Outperform ratings |
| `└ hold` | string | No | Number of Hold ratings |
| `└ under` | string | No | Number of Underperform ratings |
| `└ sell` | string | No | Number of Sell ratings |
| `└ total` | string | No | Total analyst count |
| `└ no_opinion` | string | No | Number of analysts with no opinion. |
| `└ date` | string | No | Unix timestamp (seconds) |
| `tlist` | object[] | No | Time-series list. |
| `└ date` | string | No | Unix timestamp (seconds) |
| `└ close` | string | No | Closing price. |
| `└ high_price` | string | No | High price. |
| `└ low_price` | string | No | Low price. |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"elist": [
{
"date": 1746057600,
"buy": "18",
"over": "5",
"hold": "17",
"under": "3",
"sell": "4",
"total": "51"
},
{
"date": 1743379200,
"buy": "17",
"over": "6",
"hold": "18",
"under": "3",
"sell": "5",
"total": "53"
}
]
}
}
```
#### Financial Report
`GET` `/v1/quote/financial-reports`
Fetch income statement, balance sheet, and cash flow statement for any public company.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `AAPL.US` |
| `kind` | string | Yes | Report type: `IncomeStatement`, `BalanceSheet`, `CashFlow`, `All` |
| `period` | string | Yes | Report period: `Annual`, `SemiAnnual`, `Q1`, `Q2`, `Q3`, `ThreeQ`, `QuarterlyFull` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/financial-reports?symbol=&kind=&period=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `list` | object | Yes | Report data grouped by kind (key: report type code, e.g. `IS`, `BS`, `CF`) |
| `title` | string | No | Indicator title |
| `short_title` | string | No | Short title |
| `currency` | string | No | Currency |
| `has_yoy` | boolean | No | Whether year-over-year data is available |
| `entry` | string | No | Entry identifier |
| `periods` | string[] | No | Available reporting periods |
| `accounts` | object[] | No | List of financial line items |
| `field` | string | Yes | Field identifier |
| `percent` | boolean | No | Whether the value is a percentage |
| `tip` | string | No | Tooltip description |
| `values` | object[] | No | Historical values by period |
| `period` | string | Yes | Period label (e.g. `FY 2024`) |
| `year` | integer | No | Fiscal year |
| `fp_end` | string | No | Period end timestamp |
| `value` | string | No | Reported value |
| `ratio` | string | No | Ratio value |
| `yoy` | string | No | Year-over-year growth rate |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"list": {
"IS": {
"indicators": [
{
"title": "Income Statement",
"short_title": "IS",
"currency": "USD",
"has_yoy": true,
"entry": "IS",
"periods": [
"FY2025",
"FY2024"
],
"accounts": [
{
"field": "EPS",
"name": "Earnings Per Share(USD)",
"percent": false,
"tip": "",
"values": [
{
"period": "FY 2025",
"year": 2025,
"fp_end": "1758945600",
"value": "7.46",
"ratio": "",
"yoy": "0.227"
}
]
}
]
}
]
}
}
}
}
```
#### Financial Report Snapshot
`GET` `/v1/quote/financials/earnings-snapshot`
Get an AI-generated earnings summary, revenue/EBIT/EPS forecast vs actual (beat/miss analysis), and key financial ratios.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `AAPL.US` |
| `report` | string | No | Report type: `qf` (quarterly) / `saf` (semi-annual) / `af` (annual) |
| `fiscal_year` | integer | No | Fiscal year, e.g. `2024` |
| `fiscal_period` | string | No | Fiscal period, e.g. `1` / `2` / `3` / `4` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/financials/earnings-snapshot?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `name` | string | No | Security name. |
| `ticker` | string | No | Ticker symbol without market suffix, e.g. `AAPL` |
| `currency` | string | No | Currency code |
| `report` | string | No | Report period code (e.g. `af` = annual) |
| `fiscal_year` | integer | No | Fiscal year |
| `fiscal_period` | string | No | Fiscal period number within the fiscal year |
| `opt_reports` | array | No | Optional available report periods |
| `fp_start` | string | No | Fiscal period start date in `YYYY.MM.DD` format |
| `fp_end` | string | No | Fiscal period end date in `YYYY.MM.DD` format |
| `report_desc` | string | No | AI-generated earnings summary |
| `fo_revenue` | object | No | Revenue forecast vs actual |
| `└ value` | string | No | Actual value |
| `└ yoy` | string | No | Year-over-year growth as percentage, e.g. `16.6` |
| `└ est_value` | string | No | Consensus estimate (may be empty) |
| `└ est_yoy` | string | No | Estimated year-over-year change. |
| `└ cmp` | string | No | Comparison value. |
| `└ cmp_desc` | string | No | Beat/miss description (may be empty) |
| `fo_ebit` | object | No | EBIT forecast vs actual |
| `└ value` | string | No | Actual value |
| `└ yoy` | string | No | Year-over-year growth as percentage, e.g. `16.6` |
| `└ est_value` | string | No | Consensus estimate (may be empty) |
| `└ est_yoy` | string | No | Estimated year-over-year change. |
| `└ cmp` | string | No | Comparison value. |
| `└ cmp_desc` | string | No | Beat/miss description (may be empty) |
| `fo_eps` | object | No | EPS forecast vs actual |
| `└ value` | string | No | Actual value |
| `└ yoy` | string | No | Year-over-year growth as percentage, e.g. `16.6` |
| `└ est_value` | string | No | Consensus estimate (may be empty) |
| `└ est_yoy` | string | No | Estimated year-over-year change. |
| `└ cmp` | string | No | Comparison value. |
| `└ cmp_desc` | string | No | Beat/miss description (may be empty) |
| `fr_roe_ttm` | string | No | ROE TTM as percentage, e.g. `141.47` |
| `fr_asset_turn_ttm` | string | No | Asset turnover TTM as percentage |
| `fr_profit_margin_ttm` | string | No | Net profit margin TTM as percentage |
| `fr_leverage_ttm` | string | No | Leverage TTM as percentage |
| `fr_total_assets` | object | No | Total assets |
| `└ value` | string | No | Actual value |
| `└ yoy` | string | No | Year-over-year growth as percentage, e.g. `16.6` |
| `└ est_value` | string | No | Consensus estimate (may be empty) |
| `└ est_yoy` | string | No | Estimated year-over-year change. |
| `└ cmp` | string | No | Comparison value. |
| `└ cmp_desc` | string | No | Beat/miss description (may be empty) |
| `fr_total_liability` | object | No | Total liabilities |
| `└ value` | string | No | Actual value |
| `└ yoy` | string | No | Year-over-year growth as percentage, e.g. `16.6` |
| `└ est_value` | string | No | Consensus estimate (may be empty) |
| `└ est_yoy` | string | No | Estimated year-over-year change. |
| `└ cmp` | string | No | Comparison value. |
| `└ cmp_desc` | string | No | Beat/miss description (may be empty) |
| `fr_debt_assets_ratio` | string | No | Debt-to-assets ratio as percentage |
| `fr_revenue` | object | No | Reported revenue |
| `└ value` | string | No | Actual value |
| `└ yoy` | string | No | Year-over-year growth as percentage, e.g. `16.6` |
| `└ est_value` | string | No | Consensus estimate (may be empty) |
| `└ est_yoy` | string | No | Estimated year-over-year change. |
| `└ cmp` | string | No | Comparison value. |
| `└ cmp_desc` | string | No | Beat/miss description (may be empty) |
| `fr_profit` | object | No | Reported net profit |
| `└ value` | string | No | Actual value |
| `└ yoy` | string | No | Year-over-year growth as percentage, e.g. `16.6` |
| `└ est_value` | string | No | Consensus estimate (may be empty) |
| `└ est_yoy` | string | No | Estimated year-over-year change. |
| `└ cmp` | string | No | Comparison value. |
| `└ cmp_desc` | string | No | Beat/miss description (may be empty) |
| `fr_profit_margin` | string | No | Net profit margin as percentage |
| `fr_operate_cash` | object | No | Operating cash flow |
| `└ value` | string | No | Actual value |
| `└ yoy` | string | No | Year-over-year growth as percentage, e.g. `16.6` |
| `└ est_value` | string | No | Consensus estimate (may be empty) |
| `└ est_yoy` | string | No | Estimated year-over-year change. |
| `└ cmp` | string | No | Comparison value. |
| `└ cmp_desc` | string | No | Beat/miss description (may be empty) |
| `fr_finance_cash` | object | No | Financing cash flow |
| `└ value` | string | No | Actual value |
| `└ yoy` | string | No | Year-over-year growth as percentage, e.g. `16.6` |
| `└ est_value` | string | No | Consensus estimate (may be empty) |
| `└ est_yoy` | string | No | Estimated year-over-year change. |
| `└ cmp` | string | No | Comparison value. |
| `└ cmp_desc` | string | No | Beat/miss description (may be empty) |
| `fr_invest_cash` | object | No | Investing cash flow |
| `└ value` | string | No | Actual value |
| `└ yoy` | string | No | Year-over-year growth as percentage, e.g. `16.6` |
| `└ est_value` | string | No | Consensus estimate (may be empty) |
| `└ est_yoy` | string | No | Estimated year-over-year change. |
| `└ cmp` | string | No | Comparison value. |
| `└ cmp_desc` | string | No | Beat/miss description (may be empty) |
| `market` | string | No | Market: `US`, `HK`, `CN`, `SG` |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"name": "Apple",
"ticker": "AAPL",
"fp_start": "2025.12.28",
"fp_end": "2026.03.28",
"currency": "USD",
"report_desc": "Summary: Apple (AAPL) revenue was 111.18B (+16.6%); EPS was 2.01 (+21.82%).",
"fo_revenue": {
"value": "111184000000.0000",
"yoy": "16.6",
"cmp_desc": "",
"est_value": ""
},
"fo_ebit": {
"value": "35885000000.0000",
"yoy": "21.28",
"cmp_desc": "",
"est_value": ""
},
"fo_eps": {
"value": "2.0100",
"yoy": "21.82",
"cmp_desc": "",
"est_value": ""
},
"fr_revenue": {
"value": "111184000000.0000",
"yoy": "16.6"
},
"fr_profit": {
"value": "29578000000.0000",
"yoy": "19.36"
},
"fr_roe_ttm": "141.4705",
"fr_profit_margin": "26.6027",
"fr_debt_assets_ratio": "71.3025"
}
}
```
#### Financial Consensus
`GET` `/v1/quote/financial-consensus-detail`
Get financial consensus estimates including revenue, EPS, and net income forecasts.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `TSLA.US` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/financial-consensus-detail?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `list` | object[] | No | List of consensus forecast periods |
| `└ fiscal_year` | integer | No | Fiscal year |
| `└ fiscal_period` | string | No | Fiscal period number within the fiscal year |
| `└ period_text` | string | No | Display period label (e.g. Q1 2027) |
| `└ details` | object[] | No | List of financial indicator details |
| `└ ∟ key` | string | No | Indicator key (e.g. `eps`, `revenue`) |
| `└ ∟ name` | string | No | Security name. |
| `└ ∟ description` | string | No | Full description |
| `└ ∟ estimate` | string | No | Consensus estimate |
| `└ ∟ is_released` | boolean | No | Whether actual has been released |
| `└ ∟ actual` | string | No | Actual reported value |
| `└ ∟ comp_value` | string | No | Comparison percentage value |
| `└ ∟ comp_desc` | string | No | Comparison description |
| `└ ∟ comp` | string | No | Comparison result (e.g. `beat`, `miss`) |
| `current_index` | integer | No | Index of the current period in opt_periods |
| `currency` | string | No | Reporting currency |
| `opt_periods` | array | No | Available period options |
| `current_period` | string | No | Current period code (e.g. `qf`) |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"currency": "USD",
"current_index": 3,
"current_period": "qf",
"opt_periods": [
"qf",
"af",
"saf"
],
"list": [
{
"fiscal_year": 2026,
"fiscal_period": "Q2 FY2026",
"period_text": "Q2 FY2026",
"details": [
{
"key": "revenue",
"name": "Revenue",
"estimate": "95000000000",
"actual": "",
"comp": "",
"comp_value": null,
"comp_desc": "",
"description": "",
"is_released": false
}
]
}
]
}
}
```
#### Forecast EPS
`GET` `/v1/quote/forecast-eps`
Get EPS forecasts and analyst consensus estimates.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `TSLA.US` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/forecast-eps?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `items` | object[] | No | List of EPS forecast periods |
| `└ forecast_eps_median` | string | No | Median EPS estimate |
| `└ forecast_eps_mean` | string | No | Mean EPS estimate |
| `└ forecast_eps_lowest` | string | No | Lowest EPS estimate |
| `└ forecast_eps_highest` | string | No | Highest EPS estimate |
| `└ institution_total` | integer | No | Total contributing institutions |
| `└ institution_up` | integer | No | Institutions revising up |
| `└ institution_down` | integer | No | Institutions revising down |
| `└ forecast_start_date` | string | No | Forecast period start date |
| `└ forecast_end_date` | string | No | Forecast period end date |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"items": [
{
"forecast_end_date": "1727827200",
"forecast_eps_highest": "3.71",
"forecast_eps_lowest": "2.37",
"forecast_eps_mean": "2.998",
"forecast_eps_median": "3.02",
"forecast_start_date": "1727827200",
"institution_down": 0,
"institution_total": 0,
"institution_up": 0
}
]
}
}
```
#### Valuations
`GET` `/v1/quote/valuation`
Get current valuation metrics (P/E, P/B, P/S, dividend yield) with 5-year historical context.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `AAPL.US` |
| `indicator` | string | No | Indicator filter: `pe`, `pb`, `ps`, `dvd_yld` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/valuation?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `metrics` | object | Yes | Valuation metrics map |
| `└ pe` | object | No | P/E ratio data |
| `└ ∟ current` | string | Yes | Current value |
| `└ ∟ high` | string | Yes | 5-year high |
| `└ ∟ low` | string | Yes | 5-year low |
| `└ ∟ median` | string | Yes | 5-year median |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"metrics": {
"pe": {
"current": "29.5",
"high": "35.2",
"low": "18.0",
"median": "26.0"
},
"pb": {
"current": "45.1",
"high": "50.0",
"low": "30.0",
"median": "42.0"
}
}
}
}
```
#### Valuation History
`GET` `/v1/quote/valuation/detail`
Get historical valuation metric time series (PE, PB, PS, dividend yield).
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `AAPL.US` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/valuation/detail?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `overview` | object | Yes | Current-valuation summary |
| `overview.metrics` | object | No | Metrics map keyed by indicator (pe/pb/ps) |
| `overview.metrics.pe` | object | No | Metric block for the requested indicator |
| `overview.metrics.pe.metric` | string | No | Current value, e.g. 14.85x |
| `overview.metrics.pe.industry_median` | string | No | Industry median |
| `overview.metrics.pe.desc` | string | No | Human-readable summary |
| `overview.indicator` | string | No | Requested indicator key |
| `overview.range` | integer | No | Lookback range in years |
| `overview.date` | string | No | As-of date |
| `overview.ccy_symbol` | string | No | Currency symbol |
| `history` | object | Yes | Historical time series |
| `history.metrics.pe` | object | No | History block for the indicator |
| `history.metrics.pe.low` | string | No | Historical low |
| `history.metrics.pe.median` | string | No | Historical median |
| `history.metrics.pe.high` | string | No | Historical high |
| `history.metrics.pe.list` | object[] | No | Time-series points |
| `history.metrics.pe.list[].timestamp` | string | No | Unix seconds (string) |
| `history.metrics.pe.list[].value` | string | No | Value at this point |
| `peers` | object | No | Industry peers comparison |
| `peers.pe.industry_median` | string | No | Peer-group median |
| `peers.pe.list` | object[] | No | Peer companies |
| `peers.pe.list[].symbol` | string | No | Security symbol, e.g. 9626.HK |
| `peers.pe.list[].name` | string | No | Security name |
| `peers.pe.list[].value` | string | No | Metric value |
| `layouts` | object | No | Distribution buckets for charting |
| `symbols` | object | No | Map keyed by symbol -> { name, market_cap } |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"history": {
"metrics": {
"pe": {
"desc": "P/E Ratio",
"high": "35.2",
"low": "18.1",
"median": "26.5",
"list": [
{
"timestamp": "1622520000",
"value": "28.5"
}
]
},
"pb": null,
"ps": null
}
}
}
}
```
#### Valuation Comparison
`GET` `/v1/quote/compare/valuation`
Compare valuation metrics (PE/PB/PS/market cap/close price) across multiple stocks. When no comparison symbols are provided, the server automatically selects peers from the same industry.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Primary security symbol, e.g. `AAPL.US` |
| `currency` | string | Yes | Result currency: `USD`, `HKD`, or `CNY` |
| `comparison_symbols` | array | No | Symbols to compare against; if omitted, the server auto-selects industry peers |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/compare/valuation?symbol=¤cy=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `list` | object[] | No | Valuation comparison list |
| `└ symbol` | string | No | Security symbol |
| `└ name` | string | No | Security name |
| `└ market` | string | No | Market: `US`, `HK`, `CN`, `SG` |
| `└ currency` | string | No | Currency of the values |
| `└ price_close` | string | No | Latest closing price |
| `└ market_value` | string | No | Market capitalisation |
| `└ volume` | string | No | Volume. |
| `└ pe` | string | No | P/E ratio (TTM) |
| `└ pb` | string | No | P/B ratio |
| `└ ps` | string | No | P/S ratio (TTM) |
| `└ div_yld` | string | No | Dividend yield (%) |
| `└ roa` | string | No | Return on assets (ROA). |
| `└ roe` | string | No | Return on equity (%) |
| `└ turnover` | string | No | Turnover. |
| `└ net_margin` | string | No | Net profit margin |
| `└ leverage` | string | No | Leverage ratio. |
| `└ liabilities_assets` | string | No | Liabilities-to-assets ratio. |
| `└ eps` | string | No | Earnings per share (TTM) |
| `└ sales_ps` | string | No | Sales per share. |
| `└ bps` | string | No | Book value per share |
| `└ dps` | string | No | Dividends per share (TTM) |
| `└ five_y_avg_dps` | string | No | 5-year average DPS |
| `└ div_payout_ratio` | string | No | Dividend payout ratio |
| `└ assets` | string | No | Total assets |
| `└ liabilities` | string | No | Total liabilities. |
| `└ sales` | string | No | Sales / revenue. |
| `└ net_income` | string | No | Net income |
| `└ history` | object[] | No | Historical valuation time series |
| `└ ∟ date` | string | No | Date as Unix timestamp (seconds) |
| `└ ∟ pe` | string | No | P/E ratio (TTM) |
| `└ ∟ pb` | string | No | P/B ratio |
| `└ ∟ ps` | string | No | P/S ratio (TTM) |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"list": [
{
"symbol": "AAPL.US",
"name": "Apple Inc.",
"currency": "USD",
"market_value": "3241500000000",
"price_close": "213.49",
"pe": "32.15",
"pb": "50.21",
"ps": "8.04",
"roe": "136.45",
"eps": "6.43",
"bps": "4.38",
"dps": "0.99",
"div_yld": "0.46",
"assets": "371082000000",
"history": [
{
"date": "1622520000",
"pe": "37.56",
"pb": "30.16",
"ps": "6.41"
},
{
"date": "1625112000",
"pe": "41.49",
"pb": "35.64",
"ps": "6.60"
}
]
},
{
"symbol": "MSFT.US",
"name": "Microsoft",
"currency": "USD",
"market_value": "3085000000000",
"price_close": "415.32",
"pe": "35.42",
"pb": "12.87",
"ps": "12.61",
"roe": "38.21",
"eps": "11.72",
"bps": "32.28",
"dps": "3.32",
"div_yld": "0.80",
"assets": "512163000000",
"history": [
{
"date": "1622520000",
"pe": "33.12",
"pb": "11.94",
"ps": "11.84"
}
]
}
]
}
}
```
#### Industry Valuation
`GET` `/v1/quote/industry-valuation-comparison`
Get peer valuation comparison within the same industry.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `TSLA.US` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/industry-valuation-comparison?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `list` | object[] | No | List of peer companies |
| `└ symbol` | string | No | Security symbol |
| `└ name` | string | No | Company name |
| `└ market` | string | No | Market: `US`, `HK`, `CN`, `SG` |
| `└ currency` | string | No | Reporting currency |
| `└ price_close` | string | No | Latest closing price |
| `└ market_value` | string | No | Market capitalisation |
| `└ volume` | string | No | Volume. |
| `└ pe` | string | No | Price-to-Earnings ratio |
| `└ pb` | string | No | P/B ratio |
| `└ ps` | string | No | P/S ratio (TTM) |
| `└ div_yld` | string | No | Dividend yield |
| `└ roa` | string | No | Return on assets (ROA). |
| `└ roe` | string | No | Return on equity (%) |
| `└ turnover` | string | No | Turnover. |
| `└ net_margin` | string | No | Net profit margin |
| `└ leverage` | string | No | Leverage ratio. |
| `└ liabilities_assets` | string | No | Liabilities-to-assets ratio. |
| `└ eps` | string | No | Earnings per share |
| `└ sales_ps` | string | No | Sales per share. |
| `└ bps` | string | No | Book value per share |
| `└ dps` | string | No | Dividends per share |
| `└ five_y_avg_dps` | string | No | 5-year average DPS |
| `└ div_payout_ratio` | string | No | Dividend payout ratio |
| `└ assets` | string | No | Total assets |
| `└ liabilities` | string | No | Total liabilities. |
| `└ sales` | string | No | Sales / revenue. |
| `└ net_income` | string | No | Net income |
| `└ history` | object[] | No | Historical valuation data |
| `└ ∟ date` | string | No | Date (e.g. `2026.05.13`) |
| `└ ∟ pe` | string | No | Price-to-Earnings ratio |
| `└ ∟ pb` | string | No | P/B ratio |
| `└ ∟ ps` | string | No | P/S ratio (TTM) |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"list": [
{
"symbol": "AAPL.US",
"name": "Apple Inc.",
"market": "US",
"currency": "USD",
"pe": "28.50",
"pb": "45.2",
"ps": "7.8",
"eps": "6.08",
"bps": "4.50"
}
]
}
}
```
#### Industry Valuation Distribution
`GET` `/v1/quote/industry-valuation-distribution`
Get the valuation distribution histogram for the symbol's industry.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `AAPL.US` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/industry-valuation-distribution?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `pe` | object | No | P/E ratio distribution |
| `└ low` | string | No | 5-year low |
| `└ high` | string | No | 5-year high |
| `└ median` | string | No | 5-year median |
| `└ value` | string | No | Indicator value as a string; empty when unavailable. |
| `└ ranking` | string | No | Ranking position. |
| `└ rank_index` | string | No | Rank index (position). |
| `└ rank_total` | string | No | Total number in the ranking. |
| `pb` | object | No | P/B ratio distribution |
| `└ low` | string | No | 5-year low |
| `└ high` | string | No | 5-year high |
| `└ median` | string | No | 5-year median |
| `└ value` | string | No | Indicator value as a string; empty when unavailable. |
| `└ ranking` | string | No | Ranking position. |
| `└ rank_index` | string | No | Rank index (position). |
| `└ rank_total` | string | No | Total number in the ranking. |
| `ps` | object | No | P/S ratio distribution |
| `└ low` | string | No | 5-year low |
| `└ high` | string | No | 5-year high |
| `└ median` | string | No | 5-year median |
| `└ value` | string | No | Indicator value as a string; empty when unavailable. |
| `└ ranking` | string | No | Ranking position. |
| `└ rank_index` | string | No | Rank index (position). |
| `└ rank_total` | string | No | Total number in the ranking. |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"pe": {
"value": "28.5",
"high": "120.0",
"low": "5.0",
"median": "22.0",
"ranking": "35",
"rank_index": "12",
"rank_total": "30"
},
"pb": {
"value": "45.2",
"high": "200.0",
"low": "1.0",
"median": "8.0",
"ranking": "85",
"rank_index": "25",
"rank_total": "30"
},
"ps": {
"value": "7.8",
"high": "30.0",
"low": "0.5",
"median": "4.0",
"ranking": "70",
"rank_index": "21",
"rank_total": "30"
}
}
}
```
#### Industry Ranking
`GET` `/v1/quote/industry/rank`
Get the industry ranking list by market and indicator. The returned Counter ID can be passed directly to `industry_peers` to explore the sub-sector hierarchy.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `market` | string | Yes | Market code: `US` / `HK` / `CN` / `SG` |
| `indicator` | string | Yes | Ranking indicator: `leading-gainer` / `today-trend` / `popularity` / `market-cap` / `revenue` / `revenue-growth` / `net-profit` / `net-profit-growth` |
| `sort_type` | string | Yes | Sort mode: `single` / `multi` |
| `limit` | integer | Yes | Number of results to return, default 20 |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/industry/rank?market=&indicator=&sort_type=&limit=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `items` | object[] | No | Ranked group list |
| `└ lists` | object[] | No | Industry item list |
| `└ ∟ name` | string | No | Industry name |
| `└ ∟ symbol` | string | No | Industry symbol, usable as `symbol` in `industry_peers` (e.g. `IN20245.HK`). |
| `└ ∟ chg` | string | No | Daily change (decimal) |
| `└ ∟ leading_name` | string | No | Leading stock name |
| `└ ∟ leading_ticker` | string | No | Leading stock ticker |
| `└ ∟ leading_chg` | string | No | Leading stock daily change (decimal) |
| `└ ∟ value_name` | string | No | Indicator label (may be empty depending on indicator type) |
| `└ ∟ value_data` | string | No | Indicator value (may be empty) |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"items": [
{
"lists": [
{
"name": "Technology",
"symbol": "IN00258.US",
"chg": "0.0231",
"leading_name": "NVIDIA",
"leading_ticker": "NVDA.US",
"leading_chg": "0.0512",
"value_name": "",
"value_data": ""
}
]
}
]
}
}
```
#### Industry Peer Hierarchy
`GET` `/v1/quote/industries/peers`
Get the hierarchical sub-sector tree for an industry group, including stock count, daily change, and YTD change at each node. Counter IDs come from `industry_rank`.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Industry symbol, e.g. `IN20245.HK`. |
| `market` | string | Yes | Market code: `US` / `HK` / `CN` / `SG` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/industries/peers?symbol=&market=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `top` | object | No | Top-level industry info |
| `chain` | object | No | Industry hierarchy root node |
| `market` | string | No | Market code |
| `symbol` | string | No | Sector symbol (present on the root node; empty string on child nodes). |
| `stock_num` | integer | No | Number of stocks in this sector |
| `chg` | string | No | Daily change (decimal; may be empty string) |
| `ytd_chg` | string | No | Year-to-date change (decimal; may be empty string) |
| `next` | object[] | No | Child sector list with the same structure (recursive) |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"top": {
"name": "All Industries",
"market": "US"
},
"chain": {
"name": "Technology",
"symbol": "IN00258.US",
"stock_num": 542,
"chg": "0.0231",
"ytd_chg": "0.0875",
"next": [
{
"name": "Online Consumer Electronics Retail",
"symbol": "",
"stock_num": 4,
"chg": "0.0268",
"ytd_chg": "-0.1869",
"next": []
}
]
}
}
}
```
#### Company Profile
`GET` `/v1/quote/comp-overview`
Get a company's profile information including founding year, employee count, headquarters, and description.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `AAPL.US` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/comp-overview?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `name` | string | No | Security name. |
| `company_name` | string | No | Full company name |
| `founded` | string | No | Founding year |
| `listing_date` | string | No | IPO listing date |
| `market` | string | No | Listing exchange |
| `ticker` | string | No | Ticker symbol |
| `region` | string | No | Region |
| `address` | string | No | Registered address |
| `website` | string | No | Company website |
| `icon` | string | No | Stock icon URL |
| `issue_price` | string | No | IPO issue price |
| `shares_offered` | string | No | Total shares offered |
| `chairman` | string | No | Chairman |
| `secretary` | string | No | Company secretary |
| `audit_inst` | string | No | Audit institution |
| `category` | string | No | Company category |
| `year_end` | string | No | Fiscal year-end |
| `employees` | string | No | Number of employees |
| `Phone` | string | No | Phone number |
| `fax` | string | No | Fax number |
| `email` | string | No | Contact email |
| `legal_repr` | string | No | Legal representative |
| `manager` | string | No | CEO / General manager |
| `bus_license` | string | No | Business license number |
| `accounting_firm` | string | No | Accounting firm |
| `securities_rep` | string | No | Securities representative |
| `legal_counsel` | string | No | Legal counsel |
| `office_address` | string | No | Office address |
| `zip_code` | string | No | Postal code |
| `ads_ratio` | string | No | ADS ratio |
| `profile` | string | No | Business description |
| `sector` | integer | No | Industry sector |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"company_name": "Apple Inc.",
"name": "Apple",
"ticker": "AAPL",
"market": "NasdaqGS",
"founded": "1976",
"employees": "166000",
"manager": "Timothy D. Cook",
"website": "www.apple.com",
"phone": "(408) 996-1010",
"address": "One Apple Park Way, Cupertino, California, United States",
"profile": "Apple Inc. designs, manufactures, and markets smartphones, personal computers, tablets, wearables, a...",
"region": "US",
"sector": 0,
"year_end": "September 27",
"icon": "https://assets.lbkrs.com/ticker/ST/US/AAPL.png"
}
}
```
#### Executives
`GET` `/v1/quote/company-professionals`
Get the list of key executives (CEO, CFO, etc.) for a company.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `AAPL.US` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/company-professionals?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `professional_list` | object[] | No | List of executive groups |
| `└ professionals` | array | No | List of executives |
| `└ forward_url` | string | No | Company executives page URL |
| `└ total` | integer | No | Total number of executives |
| `└ symbol` | string | No | Security symbol |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"professional_list": [
{
"forward_url": "https://longbridge.com/wiki/stocks/ST.US.AAPL#company-manager",
"professionals": [
{
"biography": "Tim Cook is the CEO of Apple Inc.",
"id": "12345",
"name": "Timothy D. Cook",
"name_en": "Timothy D. Cook",
"name_zhcn": "蒂姆·库克",
"photo": "https://cdn.example.com/timcook.jpg",
"title": "Chief Executive Officer",
"wiki_url": "https://en.wikipedia.org/wiki/Tim_Cook"
}
],
"symbol": "AAPL.US",
"total": 9
}
]
}
}
```
#### Corporate Actions
`GET` `/v1/quote/company-act`
Get corporate action history (splits, mergers, spin-offs, rights issues) for a security.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `AAPL.US` |
| `start_date` | string | No | Start date in `YYYY-MM-DD` format |
| `end_date` | string | No | End date in `YYYY-MM-DD` format |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/company-act?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `items` | object[] | Yes | Corporate action list |
| `└ id` | string | No | Action ID |
| `└ act_desc` | string | No | Action description |
| `└ act_type` | string | No | Action type category |
| `└ action` | string | No | Action code (e.g. `DividendExDate`) |
| `└ date` | string | No | Event date (YYYYMMDD) |
| `└ date_str` | string | No | Short display date (MM.DD) |
| `└ date_type` | string | No | Date type label (e.g. Payment Date) |
| `└ date_zone` | string | No | Time zone (e.g. EST) |
| `└ delay_content` | string | No | Delay content description |
| `└ is_delay` | boolean | No | Whether the event is delayed |
| `└ live` | boolean | No | Whether currently live |
| `└ recent` | boolean | No | Whether this is a recent event |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"items": [
{
"id": "622620",
"action": "DividendExDate",
"act_type": "Distribution Plan",
"act_desc": "Cash dividend 0.27 USD",
"date": "20260514",
"date_str": "05.14",
"date_type": "Payment Date",
"date_zone": "EST",
"delay_content": "",
"is_delay": false,
"recent": false,
"live": null
}
]
}
}
```
#### Investment Relations
`GET` `/v1/quote/invest-relations`
Get investment relations including parent company, subsidiaries, and major holdings.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `700.HK` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/invest-relations?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `invest_securities` | object[] | No | List of investment holdings |
| `└ company_id` | string | No | Company ID |
| `└ company_name` | string | No | Display company name |
| `└ company_name_zhcn` | string | No | Chinese company name |
| `└ company_name_en` | string | No | English company name |
| `└ symbol` | string | No | Security symbol |
| `└ percent_of_shares` | string | No | Ownership percentage |
| `└ shares_value` | string | No | Value of shares held |
| `└ shares_rank` | string | No | Rank by shares held |
| `└ currency` | string | No | Currency |
| `forward_url` | string | No | Company investment relations page URL |
| `total` | integer | No | Total number of matching stocks. |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"forward_url": "https://longbridge.com/wiki/stocks/ST.HK.700#invest",
"invest_securities": [
{
"symbol": "HUYA.US",
"company_id": "12345",
"company_name": "Huya Inc.",
"company_name_en": "Huya Inc.",
"company_name_zhcn": "虎牙直播",
"currency": "USD",
"percent_of_shares": "19.00",
"shares_rank": "1",
"shares_value": "19000000"
}
]
}
}
```
#### Operating Metrics
`GET` `/v1/quote/operatings`
:::warning Longbridge HK / SG accounts only
This method is available to Longbridge HK / SG accounts only. It works with any supported symbol, including US stocks.
:::
Get operating metrics and financial indicator summaries by report period.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `AAPL.US` |
| `period` | string | No | Report period filter, e.g. `q1`, `q2`, `q3`, `q4`, `annual` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/operatings?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `list` | object[] | No | List of operating summary reports |
| `└ id` | string | No | Internal report ID |
| `└ report` | string | No | Report period code (e.g. `af` = annual) |
| `└ title` | string | No | Report title |
| `└ txt` | string | No | Management discussion text |
| `└ latest` | boolean | No | Whether this is the most recent report |
| `└ web_url` | string | No | URL to the full report page |
| `└ keywords` | array | No | Keywords. |
| `└ financial` | object | No | Key financial metrics |
| `└ ∟ symbol` | string | No | Security symbol |
| `└ ∟ name` | string | No | Security name. |
| `└ ∟ region` | string | No | Market region |
| `└ ∟ code` | string | No | Ticker code |
| `└ ∟ currency` | string | No | Reporting currency |
| `└ ∟ report` | string | No | Report period code (e.g. `af` = annual) |
| `└ ∟ report_txt` | string | No | Period label (e.g. `FY2024`, `Q1 2024`) |
| `└ ∟ indicators` | object[] | No | Financial indicators |
| `└ ∟ ∟ field_name` | string | No | Field name key (e.g. `operating_revenue`) |
| `└ ∟ ∟ indicator_name` | string | No | Display name |
| `└ ∟ ∟ indicator_value` | string | No | Formatted value |
| `└ ∟ ∟ yoy` | string | No | Year-over-year change rate |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"list": [
{
"id": "12345",
"report": "af",
"title": "FY2025 Annual Report Summary",
"txt": "Management discussion...",
"latest": true,
"web_url": "https://longbridge.com/wiki/...",
"financial": {
"code": "700",
"currency": "HKD",
"name": "Tencent",
"region": "HK",
"report": "af",
"indicators": [
{
"field_name": "operating_revenue",
"indicator_name": "Revenue",
"indicator_value": "678.6B",
"yoy": "0.0800"
}
]
}
}
]
}
}
```
#### Buyback
`GET` `/v1/quote/buy-backs`
Get share buyback data including historical buyback amounts and ratios.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `AAPL.US` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/buy-backs?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `recent_buybacks` | object | No | Trailing 12-month buyback summary |
| `└ net_buyback_ttm` | string | No | Net buyback (trailing 12 months) |
| `└ net_buyback_yield_ttm` | string | No | Buyback yield (trailing 12 months) |
| `└ currency` | string | No | Currency |
| `buyback_history` | object[] | No | Annual buyback history |
| `└ fiscal_year` | string | No | Fiscal year |
| `└ fiscal_year_range` | string | No | Fiscal year date range |
| `└ net_buyback` | string | No | Net buyback amount |
| `└ net_buyback_yield` | string | No | Buyback yield |
| `└ net_buyback_growth_rate` | string | No | Buyback growth rate |
| `└ currency` | string | No | Currency |
| `└ total_shareholder_yield` | string | No | Total shareholder yield. |
| `└ dividend` | string | No | Dividend per share. |
| `└ dividend_yield` | string | No | Dividend yield. |
| `└ dividend_growth_rate` | string | No | Dividend growth rate. |
| `└ dividend_payout_ratio` | string | No | Dividend payout ratio. |
| `└ dividend_to_cashflow_ratio` | string | No | Dividend-to-cashflow ratio. |
| `└ net_buyback_payout_ratio` | string | No | Buyback payout ratio |
| `└ net_buyback_to_cashflow_ratio` | string | No | Buyback to free cash flow ratio |
| `buyback_ratios` | object[] | No | Buyback ratio history |
| `└ fiscal_year` | string | No | Fiscal year |
| `└ fiscal_year_range` | string | No | Fiscal year date range |
| `└ net_buyback_payout_ratio` | string | No | Buyback payout ratio |
| `└ net_buyback_to_cashflow_ratio` | string | No | Buyback to free cash flow ratio |
| `└ total_shareholder_yield` | string | No | Total shareholder yield. |
| `└ dividend` | string | No | Dividend per share. |
| `└ dividend_yield` | string | No | Dividend yield. |
| `└ dividend_growth_rate` | string | No | Dividend growth rate. |
| `└ dividend_payout_ratio` | string | No | Dividend payout ratio. |
| `└ dividend_to_cashflow_ratio` | string | No | Dividend-to-cashflow ratio. |
| `└ net_buyback` | string | No | Net buyback amount |
| `└ net_buyback_yield` | string | No | Buyback yield |
| `└ net_buyback_growth_rate` | string | No | Buyback growth rate |
| `└ currency` | string | No | Currency |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"buyback_history": [
{
"fiscal_year": "FY2024",
"fiscal_year_range": "2024-01-01~2024-12-31",
"net_buyback": "94949000000",
"net_buyback_yield": "0.0241",
"net_buyback_growth_rate": "-0.1233"
}
],
"buyback_ratios": [
{
"net_buyback_payout_ratio": "0.9502",
"net_buyback_to_cashflow_ratio": "0.8821"
}
],
"recent_buybacks": {
"currency": "USD",
"net_buyback_ttm": "94949000000",
"net_buyback_yield_ttm": "0.0241"
}
}
}
```
#### Dividends
`GET` `/v1/quote/dividends`
Get dividend history and upcoming dividend announcements for a security.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `AAPL.US` |
| `start_date` | string | No | Start date in `YYYY-MM-DD` format |
| `end_date` | string | No | End date in `YYYY-MM-DD` format |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/dividends?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `list` | object[] | No | Dividend records |
| `└ id` | string | No | Dividend event ID |
| `└ desc` | string | No | Dividend description |
| `└ symbol` | string | No | Security symbol |
| `└ record_date` | string | No | Record date |
| `└ ex_date` | string | No | Ex-dividend date |
| `└ payment_date` | string | No | Payment date |
| `└ dividend_summary` | object | No | Dividend summary. |
| `└ ∟ title` | string | No | Topic title |
| `└ ∟ desc` | string | No | Dividend description |
| `total` | string | No | Total number of matching stocks. |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"list": [
{
"id": "12345",
"symbol": "AAPL.US",
"ex_date": "2026-02-07",
"payment_date": "2026-02-13",
"record_date": "2026-02-10",
"desc": "Cash dividend 0.25 USD"
}
]
}
}
```
#### Dividend Detail
`GET` `/v1/quote/dividends/details`
Get detailed dividend information including declared, ex-dividend, and payment dates.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `AAPL.US` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/dividends/details?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `list` | object[] | No | List of dividend records |
| `└ desc` | string | No | Dividend description |
| `└ record_date` | string | No | Record date (YYYY-MM-DD) |
| `└ ex_date` | string | No | Ex-dividend date (YYYY-MM-DD) |
| `└ payment_date` | string | No | Payment date (YYYY-MM-DD) |
| `└ symbol` | string | No | Security symbol |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"list": [
{
"id": "12345",
"symbol": "AAPL.US",
"ex_date": "2026-02-07",
"payment_date": "2026-02-13",
"record_date": "2026-02-10",
"desc": "Cash dividend 0.25 USD"
}
]
}
}
```
#### Shareholders
`GET` `/v1/quote/shareholders`
Get the top institutional and individual shareholders of a company.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `AAPL.US` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/shareholders?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `shareholder_list` | object[] | No | List of shareholders |
| `└ shareholder_id` | string | No | Shareholder ID |
| `└ shareholder_name` | string | No | Shareholder name |
| `└ percent_of_shares` | string | No | Percentage of shares held |
| `└ shares_changed` | string | No | Change in shares held |
| `└ report_date` | string | No | Report date |
| `└ stocks` | array | No | Associated stocks |
| `└ institution_type` | string | No | Institution type |
| `total` | integer | No | Total number of shareholders |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"forward_url": "",
"total": 33,
"shareholder_list": [
{
"shareholder_name": "Timothy D. Cook",
"percent_of_shares": "2.84",
"institution_type": "",
"report_date": "2026-04-21",
"shareholder_id": "0",
"shares_changed": "0",
"stocks": []
}
]
}
}
```
#### Top Shareholders
`GET` `/v1/quote/shareholders/top`
Get the top 20 major shareholders (institutional, individual, and insider) for a listed company, with support for multi-period comparison. `object_id` can be passed to `shareholder_detail` to retrieve full holding history.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `AAPL.US` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/shareholders/top?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `periods` | array | No | Available reporting periods |
| `info` | object[] | No | Shareholder data per reporting period |
| `└ period` | string | No | Reporting period label (e.g. `Latest`) |
| `└ share_holders` | object[] | No | List of shareholders (up to 20) |
| `└ ∟ object_id` | string | No | Unique shareholder ID; pass to `shareholder_detail` |
| `└ ∟ name` | string | No | Shareholder name |
| `└ ∟ shares_held` | string | No | Number of shares held |
| `└ ∟ percent_shares_held` | string | No | Ownership percentage, including `%` sign (e.g. `9.71%`) |
| `└ ∟ shares_changed` | string | No | Net share count change (positive = bought, negative = sold) |
| `└ ∟ percent_shares_changed` | string | No | Change in ownership percentage, including `%` sign |
| `└ ∟ filing_date` | string | No | Filing date |
| `└ ∟ period` | string | No | Reporting period label (e.g. `Latest`) |
| `└ ∟ title` | string | No | Shareholder type (Institution / Individual / Insider) |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"info": [
{
"period": "Latest",
"share_holders": [
{
"object_id": "148057",
"name": "The Vanguard Group, Inc.",
"title": "",
"shares_held": "1426283914.00",
"percent_shares_held": "9.71%",
"percent_shares_changed": "0.01%",
"shares_changed": "0.00",
"period": "Latest",
"filing_date": "2025/12/31"
},
{
"object_id": "452583",
"name": "BlackRock, Inc.",
"title": "",
"shares_held": "1138572603.00",
"percent_shares_held": "7.75%",
"percent_shares_changed": "-0.06%",
"shares_changed": "-10565359.00",
"period": "Latest",
"filing_date": "2026/03/31"
}
]
}
]
}
}
```
#### Shareholder Detail
`GET` `/v1/quote/shareholders/holding`
Get holding history and trade details for a specific shareholder. The `object_id` comes from the `shareholder_top` response.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `AAPL.US` |
| `object_id` | integer | Yes | Shareholder ID from `shareholder_top` `object_id` field |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/shareholders/holding?symbol=&object_id=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `title` | string | No | Shareholder title / type |
| `avatar` | string | No | Avatar URL |
| `owner_source` | string | No | Shareholder type: `Company`, `Institution`, `Person`, `Insider` |
| `holding_periods` | string[] | No | Available holding periods |
| `holding_details` | object[] | No | Holding detail records |
| `holding_summary` | object[] | No | Holding summary records |
| `trading_periods` | string[] | No | Available trading periods (e.g. `Past 1 Month`, `Past 3 Months`) |
| `tradings` | object[] | No | Trade aggregates per period |
| `└ period` | string | No | Period label (e.g. `Past 1 Month`) |
| `└ accum_buy` | string | No | Cumulative shares bought in this period |
| `└ accum_sell` | string | No | Cumulative shares sold in this period |
| `└ net_buy` | string | No | Net shares bought (buy minus sell) in this period |
| `└ trading_details` | object[] | No | Individual transactions within the period |
| `└ ∟ trading_date` | string | No | Trade date |
| `└ ∟ trading_shares` | string | No | Number of shares traded |
| `└ ∟ trading_price` | string | No | Trade price |
| `└ ∟ trading_type` | string | No | Trade direction: `Buy` or `Sell` |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"name": "The Vanguard Group, Inc.",
"title": "",
"avatar": "",
"owner_source": "Institution",
"holding_periods": [],
"holding_details": [],
"holding_summary": [],
"trading_periods": [
"Past 1 Month",
"Past 3 Months",
"Past 1 Year",
"Past 3 Years"
],
"tradings": [
{
"period": "Past 1 Month",
"accum_buy": "8500000.00",
"accum_sell": "2687264.00",
"net_buy": "5812736.00",
"trading_details": [
{
"trading_date": "2025-12-18",
"trading_shares": "5200000",
"trading_price": "248.12",
"trading_type": "Buy"
}
]
}
]
}
}
```
#### Fund Holdings
`GET` `/v1/quote/fund-holders`
Get the list of funds that hold a given security, with the number of shares and ownership percentage.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `AAPL.US` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/fund-holders?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `lists` | object[] | No | List of fund holders |
| `└ symbol` | string | No | Fund symbol |
| `└ name` | string | No | Fund name |
| `└ code` | string | No | Fund code |
| `└ currency` | string | No | Currency |
| `└ position_ratio` | string | No | Position ratio (%) |
| `└ report_date` | string | No | Report date |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"lists": [
{
"symbol": "TSLT.US",
"code": "TSLT",
"name": "2x Long TSLA ETF",
"position_ratio": "101.02",
"report_date": "2026-05-07",
"currency": "USD"
}
]
}
}
```
#### Institution Rating
`GET` `/v1/quote/institution-rating-latest`
Get analyst institution rating snapshot (rating distribution and average target price).
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `TSLA.US` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/institution-rating-latest?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `evaluate` | object | No | Analyst rating distribution. |
| `└ buy` | integer | No | Number of Buy ratings. |
| `└ over` | integer | No | Number of Overweight ratings. |
| `└ hold` | integer | No | Number of Hold ratings. |
| `└ under` | integer | No | Number of Underweight ratings. |
| `└ sell` | integer | No | Number of Sell ratings. |
| `└ total` | integer | No | Total number of ratings. |
| `└ start_date` | string | No | Statistics start time (Unix seconds). |
| `└ end_date` | string | No | Statistics end time (Unix seconds). |
| `└ no_opinion` | integer | No | Number of analysts with no opinion. |
| `target` | object | No | Target-price consensus. |
| `└ highest_price` | string | No | Highest target price. |
| `└ lowest_price` | string | No | Lowest target price. |
| `└ prev_close` | string | No | Previous close price. |
| `└ start_date` | string | No | Statistics start time (Unix seconds). |
| `└ end_date` | string | No | Statistics end time (Unix seconds). |
| `industry_id` | integer | No | Industry ID. |
| `industry_name` | string | No | Industry name. |
| `industry_rank` | integer | No | The security's rank within its industry. |
| `industry_total` | integer | No | Number of securities in the industry. |
| `industry_mean` | integer | No | Industry mean rating rank. |
| `industry_median` | integer | No | Industry median rating rank. |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"latest": {
"evaluate": {
"buy": 18,
"hold": 17,
"sell": 4,
"no_opinion": 4,
"over": 5,
"under": 3,
"total": 51,
"start_date": "1778198400",
"end_date": "0"
},
"industry_id": 87676,
"industry_mean": 10,
"industry_median": 4,
"industry_name": "Automobiles",
"industry_rank": 1,
"industry_total": 30,
"target": {
"highest_price": "600.000",
"lowest_price": "123.000",
"prev_close": "428.35",
"start_date": "1778198400",
"end_date": "0"
}
},
"summary": {
"ccy_symbol": "$",
"change": "0",
"recommend": "Buy",
"updated_at": "1778198400",
"evaluate": {
"buy": 18,
"hold": 17,
"sell": 4
},
"target": {
"average_target": "350.00",
"highest_price": "600.000",
"lowest_price": "123.000"
}
}
}
}
```
#### Institution Rating Detail
`GET` `/v1/quote/institution-ratings/detail`
Get historical analyst rating and target price details.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `TSLA.US` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/institution-ratings/detail?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `evaluate` | object | No | Rating distribution history |
| `└ list` | object[] | No | Daily holding history records |
| `└ ∟ strong_buy` | integer | No | Strong buy count |
| `└ ∟ buy` | integer | No | Buy count |
| `└ ∟ hold` | integer | No | Hold count |
| `└ ∟ sell` | integer | No | Sell count |
| `└ ∟ under` | integer | No | Underperform count |
| `└ ∟ date` | string | No | Date |
| `target` | object | No | Target price history |
| `└ updated_at` | string | No | Unix timestamp (seconds) of last update |
| `└ prediction_accuracy` | string | No | Prediction accuracy. |
| `└ list` | object[] | No | Daily holding history records |
| `└ ∟ timestamp` | string | No | Unix timestamp |
| `└ ∟ price` | string | No | Closing price on that date |
| `└ ∟ meet` | boolean | No | Whether price met target |
| `└ ∟ avg_target` | string | No | Average target price |
| `└ ∟ min_target` | string | No | Lowest target price |
| `└ ∟ max_target` | string | No | Highest target price |
| `└ ∟ date` | string | No | Date |
| `└ data_percent` | string | No | Data completeness percentage. |
| `ccy_symbol` | string | No | Currency symbol |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"ccy_symbol": "$",
"evaluate": {
"list": [
{
"date": "2021/05/14",
"buy": 3,
"hold": 11,
"sell": 2,
"strong_buy": 9,
"under": 6
}
]
},
"target": {
"list": [
{
"broker_name": "Goldman Sachs",
"date": "2026-04-30",
"rating": "Buy",
"target_price": "250.00"
}
]
}
}
}
```
#### Business Segments
`GET` `/v1/quote/fundamentals/business-segments`
Get the current-period revenue segment breakdown for a listed company.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `AAPL.US` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/fundamentals/business-segments?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `date` | string | No | Report period in YYYYMMDD format, e.g. `20260331` |
| `total` | string | No | Total revenue for the period |
| `currency` | string | No | Currency code, e.g. `USD` |
| `business` | object[] | No | Business segment list |
| `└ name` | string | No | Segment name |
| `└ percent` | string | No | Revenue share percentage, e.g. `40.56` |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"date": "20260331",
"total": "124300000000",
"currency": "USD",
"business": [
{
"name": "iPhone",
"percent": "56.19"
},
{
"name": "Services",
"percent": "21.96"
},
{
"name": "Mac",
"percent": "8.04"
},
{
"name": "iPad",
"percent": "7.00"
},
{
"name": "Wearables",
"percent": "6.81"
}
]
}
}
```
#### Business Segments History
`GET` `/v1/quote/fundamentals/business-segments/history`
Get historical business segment revenue trends across reporting periods.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `AAPL.US` |
| `report` | string | No | Report type: `qf` (quarterly) / `saf` (semi-annual) / `af` (annual) |
| `cate` | string | No | Segment category filter |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/fundamentals/business-segments/history?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `historical` | object[] | No | Historical period snapshots |
| `└ total` | string | No | Total revenue for the period |
| `└ currency` | string | No | Currency code |
| `└ date` | string | No | Report period in YYYYMMDD format, e.g. `20260331` |
| `└ report` | string | No | Report period code (e.g. `af` = annual) |
| `└ report_txt` | string | No | Period label (e.g. `FY2024`, `Q1 2024`) |
| `└ fp_start` | string | No | Fiscal period start date in `YYYY.MM.DD` format |
| `└ fp_end` | string | No | Period end timestamp |
| `└ rpt_date` | string | No | Report release date (YYYY-MM-DD) |
| `└ business` | object[] | No | Business segment list |
| `└ ∟ name` | string | No | Segment name |
| `└ ∟ percent` | string | No | Revenue share percentage, e.g. `40.80` |
| `└ ∟ value` | string | No | Absolute revenue value |
| `└ ∟ id` | string | No | ID of the newly created alert |
| `└ ∟ yoy` | string | No | Year-over-year growth rate |
| `└ regionals` | array | No | Regional segment list (typically empty) |
| `└ bus_ids` | array | No | Business-segment IDs. |
| `└ reg_ids` | array | No | Regional-segment IDs. |
| `└ yoy` | string | No | Year-over-year growth rate |
| `bus_ids` | array | No | Business-segment IDs. |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"historical": [
{
"date": "20260331",
"total": "124300000000",
"currency": "USD",
"business": [
{
"name": "Americas",
"percent": "40.80",
"value": "31968000000"
},
{
"name": "Europe",
"percent": "23.64",
"value": "18521000000"
},
{
"name": "Greater China",
"percent": "20.72",
"value": "16233000000"
}
],
"regionals": []
}
]
}
}
```
#### Macroeconomic Historical Data
`GET` `/v2/quote/macrodata`
Get historical releases for a specific macroeconomic indicator — actual values, forecasts, previous values, and next release dates.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `indicator_code` | string | Yes | Indicator code from `macroeconomic_indicators` |
| `start_date` | string | No | Start date in `YYYY-MM-DD` format |
| `end_date` | string | No | End date in `YYYY-MM-DD` format |
| `offset` | integer | No | Pagination offset. Default: 0 |
| `limit` | integer | No | Max records. Default: 100, max: 100 |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v2/quote/macrodata?indicator_code=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `info` | MacroeconomicIndicator | Yes | Indicator metadata |
| `data` | Macroeconomic[] | Yes | Historical data points |
| `count` | int | Yes | Total number of data points |
| `period` | string | Yes | Statistical period (e.g. `2024-12-01`, `2024-Q4`) |
| `release_at` | int | No | Unix timestamp of release datetime |
| `actual_value` | string | Yes | Actual released value |
| `previous_value` | string | Yes | Previous period value |
| `forecast_value` | string | Yes | Market consensus forecast |
###### Response JSON Example
```json
{
"count": 24,
"info": {
"indicator_code": "61744",
"country": "US",
"name": "Non-Farm Payroll",
"periodicity": "Monthly",
"describe": "...",
"importance": 3
},
"data": [
{
"period": "2024-12-01",
"release_at": 1735900200,
"actual_value": "256000",
"previous_value": "212000",
"forecast_value": "165000"
}
]
}
```
#### Macroeconomic Indicators
`GET` `/v2/quote/macrodata/{indicator_id}`
List macroeconomic indicators available through Longbridge, optionally filtered by country.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `country` | string | No | Filter by country. Omit for all countries. |
| `keyword` | string | No | Fuzzy search by indicator name (case-insensitive) |
| `offset` | integer | No | Pagination offset. Default: 0 |
| `limit` | integer | No | Max records per page. Default: 100, max: 1000 |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v2/quote/macrodata/{indicator_id}' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `indicator` | object | Yes | Indicator detail |
| `indicator.indicator_id` | integer | No | Indicator ID |
| `indicator.indicator_name` | string | No | Indicator name |
| `indicator.unit` | string | No | Value unit |
| `indicator.description` | string | No | Indicator description |
| `indicator.market` | string | No | Market / country code |
| `indicator.frequence` | string | No | Release frequency, e.g. `day`, `month` |
| `indicator.importance` | integer | No | Importance level (1 = Low, 2 = Medium, 3 = High) |
| `indicator.indicator_data` | object[] | No | Time-series data points |
| `indicator.indicator_data[].actual_data` | string | No | Actual value |
| `indicator.indicator_data[].previous_data` | string | No | Previous value |
| `indicator.indicator_data[].estimated_data` | string | No | Forecast value |
| `indicator.indicator_data[].published_time` | string | No | Publish time (ISO 8601) |
| `indicator.indicator_data[].observation_date` | string | No | Observation date (YYYY-MM-DD) |
| `total` | integer | No | Total number of matching indicators |
###### Response JSON Example
```json
{
"count": 619,
"list": [
{
"indicator_code": "61744",
"country": "US",
"name": "Non-Farm Payroll",
"periodicity": "Monthly",
"describe": "Employment situation report...",
"importance": 3
}
]
}
```
### Market Data
#### A/H Premium
`GET` `/v1/quote/ahpremium/klines`
Get the A/H premium ratio for dual-listed stocks comparing A-share and H-share prices.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `600519.SH` or `000001.SZ`. |
| `line_type` | string | Yes | Candlestick period, e.g. `day`, `week`, `month`. |
| `line_num` | integer | Yes | Number of candlesticks to return. |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/ahpremium/klines?symbol=&line_type=&line_num=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `klines` | object[] | Yes | A/H premium daily kline records |
| `└ timestamp` | string | No | Unix timestamp |
| `└ ahpremium_rate` | string | No | A/H premium rate |
| `└ aprice` | string | No | A-share price (CNY) |
| `└ apreclose` | string | No | A-share previous close (CNY) |
| `└ hprice` | string | No | H-share price (HKD) |
| `└ hpreclose` | string | No | H-share previous close (HKD) |
| `└ currency_rate` | string | No | CNH/HKD exchange rate |
| `└ price_spread` | string | No | Price spread |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"klines": [
{
"ahpremium_rate": "0.1523",
"apreclose": "24.80",
"aprice": "25.10",
"currency_rate": "0.8920",
"hpreclose": "19.20",
"hprice": "19.50",
"price_spread": "1.23",
"timestamp": "1778198400"
}
]
}
}
```
#### A/H Premium Intraday
`GET` `/v1/quote/ahpremium/timeshares`
Get intraday A/H premium timeseries data for a dual-listed security.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | HK-side symbol of a dual-listed stock, e.g. `939.HK` |
| `days` | integer | Yes | Number of intraday trading days to return, e.g. `1` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/ahpremium/timeshares?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `klines` | object[] | Yes | Intraday A/H premium kline data |
| `└ timestamp` | string | No | Unix timestamp |
| `└ ahpremium_rate` | string | No | A/H premium rate |
| `└ aprice` | string | No | A-share price (CNY) |
| `└ apreclose` | string | No | A-share previous close (CNY) |
| `└ hprice` | string | No | H-share price (HKD) |
| `└ hpreclose` | string | No | H-share previous close (HKD) |
| `└ currency_rate` | string | No | CNH/HKD exchange rate |
| `└ price_spread` | string | No | Price spread |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"klines": [
{
"ahpremium_rate": "0.1523",
"apreclose": "24.80",
"aprice": "25.10",
"currency_rate": "0.8920",
"hpreclose": "19.20",
"hprice": "19.50",
"price_spread": "1.23",
"timestamp": "1778198400"
}
]
}
}
```
#### Broker Positions
`GET` `/v1/quote/broker-holding`
:::warning Longbridge HK / SG accounts only
This method is available to Longbridge HK / SG accounts only. It works with any supported symbol, including US stocks.
:::
View broker holding positions for HK-listed stocks, including top buyers/sellers and full detail.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `700.HK`. |
| `type` | string | Yes | Statistics period: `rct_1` (1 day), `rct_5` (5 days), `rct_20` (20 days), `rct_60` (60 days). |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/broker-holding?symbol=&type=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `buy` | object[] | No | Top buying brokers |
| `└ name` | string | No | Broker name |
| `└ parti_number` | string | No | Broker participant number |
| `└ chg` | string | No | Position change |
| `└ strong` | boolean | No | Whether marked as strong holder |
| `sell` | object[] | No | Top selling brokers |
| `└ name` | string | No | Broker name |
| `└ parti_number` | string | No | Broker participant number |
| `└ chg` | string | No | Position change |
| `└ strong` | boolean | No | Whether marked as strong holder |
| `updated_at` | string | No | Last update timestamp |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"buy": [
{
"parti_number": "B01224",
"name": "HSBC",
"chg": "5000000",
"strong": true
}
],
"sell": [
{
"parti_number": "B01274",
"name": "Goldman Sachs HK",
"chg": "-3000000",
"strong": false
}
],
"updated_at": "2026.05.13"
}
}
```
#### Broker Holding Daily
`GET` `/v1/quote/broker-holding/daily`
:::warning Longbridge HK / SG accounts only
This method is available to Longbridge HK / SG accounts only. It works with any supported symbol, including US stocks.
:::
Get daily holding history for a specific broker in an HK-listed security.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `700.HK`. |
| `parti_number` | string | Yes | Broker (participant) number. |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/broker-holding/daily?symbol=&parti_number=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `list` | object[] | Yes | Daily holding history records |
| `└ date` | string | Yes | Date (e.g. `2026.05.13`) |
| `└ holding` | string | No | Total shares held |
| `└ chg` | string | No | Daily change in shares |
| `└ ratio` | string | No | Holding ratio |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"list": [
{
"date": "2026.05.13",
"holding": "22903430",
"chg": "7029132.0000",
"ratio": "0.0025"
},
{
"date": "2026.05.12",
"holding": "15874298",
"chg": "-2150000.0000",
"ratio": "0.0017"
}
]
}
}
```
#### Broker Holding Detail
`GET` `/v1/quote/broker-holding/detail`
:::warning Longbridge HK / SG accounts only
This method is available to Longbridge HK / SG accounts only. It works with any supported symbol, including US stocks.
:::
Get full broker holding detail list for an HK-listed security (all brokers and their positions).
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | HK security symbol, e.g. `700.HK` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/broker-holding/detail?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `list` | object[] | No | Broker holding detail records |
| `└ name` | string | No | Security name. |
| `└ parti_number` | string | No | Broker participant number |
| `└ ratio` | object | No | Holding ratio |
| `└ ∟ value` | string | No | Indicator value as a string; empty when unavailable. |
| `└ ∟ chg_1` | string | No | 1-day change ratio. |
| `└ ∟ chg_5` | string | No | 5-day change ratio. |
| `└ ∟ chg_20` | string | No | 20-day change ratio. |
| `└ ∟ chg_60` | string | No | 60-day change ratio. |
| `└ shares` | object | No | Holding share counts |
| `└ ∟ value` | string | No | Indicator value as a string; empty when unavailable. |
| `└ ∟ chg_1` | string | No | 1-day change ratio. |
| `└ ∟ chg_5` | string | No | 5-day change ratio. |
| `└ ∟ chg_20` | string | No | 20-day change ratio. |
| `└ ∟ chg_60` | string | No | 60-day change ratio. |
| `└ strong` | boolean | No | Whether marked as strong holder |
| `updated_at` | string | No | Last update date |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"updated_at": "2026.05.13",
"list": [
{
"parti_number": "B01224",
"name": "HSBC Securities",
"strong": false,
"shares": {
"value": "25100",
"chg_1": "4000.0000",
"chg_5": "6100.0000",
"chg_20": "12600.0000",
"chg_60": "8800.0000"
},
"ratio": {
"value": "0.0025",
"chg_1": "0.0004",
"chg_5": "0.0006",
"chg_20": "0.0012",
"chg_60": "0.0009"
}
}
]
}
}
```
#### Index Components
`GET` `/v1/quote/index-constituents`
Get the constituent stocks of an index or ETF with sorting options and rise/fall statistics.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Index or ETF symbol, e.g. `HSI.HK`, `SPY.US` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/index-constituents?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `total` | integer | No | Total number of matching stocks. |
| `└ symbol` | string | No | Security symbol |
| `└ trade_status` | integer | No | Trading status code |
| `└ last_done` | string | No | Last trade price |
| `└ prev_close` | string | No | Previous close |
| `└ inflow` | string | No | Capital inflow |
| `└ balance` | string | No | Market cap |
| `└ amount` | string | No | Trading volume amount |
| `└ total_shares` | string | No | Total shares |
| `└ circulating_shares` | string | No | Circulating shares |
| `└ tags` | array | No | Tags |
| `└ name` | string | No | Security name |
| `└ market` | string | No | Market |
| `└ intro` | string | No | Brief description |
| `└ delay` | boolean | No | Whether data is delayed |
| `└ chg` | string | No | Price change percentage |
| `rise_num` | integer | No | Number of rising stocks |
| `fall_num` | integer | No | Number of falling stocks |
| `flat_num` | integer | No | Number of flat stocks |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"fall_num": 10,
"flat_num": 3,
"rise_num": 7,
"stocks": [
{
"symbol": "9988.HK",
"name": "BABA-W",
"market": "HK",
"last_done": "140.90",
"prev_close": "132.80",
"chg": "0.0610",
"amount": "93828577",
"inflow": "18483450",
"balance": "13320299492",
"circulating_shares": "19192403958",
"total_shares": "19192403958",
"trade_status": 105,
"intro": "China's largest e-commerce platform",
"delay": false,
"tags": [
"Top gainers"
]
}
]
}
}
```
#### Trading Stats
`GET` `/v1/quote/trades-statistics`
Get trade statistics showing price distribution by volume for a security.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Security symbol, e.g. `700.HK` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/trades-statistics?symbol=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `trades` | object[] | No | Price-level trade distribution |
| `└ price` | string | No | Price level |
| `└ buy_amount` | string | No | Buy amount at this price |
| `└ sell_amount` | string | No | Sell amount at this price |
| `└ neutral_amount` | string | No | Neutral amount at this price |
| `statistics` | object | No | Aggregate trade statistics |
| `└ avgprice` | string | No | Average price. |
| `└ trades_count` | string | No | Number of trades. |
| `└ total_amount` | string | No | Total market turnover. |
| `└ buy` | string | No | Top buying brokers |
| `└ sell` | string | No | Top selling brokers |
| `└ neutral` | string | No | Neutral value/count. |
| `└ timestamp` | string | No | Event time (Unix seconds as string) |
| `└ preclose` | string | No | Previous close price. |
| `└ trade_date` | array | No | Next projected trade date (YYYY-MM-DD) |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"statistics": {
"avgprice": "210.50",
"buy": "45000000",
"sell": "38000000",
"neutral": "12000000",
"total_amount": "95000000",
"trades_count": "125000",
"preclose": "208.20",
"timestamp": "1778198400",
"trade_date": [
"2026-05-13"
]
},
"trades": [
{
"price": "210.00",
"buy_amount": "5000000",
"sell_amount": "4000000",
"neutral_amount": "1000000"
}
]
}
}
```
## Market
### Market Status
#### Top Movers
`POST` `/v1/quote/market/stock-events`
Get stocks whose price movement exceeds the 20-trading-day standard deviation, with automatically correlated news to explain the move.
##### Parameters
###### Request Body
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `markets` | array | No | Market list: `HK`, `US`, `CN`, `SG`; returns all markets if omitted |
| `sort` | integer | No | Sort order: `0`=time (newest first), `1`=price change, `2`=hotness (default) |
| `date` | string | No | Target date in `YYYY-MM-DD` format; returns latest data if omitted |
| `limit` | integer | No | Number of results to return, default 20 |
##### Request Example
```bash
curl --request POST \
--url 'https://openapi.longbridge.com/v1/quote/market/stock-events' \
--header 'Authorization: Bearer ' \
--header 'Content-Type: application/json' \
--data '{"markets":[],"sort":0,"date":"","limit":0}'
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `events` | object[] | No | List of moving stocks |
| `└ stock` | object | No | Basic stock information |
| `└ ∟ code` | string | No | Ticker code (e.g. `TSLA`) |
| `└ ∟ name` | string | No | Security name |
| `└ ∟ change` | string | No | Price change ratio (e.g. `-0.0388`) |
| `└ ∟ last_done` | string | No | Latest trade price |
| `└ ∟ market` | string | No | Market: `US`, `HK`, `CN`, `SG` |
| `└ ∟ labels` | string[] | No | Industry / theme tags |
| `└ ∟ logo` | string | No | Logo image URL |
| `└ ∟ trade_status` | integer | No | Trading status code |
| `└ timestamp` | string | No | Event time (Unix seconds as string) |
| `└ alert_reason` | string | No | Description of the move reason |
| `└ alert_type` | integer | No | Move type code |
| `└ post` | object | No | Associated news article (complex object with `title`, `description_html`, `published_at` and other fields; `null` when no article is linked) |
| `next_params` | object | No | Pagination cursor object; pass to the next request to get the next page |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"events": [
{
"stock": {
"code": "TSLA",
"symbol": "TSLA.US",
"name": "Tesla, Inc.",
"change": "-0.0388",
"last_done": "404.110",
"market": "US",
"labels": [
"Automobile Manufacturers"
],
"logo": "https://assets.lbkrs.com/ticker/ST/US/TSLA.png",
"trade_status": 0
},
"timestamp": "1779202097",
"alert_reason": "Volatility exceeds 20-day avg",
"alert_type": 11,
"post": null
}
],
"next_params": {
"visited": [
"11098290",
"11098478",
"11099705"
]
}
}
}
```
#### Market Status
`GET` `/v1/quote/market-status`
Get the current open/close status for each exchange.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `market` | string | No | Market code: `US`, `HK`, `SH`, `SZ`, `SG`. Omit for all markets. |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/market-status' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `market_time` | object[] | No | List of market status items |
| `└ market` | string | No | Market: `US`, `HK`, `CN`, `SG`, `Crypto` |
| `└ trade_status` | integer | No | Trading status code |
| `└ timestamp` | string | No | Event time (Unix seconds as string) |
| `└ delay_trade_status` | integer | No | Delayed trading status |
| `└ delay_timestamp` | string | No | Delay timestamp |
| `└ sub_status` | integer | No | Sub-status. |
| `└ delay_sub_status` | integer | No | Delayed subscription status |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"market_time": [
{
"market": "US",
"delay_sub_status": 0,
"delay_timestamp": "0",
"delay_trade_status": 0
},
{
"market": "HK",
"delay_sub_status": 0,
"delay_timestamp": "0",
"delay_trade_status": 0
}
]
}
}
```
#### Rank Categories
`GET` `/v1/quote/market/rank/categories`
Get the tag category configuration for the popularity leaderboard. `second_tags[].key` can be passed to `rank_list`.
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/market/rank/categories' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `first_tags` | object[] | No | Top-level category list |
| `└ key` | string | No | Top-level category key |
| `└ name` | string | No | Top-level category name |
| `└ second_tags` | object[] | No | Second-level category list |
| `└ ∟ key` | string | No | Top-level category key |
| `└ ∟ name` | string | No | Top-level category name |
| `└ ∟ market` | string | No | Associated market: `US`, `HK`, `CN`, `SG` |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"first_tags": [
{
"key": "ib_hot",
"name": "Hotness Rank",
"second_tags": [
{
"key": "ib_hot_all-us",
"name": "US Total Hotness",
"market": "US"
},
{
"key": "ib_hot_all-hk",
"name": "HK Total Hotness",
"market": "HK"
},
{
"key": "ib_hot_all-cn",
"name": "A-share Total Hotness",
"market": "CN"
}
]
},
{
"key": "ib_change",
"name": "Price Change Rank",
"second_tags": [
{
"key": "ib_change_top-us",
"name": "US Top Gainers",
"market": "US"
},
{
"key": "ib_change_top-hk",
"name": "HK Top Gainers",
"market": "HK"
}
]
}
]
}
}
```
#### Popularity Leaderboard
`GET` `/v1/quote/market/rank/list`
Get the stock ranking for a given leaderboard tag key. The key comes from `rank_categories` `second_tags[].key`, e.g. `hot_all-us` (US total hotness).
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `key` | string | Yes | Leaderboard tag key from `rank_categories` `second_tags[].key` |
| `need_article` | boolean | No | Whether to return associated articles, default `false` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/market/rank/list?key=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `bmp` | boolean | No | Whether the response is a market preview (before open) |
| `lists` | object[] | No | Leaderboard stock list |
| `└ code` | string | No | Ticker code (e.g. `MU`) |
| `└ symbol` | string | No | Symbol in `CODE.MARKET` format (e.g. `MU.US`) |
| `└ name` | string | No | Security name |
| `└ last_done` | string | No | Latest trade price |
| `└ chg` | string | No | Price change ratio as decimal (e.g. `0.0252` = 2.52%) |
| `└ change` | string | No | Absolute price change (e.g. `17.200`) |
| `└ inflow` | string | No | Net capital inflow (in the market's currency) |
| `└ market_cap` | string | No | Market capitalisation |
| `└ industry` | string | No | Industry classification |
| `└ pre_post_price` | string | No | Pre/post-market price |
| `└ pre_post_chg` | string | No | Pre/post-market price change ratio (decimal) |
| `└ amplitude` | string | No | Amplitude / intraday range ratio (decimal) |
| `└ five_day_chg` | string | No | 5-day price change ratio (decimal) |
| `└ turnover_rate` | string | No | Turnover rate (decimal) |
| `└ volume_rate` | string | No | Volume ratio (vs average) |
| `└ pb_ttm` | string | No | Price-to-book ratio (TTM) |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"bmp": false,
"lists": [
{
"code": "MU",
"symbol": "MU.US",
"name": "Micron Technology",
"last_done": "698.740",
"chg": "0.0252",
"change": "17.200",
"inflow": "-347041642",
"market_cap": "787992890796",
"industry": "Semiconductor Manufacturers",
"pre_post_price": "726.600",
"pre_post_chg": "0.0399",
"amplitude": "0.1082",
"five_day_chg": "-0.0885",
"turnover_rate": "0.0550",
"volume_rate": "1.11",
"pb_ttm": "32.68"
}
]
}
}
```
#### Unusual Items
`GET` `/v1/quote/changes`
Detect unusual market movements — price spikes, volume surges, and other abnormal trading activity.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `market` | string | Yes | Market code: `US`, `HK`, `SH`, `SZ`, `SG` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/changes?market=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `all_off` | boolean | No | Whether anomaly alerts are globally disabled |
| `changes` | object[] | No | List of market anomaly events |
| `└ symbol` | string | Yes | Security symbol |
| `└ name` | string | No | Security name |
| `└ alert_name` | string | No | Anomaly type name |
| `└ alert_time` | integer | No | Anomaly time (Unix timestamp, ms) |
| `└ emotion` | integer | No | Sentiment: `1`=positive/up, `2`=negative/down |
| `└ change_values` | string[] | No | Change value strings |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"all_off": false,
"changes": [
{
"symbol": "TSLA.US",
"name": "Tesla Inc.",
"alert_name": "Block Trade",
"alert_time": 1778198400000,
"emotion": 1,
"change_values": [
"+5.2%"
]
}
]
}
}
```
#### Get Historical Market Temperature
`GET` `/v1/quote/history_market_temperature`
> **Quote Permission Required · Free**
> Included with OpenAPI activation — no extra purchase needed.
> _OpenAPI quote perms are separate from App/Web perms_
Get the historical market temperature time series for the specified market within a date range.
Each data point contains the daily temperature, valuation, and sentiment scores (all scored 0–100).
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `market` | string | Yes | Market code. One of `HK`, `US`, `CN`, `SG`. |
| `start_date` | string | Yes | Start date in `YYYYMMDD` format (e.g. `20250101`). |
| `end_date` | string | Yes | End date in `YYYYMMDD` format (e.g. `20250110`). |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/history_market_temperature?market=&start_date=&end_date=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `list` | object[] | No | Market-temperature time series. |
| `└ timestamp` | string | No | Unix timestamp of the data point. |
| `└ temperature` | integer | No | Market temperature (0–100). |
| `└ valuation` | integer | No | Valuation score. |
| `└ sentiment` | integer | No | Sentiment score. |
| `type` | string | No | Granularity of the series, e.g. `day`. |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"list": [
{
"timestamp": "1735794000",
"temperature": 58,
"valuation": 54,
"sentiment": 61
},
{
"timestamp": "1735880400",
"temperature": 59,
"valuation": 56,
"sentiment": 63
}
],
"type": "day"
}
}
```
#### Get Current Market Temperature
`GET` `/v1/quote/market_temperature`
> **Quote Permission Required · Free**
> Included with OpenAPI activation — no extra purchase needed.
> _OpenAPI quote perms are separate from App/Web perms_
Get the current sentiment temperature snapshot for the specified market.
Scores range from 0–100; a higher value indicates a more bullish market.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `market` | string | Yes | Market code. One of `HK`, `US`, `CN`, `SG`. |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/market_temperature?market=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `temperature` | integer | No | Current market temperature (0–100). |
| `description` | string | No | Text description of the current temperature. |
| `valuation` | integer | No | Valuation score. |
| `sentiment` | integer | No | Sentiment score. |
| `updated_at` | string | No | Update time (Unix timestamp). |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"temperature": 70,
"description": "Warm & rising quickly",
"valuation": 59,
"sentiment": 82,
"updated_at": "1774317902"
}
}
```
### Financial Calendar
#### Earnings Calendar
`GET` `/v1/quote/finance_calendar`
Browse upcoming earnings reports and recent results, with EPS and revenue estimates.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `date` | string | Yes | Start date, `YYYYMMDD`. Paginate by passing the returned `next_date`. |
| `date_end` | string | Yes | End date, `YYYYMMDD`. |
| `types[]` | string | Yes | Event category: `report`, `dividend`, `split`, `ipo`, `macrodata`, `closed`, `meeting`, `merge`. |
| `markets[]` | string | No | Market filter, e.g. `US`, `HK`, `CN`. If omitted, all markets. |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/finance_calendar?date=&date_end=&types[]=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `date` | string | No | Response date |
| `list` | object[] | Yes | List of calendar date groups |
| `count` | integer | No | Number of events on this date |
| `infos` | object[] | Yes | List of calendar events |
| `id` | string | No | Event ID |
| `symbol` | string | No | Security symbol |
| `market` | string | No | Market |
| `counter_name` | string | No | Security name |
| `type` | string | No | Event type |
| `activity_type` | string | No | Activity type |
| `datetime` | string | No | Event datetime |
| `date_type` | string | No | Date type |
| `content` | string | No | Event content description |
| `currency` | string | No | Currency |
| `star` | integer | No | Importance rating (1-3) |
| `icon` | string | No | Icon URL |
| `chart_uid` | string | No | Chart identifier |
| `financial_market_time` | string | No | Financial market time |
| `data_kv` | object[] | No | Key-value data pairs |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"date": "2026-04-30",
"list": [
{
"date": "2026-04-30",
"count": 2228,
"infos": [
{
"id": "12345",
"symbol": "AAPL.US",
"market": "US",
"counter_name": "Apple Inc.",
"event_type": "",
"activity_type": "",
"date": "2026-05-14",
"datetime": "",
"content": "",
"star": 0,
"currency": "",
"icon": "",
"chart_uid": "",
"date_type": "",
"financial_market_time": "",
"data_kv": []
}
]
}
]
}
}
```
## News & Contents
### News
#### Security News
`GET` `/v1/content/{symbol}/news`
Get the news list for a specified security. Browse the full feed on [News](https://longbridge.com/news).
##### Parameters
###### Path Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Stock symbol, use `ticker.region` format, e.g. `AAPL.US` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/content//news' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `items` | object[] | No | News list |
| `└ id` | string | No | News ID |
| `└ title` | string | No | Title |
| `└ description` | string | No | Summary/description |
| `└ url` | string | No | Detail page URL |
| `└ comments_count` | integer | No | Comment count |
| `└ likes_count` | integer | No | Like count |
| `└ shares_count` | integer | No | Share count |
| `└ published_at` | string | No | Published time, Unix timestamp (seconds) |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"items": [
{
"id": "279528757",
"title": "Beats cross-industry collaboration breaks the circle with Nike! Apple aims to ignite a new wave of wearable consumer trends, while Nike bets on the narrative of \"sports technology.\"",
"description": "Apple's Beats has collaborated with Nike to launch a limited edition Powerbeats Pro 2 headphones, featuring Nike's Swoosh logo. The headphones will be available online and at select Apple Stores on March 20, priced at $250. This marks Beats' first collaboration with an external sports brand, signifying further synergy between the two companies in branding and product ecosystems. The headphones feature real-time heart rate tracking and a battery life of up to 45 hours",
"url": "https://longbridge.com/news/279528757",
"published_at": "1773805586",
"comments_count": 0,
"likes_count": 0,
"shares_count": 0
}
]
}
}
```
### Topics
#### Create Topic
`POST` `/v1/content/topics`
Create a new community topic on [Topics](https://longbridge.com/topics). Two content types are supported:
| Type | `title` | `body` format | Notes |
| ---------------- | ------------ | --------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `post` (default) | Optional | Plain text only | Markdown syntax (e.g. `**bold**`, `# heading`) is NOT rendered — it appears as literal characters, similar to a tweet. |
| `article` | **Required** | Markdown | The server converts Markdown to HTML for display. Supports headers, tables, bold, code blocks, etc. |
Only users who have opened a **Longbridge account and hold assets** are allowed to publish community topics and replies via Longbridge Developers API or CLI. Returns `403` otherwise.
:::tip Tip
Stock symbols mentioned in the body (e.g. `700.HK`, `TSLA.US`) are automatically recognized and linked as related stocks by the platform. Use `tickers` to associate additional symbols not explicitly mentioned in the body.
⚠️ Do not abuse symbol linking to associate unrelated stocks. Content moderation may restrict publishing or mute the account.
:::
**Rate limit:** Max 3 topics per user per minute and 10 per 24 hours. Exceeding the limit returns `429`.
:::warning
⚠️ Rate limit thresholds are for reference only and may be adjusted by the platform at any time.
:::
##### Parameters
###### Request Body
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `title` | string | No | Topic title. Required when `topic_type` is `article`; optional for `post`. |
| `body` | string | Yes | Topic body. - For `post`: plain text only — Markdown is not rendered. - For `article`: Markdown is supported. |
| `topic_type` | string | No | Content type: `post` (plain text, default) or `article` (Markdown). |
| `tickers` | array | No | Related security symbols, format `{symbol}.{market}` (e.g. `["AAPL.US", "700.HK"]`). Maximum 10. **Note:** Symbols mentioned in the body (e.g. `700.HK`, `TSLA.US`) are automatically recognized and linked by the platform. Use `tickers` to associate additional symbols not explicitly mentioned in the body. |
| `hashtags` | array | No | Hashtag names (e.g. `["earnings", "fed"]`). Maximum 1. |
##### Request Example
```bash
curl --request POST \
--url 'https://openapi.longbridge.com/v1/content/topics' \
--header 'Authorization: Bearer ' \
--header 'Content-Type: application/json' \
--data '{"title":"","body":" ","topic_type":"","tickers":[],"hashtags":[]}'
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `item` | object | Yes | Newly created topic details |
| `└ id` | string | Yes | Topic ID |
| `└ title` | string | No | Topic title |
| `└ description` | string | No | Plain-text summary (auto-generated from body) |
| `└ body` | string | No | Full body text (Markdown for `article`) |
| `└ topic_type` | string | No | Topic type. One of `article`, `post` |
| `└ tickers` | string[] | No | Associated security symbols |
| `└ hashtags` | string[] | No | Associated hashtag names |
| `└ images` | object[] | No | Image list |
| `└ ∟ url` | string | No | Original image URL |
| `└ ∟ sm` | string | No | Small thumbnail URL |
| `└ ∟ lg` | string | No | Large thumbnail URL |
| `└ likes_count` | int32 | No | Number of likes |
| `└ comments_count` | int32 | No | Number of replies |
| `└ views_count` | int32 | No | Number of views |
| `└ shares_count` | int32 | No | Number of shares |
| `└ detail_url` | string | No | Direct URL to the topic |
| `└ author` | object | No | Author information |
| `└ ∟ member_id` | string | No | Author member ID |
| `└ ∟ name` | string | No | Author display name |
| `└ ∟ avatar` | string | No | Author avatar URL |
| `└ created_at` | string | Yes | Unix timestamp (seconds) when the topic was created |
| `└ updated_at` | string | No | Unix timestamp (seconds) of last update |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"item": {
"id": "39304657",
"title": "My View on AAPL",
"topic_type": "article",
"tickers": [
"AAPL.US"
],
"hashtags": [
"earnings"
],
"created_at": "1742000000"
}
}
}
```
#### Topic Replies
`GET` `/v1/content/topics/{topic_id}/comments`
Get a paginated list of replies for a specific topic. Browse the discussion on [Topics](https://longbridge.com/topics).
Each reply includes author info, body (plain text), engagement counts, and a `reply_to_id` field: `"0"` indicates a top-level reply; any other value identifies the parent reply for nested replies.
##### Parameters
###### Path Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `topic_id` | string | Yes | Topic ID (e.g. `6993508780031016960`) |
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `page` | integer | No | Page number (1-based). Defaults to `1`. |
| `size` | integer | No | Items per page, range 1–50. Defaults to `20`. |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/content/topics//comments' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `items` | object[] | Yes | List of replies |
| `└ id` | string | Yes | Reply ID |
| `└ topic_id` | string | Yes | Parent topic ID |
| `└ body` | string | No | Reply body (plain text) |
| `└ reply_to_id` | string | No | Parent reply ID; `"0"` = top-level reply |
| `└ author` | object | No | Author info |
| `└ images` | object[] | No | Attached images |
| `└ likes_count` | int32 | No | Likes count |
| `└ comments_count` | int32 | No | Nested replies count |
| `└ created_at` | string | Yes | Creation time as Unix timestamp (seconds) |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"items": [
{
"id": "7001234567890123456",
"topic_id": "6993508780031016960",
"body": "Great analysis!",
"reply_to_id": "0",
"author": {
"member_id": "10087",
"name": "John Smith",
"avatar": "https://example.com/avatar2.jpg"
},
"images": [],
"likes_count": 5,
"comments_count": 2,
"created_at": "1742001500"
},
{
"id": "7001234567890123457",
"topic_id": "6993508780031016960",
"body": "I disagree on the valuation part.",
"reply_to_id": "7001234567890123456",
"author": {
"member_id": "10088",
"name": "Alice Lee",
"avatar": "https://example.com/avatar3.jpg"
},
"images": [],
"likes_count": 1,
"comments_count": 0,
"created_at": "1742001800"
}
]
}
}
```
#### Create Topic Reply
`POST` `/v1/content/topics/{topic_id}/comments`
Post a reply to a community topic. Supports nesting under an existing reply. Browse the community on [Topics](https://longbridge.com/topics).
Only users who have opened a **[Longbridge account](https://longbridge.com/hk/download) and hold assets** are allowed to publish community topics and replies via Longbridge Developers API or CLI. Returns `403` otherwise.
**Body format:** Plain text only — HTML and Markdown are **not** rendered.
:::tip Tip
Stock symbols mentioned in the body (e.g. `700.HK`, `TSLA.US`) are automatically recognized and linked as related stocks by the platform.
⚠️ Do not abuse symbol linking to associate unrelated stocks. Content moderation may restrict publishing or mute the account.
:::
**Rate limit:** The first 3 replies per user per topic have no wait requirement. After that, each subsequent reply must wait an incrementally longer interval since the previous one:
| Reply # (after 3rd) | Required wait |
| ------------------- | ------------- |
| 4th | 3 s |
| 5th | 5 s |
| 6th | 8 s |
| 7th | 13 s |
| 8th | 21 s |
| 9th | 34 s |
| 10th+ | 55 s (cap) |
Exceeding the limit returns `429`.
:::warning
⚠️ Rate limit thresholds are for reference only and may be adjusted by the platform at any time.
:::
##### Parameters
###### Path Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `topic_id` | string | Yes | Topic ID (e.g. `6993508780031016960`) |
###### Request Body
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `body` | string | Yes | Reply body. Plain text only — Markdown is not rendered. Symbols mentioned in the body are auto-linked by the platform. |
| `reply_to_id` | string | No | ID of the reply to nest under. Omit or set to `"0"` for a top-level reply. |
##### Request Example
```bash
curl --request POST \
--url 'https://openapi.longbridge.com/v1/content/topics//comments' \
--header 'Authorization: Bearer ' \
--header 'Content-Type: application/json' \
--data '{"body":"","reply_to_id":""}'
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `item` | object | Yes | Created reply details |
| `└ id` | string | Yes | Reply ID |
| `└ topic_id` | string | Yes | Parent topic ID |
| `└ body` | string | No | Reply body (plain text) |
| `└ reply_to_id` | string | No | Parent reply ID; `"0"` = top-level reply |
| `└ author` | object | No | Author info |
| `└ ∟ member_id` | string | No | Author member ID |
| `└ ∟ name` | string | No | Author display name |
| `└ ∟ avatar` | string | No | Author avatar URL |
| `└ images` | object[] | No | Attached images |
| `└ ∟ url` | string | No | Original image URL |
| `└ ∟ sm` | string | No | Small thumbnail URL |
| `└ ∟ lg` | string | No | Large image URL |
| `└ likes_count` | int32 | No | Likes count |
| `└ comments_count` | int32 | No | Nested replies count |
| `└ created_at` | string | Yes | Creation time as Unix timestamp (seconds) |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"item": {
"id": "7001234567890123460",
"topic_id": "6993508780031016960",
"body": "Great analysis!",
"reply_to_id": "0",
"author": {
"member_id": "10086",
"name": "Jane Doe",
"avatar": "https://example.com/avatar.jpg"
},
"images": [],
"likes_count": 0,
"comments_count": 0,
"created_at": "1742002000"
}
}
}
```
#### Topics by Symbol
`GET` `/v1/content/{symbol}/topics`
Get the topic/discussion list for a specified security. Browse the full community on [Topics](https://longbridge.com/topics).
##### Parameters
###### Path Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbol` | string | Yes | Stock symbol, use `ticker.region` format, e.g. `AAPL.US` |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/content//topics' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `items` | object[] | No | Topic list |
| `└ id` | string | No | Topic ID |
| `└ description` | string | No | Summary/description |
| `└ url` | string | No | Detail page URL |
| `└ comments_count` | integer | No | Comment count |
| `└ likes_count` | integer | No | Like count |
| `└ shares_count` | integer | No | Share count |
| `└ published_at` | string | No | Published time, Unix timestamp (seconds) |
| `└ title` | string | No | Title |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"items": [
{
"id": "39304657",
"title": "NVDA GTC in focus; Alibaba 'Token strategy' ramps up | Daily News Recap",
"description": "0317 | Dolphin Research Focus: 🐬 Stock #1, $NVIDIA(NVDA.US) — NVIDIA's GTC 2026 officially kicked off, and founder & CEO Jensen Huang delivered the keynote.He announced a Vera Rubin Space Module under the next-gen Vera Rubin architecture, designed for orbital data centers, delivering 25x performance vs. H100.He also unveiled a partnership with Groq to co-develop new LPU chips...",
"url": "https://longbridge.com/topics/39304657",
"published_at": "1773736144",
"comments_count": 1,
"likes_count": 7,
"shares_count": 4
}
]
}
}
```
#### My Topics
`GET` `/v1/content/topics/mine`
Get the list of topics I have published. View them on [Topics](https://longbridge.com/topics).
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `page` | integer | No | Page number (1-based). Defaults to `1`. |
| `size` | integer | No | Number of items per page, range 1–500. Defaults to `50`. |
| `topic_type` | string | No | Filter by type. One of `article` (long-form), `post` (short post). Omit to return all types. |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/content/topics/mine' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `items` | object[] | No | Topic list |
| `└ id` | string | No | Topic ID |
| `└ description` | string | No | Plain-text summary of the topic body |
| `└ author` | object | No | Author information |
| `└ ∟ member_id` | string | No | Author member ID |
| `└ ∟ name` | string | No | Author display name |
| `└ ∟ avatar` | string | No | Author avatar URL |
| `└ tickers` | array | No | Associated security symbols (e.g. `["AAPL.US", "700.HK"]`) |
| `└ hashtags` | array | No | Associated hashtag names |
| `└ images` | array | No | Images attached to the topic |
| `└ likes_count` | integer | No | Number of likes |
| `└ comments_count` | integer | No | Number of comments |
| `└ views_count` | integer | No | Number of views |
| `└ shares_count` | integer | No | Number of shares |
| `└ topic_type` | string | No | Topic type. One of `article`, `post` |
| `└ detail_url` | string | No | Link to the topic detail page |
| `└ created_at` | string | No | Unix timestamp (seconds) when the topic was created |
| `└ updated_at` | string | No | Unix timestamp (seconds) when the topic was last updated |
| `└ title` | string | No | Topic title (may be empty for short posts) |
| `└ body` | string | No | Full topic body in Markdown format |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"items": [
{
"id": "39304657",
"title": "My Analysis on AAPL",
"description": "A brief summary of my article...",
"body": "Full markdown content here...",
"topic_type": "article",
"tickers": [
"AAPL.US"
],
"hashtags": [
"earnings"
],
"images": [],
"likes_count": 12,
"comments_count": 3,
"views_count": 200,
"shares_count": 1,
"license": 1,
"detail_url": "https://longbridge.com/topics/39304657",
"author": {
"member_id": "10086",
"name": "John",
"avatar": "https://example.com/avatar.jpg"
},
"created_at": "1742000000",
"updated_at": "1742000000"
}
]
}
}
```
#### Topic Detail
`GET` `/v1/content/topics/{id}`
Get the full details of a community topic by its ID, including the body (Markdown), author info, associated tickers and hashtags, engagement counts, and the direct URL. View the topic on [Topics](https://longbridge.com/topics).
##### Parameters
###### Path Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | string | Yes | Topic ID (e.g. `6993508780031016960`) |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/content/topics/' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `item` | object | Yes | Topic detail object |
| `└ id` | string | Yes | Topic ID |
| `└ title` | string | No | Title (may be empty for short posts) |
| `└ description` | string | No | Plain-text excerpt |
| `└ body` | string | No | Markdown body |
| `└ topic_type` | string | Yes | Content type: `article` or `post` |
| `└ tickers` | string[] | No | Associated security symbols (e.g. `["AAPL.US", "700.HK"]`) |
| `└ hashtags` | string[] | No | Hashtag names |
| `└ images` | object[] | No | Attached images |
| `└ ∟ url` | string | No | Original image URL |
| `└ ∟ sm` | string | No | Small thumbnail URL |
| `└ ∟ lg` | string | No | Large image URL |
| `└ likes_count` | int32 | No | Likes count |
| `└ comments_count` | int32 | No | Replies count |
| `└ views_count` | int32 | No | Views count |
| `└ shares_count` | int32 | No | Shares count |
| `└ detail_url` | string | No | URL to the topic detail page |
| `└ author` | object | No | Author info |
| `└ ∟ member_id` | string | No | Author member ID |
| `└ ∟ name` | string | No | Author display name |
| `└ ∟ avatar` | string | No | Author avatar URL |
| `└ created_at` | string | Yes | Creation time as Unix timestamp (seconds) |
| `└ updated_at` | string | No | Last updated time as Unix timestamp (seconds) |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"item": {
"id": "6993508780031016960",
"title": "My Analysis on AAPL",
"description": "Brief plain-text summary...",
"body": "**Bullish** on AAPL because...",
"topic_type": "article",
"tickers": [
"AAPL.US"
],
"hashtags": [
"earnings"
],
"images": [
{
"url": "https://cdn.longbridge.com/img/abc.jpg",
"sm": "https://cdn.longbridge.com/img/abc_sm.jpg",
"lg": "https://cdn.longbridge.com/img/abc_lg.jpg"
}
],
"likes_count": 42,
"comments_count": 7,
"views_count": 1500,
"shares_count": 3,
"detail_url": "https://longbridge.com/topics/6993508780031016960",
"author": {
"member_id": "10086",
"name": "Jane Doe",
"avatar": "https://example.com/avatar.jpg"
},
"created_at": "1742000000",
"updated_at": "1742001000"
}
}
}
```
### Sharelist
#### List Sharelists
`GET` `/v1/sharelists`
Get all community stock lists (sharelists) created by or subscribed to by the current user.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `type` | string | No | Filter: `mine` or `subscribed`. Omit for both. |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/sharelists' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `sharelists` | object[] | No | User's own sharelists |
| `subscribed_sharelists` | object[] | No | Subscribed sharelists |
| `tail_mark` | string | No | Pagination cursor for subscribed list |
| `id` | integer | Yes | Sharelist ID |
| `description` | string | No | Description |
| `cover` | string | No | Cover image URL |
| `subscribers_count` | integer | No | Number of subscribers |
| `chg` | string | No | Day change percentage |
| `this_year_chg` | string | No | Year-to-date change percentage |
| `subscribed` | boolean | No | Whether the current user is subscribed |
| `sharelist_type` | integer | No | Type: `0`=regular, `3`=official, `4`=industry |
| `industry_code` | string | No | Industry code (for industry sharelists) |
| `symbol` | string | Yes | Security symbol |
| `code` | string | No | Ticker code |
| `market` | string | No | Market |
| `intro` | string | No | Brief description |
| `last_done` | string | No | Latest price |
| `change` | string | No | Day change percentage |
| `trade_status` | integer | No | Trade status code |
| `latency` | boolean | No | Whether quote data is delayed |
| `unread_change_log_category` | string | No | Unread change log category |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"mine": [
{
"id": 15921,
"name": "AI Picks",
"type": "Regular",
"day_change": "-0.40",
"ytd_change": "6.64",
"subscribers": 500
}
],
"subscribed": []
}
}
```
#### Create Sharelist
`POST` `/v1/sharelists`
Create a new community stock list with an optional initial set of securities.
##### Parameters
###### Request Body
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `name` | string | Yes | Sharelist name (required) |
| `cover` | string | Yes | Cover image URL (required) |
| `description` | string | Yes | Description |
| `securities` | array | No | Initial list of security symbols, e.g. `["AAPL.US", "NVDA.US"]` |
##### Request Example
```bash
curl --request POST \
--url 'https://openapi.longbridge.com/v1/sharelists' \
--header 'Authorization: Bearer ' \
--header 'Content-Type: application/json' \
--data '{"description":"","securities":[]}'
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | int64 | Yes | ID of the newly created sharelist |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"id": 15922
}
}
```
#### Add Securities to Sharelist
`POST` `/v1/sharelists/{id}/items`
Add one or more securities to a sharelist.
##### Parameters
###### Path Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | integer | Yes | Sharelist ID |
###### Request Body
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbols` | string | Yes | Comma-separated security symbols, e.g. `AAPL.US,700.HK` (NOT a JSON array) |
##### Request Example
```bash
curl --request POST \
--url 'https://openapi.longbridge.com/v1/sharelists//items' \
--header 'Authorization: Bearer ' \
--header 'Content-Type: application/json' \
--data '{"symbols":[]}'
```
##### Response
###### Response JSON Example
```json
{
"code": 0,
"message": "success"
}
```
#### Remove Securities from Sharelist
`DELETE` `/v1/sharelists/{id}/items`
Remove one or more securities from a sharelist.
##### Parameters
###### Path Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | integer | Yes | Sharelist ID |
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbols` | array | Yes | Security symbols to remove |
##### Request Example
```bash
curl --request DELETE \
--url 'https://openapi.longbridge.com/v1/sharelists//items?symbols=' \
--header 'Authorization: Bearer '
```
##### Response
###### Response JSON Example
```json
{
"code": 0,
"message": "success"
}
```
#### Sort Securities in Sharelist
`POST` `/v1/sharelists/{id}/items/sort`
Reorder the securities in a sharelist. The symbols list defines the new order.
##### Parameters
###### Path Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | integer | Yes | Sharelist ID |
###### Request Body
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `symbols` | string | Yes | Comma-separated security symbols, e.g. `AAPL.US,700.HK` (NOT a JSON array) |
##### Request Example
```bash
curl --request POST \
--url 'https://openapi.longbridge.com/v1/sharelists//items/sort' \
--header 'Authorization: Bearer ' \
--header 'Content-Type: application/json' \
--data '{"symbols":[]}'
```
##### Response
###### Response JSON Example
```json
{
"code": 0,
"message": "success"
}
```
#### Popular Sharelists
`GET` `/v1/sharelists/popular`
Get popular/trending sharelists from the community.
##### Parameters
###### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `count` | integer | No | Maximum number of results, default 20 |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/sharelists/popular' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `sharelists` | object[] | No | User's own sharelists |
| `└ id` | string | No | Sharelist ID |
| `└ subscribers_count` | integer | No | Number of subscribers |
| `└ stocks_count` | integer | No | Number of securities in the list. |
| `└ name` | string | No | Security name. |
| `└ description` | string | No | Description |
| `└ cover` | string | No | Cover image URL |
| `└ created_at` | string | No | Unix timestamp (seconds) when the topic was created |
| `└ this_year_chg` | string | No | Year-to-date change percentage |
| `└ status` | integer | No | Final run status: `succeeded` / `interrupted` / `failed` / `stopped` |
| `└ edited_at` | string | No | Last edit time. |
| `└ digest` | string | No | Short description / digest. |
| `└ creator` | object | No | Creator user name. |
| `└ ∟ id` | string | No | Sharelist ID |
| `└ ∟ name` | string | No | Security name. |
| `└ ∟ avatar` | string | No | Author avatar URL |
| `└ ∟ member_id` | string | No | Author member ID |
| `└ ∟ scopes` | object | No | Subscription scope info |
| `└ ∟ ∟ followed` | boolean | No | Whether the current user follows this list. |
| `└ ∟ ∟ following` | boolean | No | Whether following the creator. |
| `└ ∟ ∟ self` | boolean | No | Whether the list belongs to the current user. |
| `└ ∟ ∟ blocked` | boolean | No | Whether blocked by the current user. |
| `└ ∟ ∟ special_following` | boolean | No | Whether specially followed. |
| `└ ∟ ∟ be_blocked` | boolean | No | Whether the current user is blocked. |
| `└ ∟ ∟ trade_following` | boolean | No | Whether copy-trade following. |
| `└ ∟ profile_id` | string | No | Profile ID. |
| `└ ∟ group_scopes` | object | No | Group permission scopes. |
| `└ ∟ ∟ joined` | boolean | No | Whether the user has joined. |
| `└ ∟ group_member` | string | No | Whether a group member. |
| `└ ∟ description` | string | No | Description |
| `└ ∟ invite_code` | string | No | Invitation code. |
| `└ ∟ cert_scopes` | object | No | Certification scopes. |
| `└ ∟ ∟ official` | boolean | No | Whether an official list. |
| `└ ∟ ∟ cert_Info` | object | No | Certification info. |
| `└ ∟ ∟ ∟ label` | string | No | Label. |
| `└ ∟ ∟ ∟ name` | string | No | Security name. |
| `└ ∟ ∟ ∟ desc` | string | No | Description of current valuation |
| `└ ∟ ∟ ∟ icon` | string | No | Icon URL |
| `└ ∟ ∟ security_live_info` | string | No | Security live-stream info. |
| `└ ∟ certification` | boolean | No | Certification. |
| `└ stocks` | array | No | Constituent stocks |
| `└ subscribed` | boolean | No | Whether the current user is subscribed |
| `└ stock_group_id` | string | No | Stock-group ID. |
| `└ last_read_log_id` | string | No | Last-read change-log ID. |
| `└ chg` | string | No | Day change percentage |
| `└ group_id` | string | No | Group ID. |
| `└ sharelist_type` | integer | No | Type: `0`=regular, `3`=official, `4`=industry |
| `└ industry_code` | string | No | Industry code (for industry sharelists) |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"list": [
{
"id": 123,
"name": "AI Picks",
"description": "Top AI infrastructure stocks"
},
{
"id": 456,
"name": "EV Leaders",
"description": "Electric vehicle sector leaders"
}
]
}
}
```
#### Sharelist Detail
`GET` `/v1/sharelists/{id}`
Get sharelist detail including name, description, and constituent stocks.
##### Parameters
###### Path Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | integer | Yes | Sharelist ID |
##### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/sharelists/' \
--header 'Authorization: Bearer '
```
##### Response
###### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `sharelist` | object | Yes | Sharelist information |
| `scopes` | object | No | Subscription scope info |
| `id` | integer | Yes | Sharelist ID |
| `description` | string | No | Description |
| `cover` | string | No | Cover image URL |
| `subscribers_count` | integer | No | Number of subscribers |
| `chg` | string | No | Day change percentage |
| `this_year_chg` | string | No | Year-to-date change |
| `subscribed` | boolean | No | Whether subscribed |
| `sharelist_type` | integer | No | Type: `0`=regular, `3`=official, `4`=industry |
| `industry_code` | string | No | Industry code |
| `is_self` | boolean | No | Whether the current user is the creator |
| `subscription` | boolean | No | Whether the current user is subscribed |
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"id": 123,
"name": "AI Picks",
"description": "Top AI infrastructure stocks",
"securities": [
"AAPL.US",
"NVDA.US"
]
}
}
```
#### Delete Sharelist
`DELETE` `/v1/sharelists/{id}`
Permanently delete a sharelist you own. This action cannot be undone.
##### Parameters
###### Path Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | integer | Yes | Sharelist ID (path parameter) |
##### Request Example
```bash
curl --request DELETE \
--url 'https://openapi.longbridge.com/v1/sharelists/' \
--header 'Authorization: Bearer '
```
##### Response
###### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {}
}
```
## Screener
### Screener Search
`POST` `/v1/quote/ai/screener/search`
Filter stocks by strategy ID or custom indicator conditions, with pagination support.
#### Parameters
##### Request Body
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `market` | string | Yes | Market to screen, e.g. `US`, `HK`, `CN`. When a strategy is used, taken from the strategy. |
| `filters` | array | Yes | Filter conditions. Each item is `{ "key": "filter_pettm", "min": "10", "max": "30", "tech_values": {} }`. |
| `returns` | array | Yes | Indicator keys to return for each match, e.g. `filter_pettm`. |
| `page` | integer | Yes | Page number (0-indexed). |
| `size` | integer | Yes | Page size. |
#### Request Example
```bash
curl --request POST \
--url 'https://openapi.longbridge.com/v1/quote/ai/screener/search' \
--header 'Authorization: Bearer ' \
--header 'Content-Type: application/json' \
--data '{"market":"","filters":[],"returns":[],"page":0,"size":0}'
```
#### Response
##### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `total` | integer | No | Total number of matching stocks. |
| `items` | object[] | No | Matched stock list. |
| `└ symbol` | string | No | Security symbol, e.g. `WXT.US`. |
| `└ name` | string | No | Security name. |
| `└ indicators` | object[] | No | Indicator values for this stock. |
| `└ ∟ key` | string | No | Indicator key, e.g. `filter_pettm`. |
| `└ ∟ name` | string | No | Indicator display name. |
| `└ ∟ value` | string | No | Indicator value as a string; empty when unavailable. |
| `└ ∟ unit` | string | No | Value unit, e.g. `%`, `B`. |
##### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"total": 88,
"page": 0,
"market": "US",
"items": [
{
"symbol": "AAPL.US",
"name": "Apple Inc.",
"prevchg": 0.62,
"marketcap": 3241500000000,
"pettm": 32.15,
"pbmrq": 50.21,
"salesgrowthyoy": 8.04
},
{
"symbol": "MSFT.US",
"name": "Microsoft",
"prevchg": 1.05,
"marketcap": 3085000000000,
"pettm": 35.42,
"pbmrq": 12.87,
"salesgrowthyoy": 12.61
}
]
}
}
```
### Screener Indicators
`GET` `/v1/quote/ai/screener/indicators`
Get all indicator definitions supported by the [stock screener](https://longbridge.com/screener), including keys, names, units, and available ranges. Use these to build custom filter conditions.
#### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/ai/screener/indicators' \
--header 'Authorization: Bearer '
```
#### Response
##### Response Properties
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `groups` | object[] | No | Indicator groups |
| `└ group_type` | string | No | Group type. |
| `└ group_name` | string | No | Group name |
| `└ indicators` | object[] | No | Indicators in this group |
| `└ ∟ id` | integer | No | Indicator ID (string) |
| `└ ∟ key` | string | No | Indicator key, e.g. `filter_pettm`. |
| `└ ∟ name` | string | No | Indicator display name |
| `└ ∟ places` | integer | No | Number of decimal places. |
| `└ ∟ category` | integer | No | Company category |
| `└ ∟ tech_indicators` | array | No | Technical indicator options. |
| `└ ∟ default_range` | object | No | Default value range. |
| `└ ∟ unit` | string | No | Unit (e.g. `%`, `B`) |
##### Response JSON Example
```json
{
"code": 0,
"message": "success",
"data": {
"groups": [
{
"group_name": "Company Size & Financials",
"indicators": [
{
"id": "1",
"key": "marketcap",
"name": "Market Cap",
"unit": "B",
"min": null,
"max": null
}
]
}
]
}
}
```
### Preset Screener Strategies
`GET` `/v1/quote/ai/screener/strategies/recommend`
Get the list of platform-preset stock screener strategies, including recent average daily change and constituent stocks.
#### Parameters
##### Query Parameters
| Name | Type | Required | Description |
| --- | --- | --- | --- |
| `market` | string | No | Market filter: `US`, `HK`, `CN`, `SG`. Default: `US` |
#### Request Example
```bash
curl --request GET \
--url 'https://openapi.longbridge.com/v1/quote/ai/screener/strategies/recommend' \
--header 'Authorization: Bearer