# Longbridge Developers Documentation
# Index
| 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 |
### 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 revoke access, go to your Longbridge account → Security Settings → manage authorized apps.
## Zh-CN
### Pricing
### Skill
#### Install
### Docs
#### Socket
##### Protocol
#### Screener
#### Assets
#### Fundamental
##### Fundamental
##### Market
#### Ai
##### Chat
##### Workspace
#### Quote
##### Pull
##### Push
##### Stocks
##### Security
##### Subscribe
##### Watchlist
#### Legal
#### Cli
##### Ipo
##### Fundamentals
##### Orders
##### Market-data
##### Quant
##### Watchlist
##### Derivatives
##### Account
##### Content
##### Research
#### Market
##### Calendar
#### Trade
##### Order
##### Execution
##### Asset
#### Qa
#### Account
##### Portfolio
##### Dca
##### Alert
#### Content
##### Sharelist
##### Topics
##### News
## Longbridge-terminal
## Docs
## API Reference
## Getting Started
## 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 and Data Centers
Two concepts that are easy to confuse:
- **Access point** (`.com` / `.cn`) — network routing only. Both serve identical data and identical auth: a token issued through one is accepted by the other.
- **Data center** (`ap` / `us`) — where the account itself lives. It determines which US-only APIs are available.
The two cannot be combined freely:
| Data center | `.com` | `.cn` |
| ------------------------- | ---------------------------------- | ------------- |
| `us` (US accounts) | Yes — the only usable access point | Not supported |
| `ap` (Longbridge SG / HK) | Yes | Yes |
`.cn` has no route to the US data center, so US accounts must always use the `.com` domains — including for login, since the `.cn` login page does not offer US accounts.
## Time Format
All API response are used [Unix Timestamp](https://en.wikipedia.org/wiki/Unix_time), timezone is UTC.
## Environment Requirements
- 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.
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.
## Get Socket OTP (One time password)
# 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
}
}
```
## Changelog
## 2026-07-20
- **US accounts can sign in to Longbridge Developers** — US accounts are now supported for login and API access. Note that the mainland-China `.cn` domains (`openapi.longbridge.cn`, `openapi-quote.longbridge.cn`, `openapi-trade.longbridge.cn`) do not serve US accounts; use the default domains instead
- **Longbridge MCP supports US accounts** — US accounts can complete OAuth authorization on `https://mcp.longbridge.com` and requests route to the US data center; the `https://mcp.longbridge.cn` endpoint serves AP accounts only
### SDK v4.4.0
- **US market APIs** — 14 new methods across `FundamentalContext` (9), `QuoteContext` (1), `TradeContext` (4); all US data-center only
### CLI v0.25.0
- **US data center is live** — US accounts can log in through `auth login` (device flow or `--auth-code`), and requests route to the data center matching the token; `auth status` reports the active DC region
- **US market routing** — `company`, `valuation`, `financial-report`, `consensus`, `dividend`, `order`, `positions` now route to US APIs automatically for US data-center accounts
- **New `etf-docs` command** — list regulatory documents (prospectus, fact sheets) for US ETFs
- **New `financial-report key-metrics` subcommand** — key financial metrics for US stocks (annual/quarterly)
- **New `profit-analysis realized` subcommand** — realized P&L breakdown by asset category for US accounts (stock/option/crypto)
- **New `order --action` flag** — filter US order history by direction (buy/sell)
- **New `order detail --attached` flag** — show attached child order for US accounts
- **Navi scripting on the quant platform** — `quant run` now targets the v2 API and supports Navi alongside PineScript via `--language navi|pine` (Navi is the default)
## 2026-06-25
### SDK v4.3.3
- **Macroeconomic indicators** — Two new `FundamentalContext` methods: `macroeconomic_indicators` lists all indicators (filter by country, keyword search), `macroeconomic` returns historical release data (actual / forecast / previous values) for a given indicator code
### CLI v0.24.0
- **New `macrodata` command** — Browse 400+ macro indicators across US/HK/CN/EU/JP/SG and query historical release data with actual, forecast, previous, and revised values; supports `--country`, `--keyword`, `--lang`, `--start`, `--end`, `--limit`, `--page`, `--format json`
- MCP server updated in sync — `macrodata_indicators` and `macrodata` tools now available to AI agents via the Longbridge MCP server
## 2026-06-16
### CLI v0.23.2
- **Local-time date parsing** — date-only and legacy minute-resolution datetime arguments are interpreted in the user's local timezone before API calls, with RFC 3339 inputs supported for explicit timezone-safe workflows
- **`market-status` US post-market fix** — US status code `203` now displays as `Post-Market` instead of `Trading`, correcting the after-hours market label
## 2026-06-04
### CLI v0.22.4
- **`constituent` now supports ETFs** — ETF symbols return an asset-allocation breakdown (holdings / regional / asset-class / industry); for US ETFs, the complete portfolio holdings are fetched from SEC EDGAR N-PORT filings by default (weight, shares, market value), with fallback to the platform's asset-allocation summary; index symbols behave exactly as before
## 2026-06-03
### CLI v0.22.3
- **`quote` now includes the US overnight session** — `--format json` populates `overnight_quote` alongside `pre_market_quote` and `post_market_quote`, completing after-hours coverage for AI workflows
- **Account-type banner on holdings commands** — `positions`, `fund-positions`, `assets`, and `portfolio` print a one-line banner (`Live A/C` / `Demo A/C`) before the table, making it clear which account the data belongs to
## 2026-06-02
### CLI v0.22.2
- **JSON timestamps now RFC 3339** — time-series and history commands (`kline`, `trades`, `intraday`, `capital-flow`, etc.) and account P&L flows output ISO 8601 / RFC 3339 datetimes instead of raw Unix epochs, making JSON output directly consumable by AI agents and downstream tools
- **`market-temp --history` default range** — omitting `--start` now returns a full month of data instead of a single day
## 2026-05-22
### CLI v0.22.0
- **`shareholder --top`** — Top-20 major shareholders (institutions, individuals, insiders) with multi-period comparison; `--object-id 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.
| 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 |
| HTTP Method | GET |
| HTTP URL | /v1/ai/workspaces/:id/agents |
| User Type | The maximum number of targets that can be queried per month |
|---|---|
| User account opening | |
| Total assets reach HKD 10,000 | |
| Total assets reach HKD 80,000 | |
| Total assets reach 400,000 HKD or the number of transactions per month is greater than 160 | |
| Total assets reach 4 million HKD or the number of transactions per month is greater than 1,600 | |
| Total assets reach 6 million HKD or the number of transactions per month is greater than 2,500 |
| 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 |
| HTTP Method | GET |
| HTTP URL | /v1/quote/filings |
| HTTP Method | GET |
| HTTP URL | /v1/quote/get_security_list |
| HTTP Method | DELETE |
| HTTP URL | /v1/watchlist/groups |
| HTTP Method | GET |
| HTTP URL | /v1/watchlist/groups |
| HTTP Method | POST |
| HTTP URL | /v1/watchlist/groups |
| HTTP Method | PUT |
| HTTP URL | /v1/watchlist/groups |
| HTTP Method | PUT |
| HTTP URL | /watchlist/groups |
` 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)
#### Ipo
#### ipo
# 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 |
|------------|---------|---------|------------|--------------|------------|
| 翼菲科技 | 6871.HK | pending | 2026-05-07 | 2026-05-13 | 2026-05-17 |
| 英派药业-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/) guide.
#### Fundamentals
#### business-segments
# longbridge business-segments
Show revenue breakdown by business segment for a company — current period totals or historical trends across reporting periods.
## Basic Usage
```bash
longbridge business-segments AAPL.US
```
```
Period: Q1 FY2026 Total: 124,300,000,000 Currency: USD
| segment | amount | share |
|-------------------|-----------------|--------|
| iPhone | 69,140,000,000 | 55.62% |
| Services | 26,340,000,000 | 21.19% |
| Mac | 7,940,000,000 | 6.39% |
| iPad | 8,090,000,000 | 6.51% |
| Wearables & Other | 12,790,000,000 | 10.29% |
```
## Examples
### Current period breakdown
```bash
longbridge business-segments AAPL.US
```
Shows each business segment's revenue and its share of total revenue for the most recent reporting period.
### Historical segment trends
```bash
longbridge business-segments AAPL.US --history
```
Returns segment revenue across multiple reporting periods so you can track how the revenue mix has shifted over time.
### Filter by report type
```bash
longbridge business-segments AAPL.US --history --report af
```
Use `--report` to scope the history to a specific period type: `af` (annual), `saf` (semi-annual), `qf` (quarterly).
## Options
| Flag | Description |
|------|-------------|
| `--history` | Show historical segment data across multiple periods |
| `--report ` | Period type filter: `af` (annual), `saf` (semi-annual), `qf` (quarterly) |
| `--format json` | Output raw JSON |
#### valuation
# 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.
:::info US Accounts
For `.US` symbols on US data-center accounts, `valuation` routes to the US valuation overview API automatically.
:::
#### finance-calendar
# longbridge finance-calendar
Browse upcoming financial events — earnings reports, dividend payments, stock splits, IPOs, and macrodata releases — filtered by symbol, watchlist, market, or event type.
## Subcommands
| Subcommand | Description |
| ----------- | ------------------------------------------- |
| `report` | Earnings reports (upcoming and recent) |
| `dividend` | Dividend announcements |
| `split` | Stock splits and merges |
| `ipo` | IPO listings |
| `macrodata` | Macrodata releases |
| `closed` | Market closure days |
## Examples
### Upcoming earnings reports
```bash
longbridge finance-calendar report
```
Shows upcoming earnings events from today. Displays EPS and revenue estimates alongside actual results for recently reported quarters. You can also view the same earnings events on web and mobile in the ["Stock Earnings Calendar"](https://longbridge.com/calendar/report).
### Earnings for watchlist stocks
```bash
longbridge finance-calendar report --filter watchlist --market US
```
Scopes the earnings calendar to US stocks in your watchlist. Use `--filter positions` to limit to your current holdings instead.
### Dividends for held positions
```bash
longbridge finance-calendar dividend --filter positions
```
Lists dividend events only for stocks you currently hold. Useful for tracking upcoming ex-dividend and payment dates.
### Stock splits and merges in HK market
```bash
longbridge finance-calendar split --market HK
```
Shows both split and merge events for Hong Kong-listed stocks.
### High-importance macro events
```bash
longbridge finance-calendar macrodata --star 3
```
Filters macrodata events to only show high-importance releases (3-star). Covers data like CPI, NFP, Fed rate decisions, and similar market-moving events.
### IPO calendar
```bash
longbridge finance-calendar ipo
```
Shows upcoming IPOs across supported markets. Combine with `--market` to filter by a specific exchange.
#### industry-rank
# longbridge industry-rank
Rank all industries in a market by a chosen indicator — see which sectors are leading today, which have the strongest revenue growth, or which are attracting the most capital.
## Basic Usage
```bash
longbridge industry-rank --market US
```
```
| rank | name | counter_id | chg | indicator |
|------|-----------------------------------------|-----------------|--------|-----------|
| 1 | Semiconductors | BK/US/IN00258 | +3.82% | ... |
| 2 | Software - Infrastructure | BK/US/IN00305 | +2.91% | ... |
| 3 | Biotechnology | BK/US/IN00043 | +2.54% | ... |
| 4 | Electronic Components | BK/US/IN00099 | +1.98% | ... |
| 5 | Asset Management | BK/US/IN00033 | +1.73% | ... |
```
The `counter_id` column (e.g. `BK/US/IN00258`) can be passed directly to [`industry-peers`](./industry-peers) to explore the competitive tree within that sector.
## Examples
### Leading industries today
```bash
longbridge industry-rank --market US
```
Ranks industries by daily price performance. Replace `US` with `HK`, `CN`, or `SG` to switch markets.
### Top industries by market cap
```bash
longbridge industry-rank --market HK --indicator market-cap
```
### Top industries by revenue growth
```bash
longbridge industry-rank --market CN --indicator revenue-growth
```
### Then drill into a sector
```bash
# Get the counter_id from industry-rank, then explore its sub-sectors
longbridge industry-peers BK/US/IN00258
```
## Options
| Flag | Description |
|------|-------------|
| `--market ` | Market to rank: `US`, `HK`, `CN`, `SG` |
| `--indicator ` | Ranking indicator (see below) |
| `--format json` | Output raw JSON |
### Indicators
| Value | Description |
|-------|-------------|
| `leading-gainer` | Daily price performance (default) |
| `today-trend` | Intraday trend strength |
| `popularity` | Search and watchlist activity |
| `market-cap` | Total market capitalisation |
| `revenue` | Latest revenue |
| `revenue-growth` | YoY revenue growth rate |
| `net-profit` | Latest net profit |
| `net-profit-growth` | YoY net profit growth rate |
#### industry-valuation
# longbridge industry-valuation
Compare a stock's valuation against industry peers (PE/PB/EPS/Dividend Yield), or view its percentile ranking within the industry.
## Basic Usage
```bash
longbridge industry-valuation AAPL.US
```
```
| symbol | name | market_cap | price | pe | pb | eps | div_yld |
|---------|----------|-------------|-----------|---------|--------|----------|---------|
| AAPL.US | Apple | USD3.82T | USD260.48 | 34.14x | 43.36x | USD7.88 | 0.40% |
| SNDK.US | SanDisk | USD1257.22B | USD851.77 | -76.61x | 12.31x | USD-7.15 | 0.00% |
| WDC.US | WDC | USD1164.36B | USD343.43 | 63.14x | 16.37x | USD10.09 | 0.13% |
```
## Examples
### Peer comparison table
```bash
longbridge industry-valuation AAPL.US
longbridge industry-valuation TSLA.US --currency USD
```
Shows a comparison table of the stock and its industry peers with PE, PB, EPS, and dividend yield metrics.
### Percentile distribution
```bash
longbridge industry-valuation dist AAPL.US
longbridge industry-valuation dist 700.HK
```
```
| metric | current | low | median | high | rank | percentile |
|--------|---------|-------|--------|--------|-------|------------|
| PE | 32.47x | 0.82x | 17.38x | 55.69x | 17/19 | 88.9% |
| PB | 43.36x | 0.05x | 1.58x | 43.36x | 32/32 | 100.0% |
| PS | 8.78x | 0.01x | 0.92x | 94.81x | 33/41 | 80.0% |
```
Shows where the stock's PE/PB/PS sits within the industry distribution as a percentile ranking.
### JSON output
```bash
longbridge industry-valuation TSLA.US --format json
longbridge industry-valuation dist TSLA.US --format json
```
#### corp-action
# longbridge corp-action
View corporate actions for a stock — splits, dividends, rights issues, and more.
## Basic Usage
```bash
longbridge corp-action 700.HK
```
```
| date | date_type | action | description |
|----------|-----------|-----------|----------------------|
| 20260601 | Pay Date | Dividend | HKD 5.3 per share |
| 20260518 | Record | Dividend | HKD 5.3 per share |
| 20260515 | Ex-Date | Dividend | HKD 5.3 per share |
| 20260318 | | Earnings | FY2025 Q4 Revenue 216.1B, Net Income 64.8B |
...
```
## Examples
### View corporate actions
```bash
longbridge corp-action 700.HK
longbridge corp-action AAPL.US
```
Lists historical corporate actions including stock splits, dividend distributions, and rights offerings.
### JSON output
```bash
longbridge corp-action TSLA.US --format json
```
#### industry-peers
# longbridge industry-peers
Explore the hierarchical sub-sector tree for an industry group. Takes a BK counter ID from [`industry-rank`](./industry-rank) and expands it into a full competitive landscape — sub-sectors, their sub-sectors, and the stocks in each.
## Basic Usage
```bash
longbridge industry-peers BK/US/IN00258
```
```
Root: Semiconductors (US)
├── Design & Fabless 23 stocks +3.12% YTD +18.4%
│ ├── GPU & AI Chips 8 stocks +4.91% YTD +24.1%
│ ├── Mobile SoC 6 stocks +2.33% YTD +12.8%
│ └── Analog IC 9 stocks +1.54% YTD +9.3%
├── Foundry & Manufacturing 7 stocks +2.87% YTD +15.6%
│ ├── Logic Foundry 3 stocks +3.11% YTD +19.2%
│ └── Memory 4 stocks +2.61% YTD +11.9%
└── Equipment & Materials 12 stocks +1.43% YTD +7.2%
```
## Examples
### Explore a sector from industry-rank
```bash
# Step 1: find a sector
longbridge industry-rank --market US
# Step 2: drill into it using the counter_id column
longbridge industry-peers BK/US/IN00258
```
### HK sector tree
```bash
longbridge industry-peers BK/HK/IN00012
```
Works the same way across markets — use counter IDs from `industry-rank --market HK`, `--market CN`, or `--market SG`.
## Options
| Flag | Description |
|------|-------------|
| `--format json` | Output raw JSON |
## Notes
- Counter IDs follow the format `BK//IN` — copy them directly from `industry-rank` output
- Each node shows stock count, daily change, and YTD change
#### operating
# 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
```
#### consensus
# longbridge consensus
See Wall Street's consensus financial estimates — revenue, EBIT, and EPS — for upcoming earnings periods.
## Basic Usage
```bash
longbridge consensus TSLA.US
```
```
Currency: USD | Period: qf
| metric | Q3 2026 | Q2 2026 | Q1 2026 | Q4 2025 | Q3 2025 |
|---------------|---------|---------|----------|-----------|----------|
| Revenue | ~27.14B | ~24.71B | ~22.75B | 24.90B ↑ | 28.09B ↑ |
| Net Income | ~1.28B | ~1.08B | ~879.54M | 840.00M ↓ | 1.37B ↓ |
| EPS | ~0.3818 | ~0.2969 | ~0.2390 | 0.2400 ↓ | 0.3900 ↓ |
...
```
## Examples
### Check consensus estimates
```bash
longbridge consensus TSLA.US
```
Displays the analyst consensus estimates for the upcoming reporting period, covering key metrics like revenue, EBIT, and EPS.
### JSON output
```bash
longbridge consensus TSLA.US --format json
```
```json
{
"currency": "USD",
"current_period": "qf",
"list": [
{
"details": [
{ "key": "revenue", "name": "Revenue", "estimate": "27144782630.0000", "is_released": false },
{ "key": "ebit", "name": "EBIT", "estimate": "1496709370.0000", "is_released": false }
]
}
]
}
```
Each `details` entry includes the metric key, the consensus estimate value, and whether the actual result has already been released. `current_index` in the full response indicates which period in the list is the current one.
:::info US Accounts
For `.US` symbols on US data-center accounts, `consensus` routes to the US analyst consensus API automatically.
:::
#### company
# longbridge company
View a company's profile — founding date, employee count, IPO price, headquarters address, and more.
## Basic Usage
```bash
longbridge company AAPL.US
```
```
Name Apple Inc.
Founded 1976
Market NASDAQ Global Select
CEO Timothy D. Cook
Employees 166000
Address One Apple Park Way, Cupertino, California, United States
Website www.apple.com
Phone (408) 996-1010
Year End Sep 27
```
## Examples
### View company overview
```bash
longbridge company AAPL.US
longbridge company 700.HK
```
Shows key company information including founding date, number of employees, IPO price, and registered address.
### JSON output
```bash
longbridge company TSLA.US --format json
```
:::info US Accounts
For `.US` symbols on US data-center accounts, `company` routes to the US company overview API automatically.
:::
#### institution-rating
# longbridge institution-rating
See the consensus from Wall Street analysts — buy/hold/sell distribution, price target range, and industry rankings.
## Basic Usage
```bash
longbridge institution-rating TSLA.US
```
```
Consensus:
| recommend | target | change | updated_at |
|-----------|--------|--------|-------------|
| buy | 415.78 | 20.30% | 2026-04-09 |
Rating breakdown:
| strong_buy | buy | hold | sell | under | no_opinion | total |
|------------|-----|------|------|-------|------------|-------|
| 18 | 5 | 17 | 6 | 2 | 4 | 52 |
Target price range:
| lowest_price | highest_price | prev_close |
|--------------|---------------|------------|
| 125.000 | 600.000 | 345.62 |
```
## Examples
### Check analyst consensus
```bash
longbridge institution-rating TSLA.US
```
Shows the breakdown of analyst ratings (Buy, Hold, Sell, and variants), the consensus price target range, and industry peer ranking.
### View historical rating changes over time
```bash
# Show week-by-week rating count history and individual analyst target prices
longbridge institution-rating detail TSLA.US
```
The `detail` subcommand lists the historical rating distribution by week and individual analyst price targets, so you can track how sentiment has shifted over time.
### Rating history with target price changes
```bash
longbridge institution-rating TSLA.US --history
```
Shows how the rating distribution and consensus price target have changed over time — useful for tracking momentum shifts in analyst sentiment.
### Industry-wide ranking
```bash
longbridge institution-rating TSLA.US --industry-rank
# Paginate
longbridge institution-rating TSLA.US --industry-rank --page 2 --limit 20
```
```
| key | value |
|-----------------|------------|
| industry_name | Automobile Manufacturers |
| industry_rank | 1 |
| industry_mean | 10 |
| industry_total | 30 |
items:
| symbol | name | buy | hold | sell | total | rank |
|----------|--------|-----|------|------|-------|------|
| TSLA.US | Tesla | 23 | 17 | 10 | 51 | 1 |
| GM.US | GM | 20 | 5 | 1 | 27 | 2 |
...
```
Ranks every stock in the same industry by total analyst coverage, so you can see where your stock stands relative to peers.
### JSON for monitoring
```bash
longbridge institution-rating TSLA.US --format json
```
```json
{
"analyst": {
"evaluate": {
"buy": 18,
"hold": 17,
"no_opinion": 4,
"over": 5,
"sell": 6,
"under": 2,
"total": 52
},
"target": {
"highest_price": "600.000",
"lowest_price": "125.000",
"prev_close": "345.62"
}
}
}
```
The `evaluate` object contains the per-rating counts across all 52 covering analysts. The `target` object shows the highest and lowest price targets alongside the previous close for context.
### Monthly analyst sentiment trend
```bash
longbridge institution-rating TSLA.US --views
```
```
| month | strong_buy | buy | hold | sell | under | no_opinion | total |
|---------|------------|-----|------|------|-------|------------|-------|
| 2026-04 | 18 | 5 | 17 | 6 | 2 | 4 | 52 |
| 2026-03 | 17 | 6 | 18 | 5 | 3 | 3 | 52 |
| 2026-02 | 16 | 7 | 19 | 5 | 3 | 2 | 52 |
| 2026-01 | 15 | 8 | 19 | 6 | 2 | 2 | 52 |
```
Shows how the buy/hold/sell distribution has shifted month by month, newest first. Use alongside `--history` (individual analyst target price changes) to get both perspectives on momentum.
#### financial-report
# longbridge financial-report
Fetch income statements, balance sheets, and cash flow statements for any public company.
## Basic Usage
```bash
longbridge financial-report TSLA.US --kind IS
```
```
── IS ──
| metric | Q4 2025 | Q3 2025 | Q2 2025 | Q1 2025 | Q4 2024 |
|---------------------|---------|---------|---------|---------|---------|
| EPS (USD) | 0.2404 | 0.3900 | 0.3300 | 0.1200 | 0.6104 |
| ROE | 4.15% | 6.98% | 6.17% | 2.22% | 11.90% |
| Revenue (USD) | 24.90B | 28.09B | 22.50B | 19.34B | 25.71B |
| Net Income (USD) | 840.00M | 1.37B | 1.17B | 409.00M | 2.12B |
| Gross Margin | 20.12% | 17.99% | 17.24% | 16.31% | 16.26% |
| Net Margin | 3.37% | 4.89% | 5.21% | 2.12% | 8.28% |
```
## Examples
### Get the latest income statement
```bash
longbridge financial-report TSLA.US --kind IS
```
Returns the income statement for the most recent reporting period, including EPS, revenue, and other earnings line items.
### Get all three statements
```bash
longbridge financial-report TSLA.US
```
Fetches the income statement, balance sheet, and cash flow statement together. Equivalent to `--kind ALL`.
### Get the cash flow statement
```bash
longbridge financial-report TSLA.US --kind CF
```
Returns the cash flow statement, covering operating, investing, and financing activities.
### Annual balance sheet
```bash
longbridge financial-report 700.HK --kind BS --report af
```
Retrieves the annual balance sheet for Tencent. Use `--report` to choose the reporting period: `af` (annual), `saf` (semi-annual), `q1`, `3q`, or `qf` (quarterly).
### AI earnings snapshot
```bash
longbridge financial-report snapshot AAPL.US
```
```
Apple Inc. (AAPL) Q1 FY2026 Jan 2026 – Mar 2026 USD
Apple delivered a solid quarter with revenue and EPS beating consensus
estimates. Services continued to outperform, offsetting softer iPhone
sales outside of China.
── Forecast vs Actual ──────────────────────────────────────────────
| metric | consensus | actual | beat/miss |
|---------------|-----------|---------|-----------|
| Revenue | 123.15B | 124.30B | +0.93% |
| EBIT | 34.21B | 35.43B | +3.57% |
| Net Income | 29.48B | 30.52B | +3.53% |
── Upcoming peer earnings ──────────────────────────────────────────
| company | ticker | date |
|-------------|----------|------------|
| Microsoft | MSFT.US | 2026-04-29 |
| Alphabet | GOOG.US | 2026-04-29 |
| Meta | META.US | 2026-04-30 |
```
The `snapshot` subcommand provides an AI-generated earnings summary, beat/miss analysis against consensus estimates, and upcoming earnings dates for peer companies.
```bash
# Specify a historical quarter
longbridge financial-report snapshot TSLA.US --report qf --year 2025 --period 4
```
Use `--report qf --year --period <1-4>` to retrieve a specific quarter.
### Key financial metrics (US accounts)
```bash
longbridge financial-report key-metrics AAPL.US
longbridge financial-report key-metrics AAPL.US --report qf
```
Returns key financial indicators for US stocks: revenue, net income, EPS, margins, and growth rates.
:::warning Longbridge US Accounts
`financial-report key-metrics` is only available for US data-center accounts.
:::
| Option | Description | Default |
| ------ | ----------- | ------- |
| `--report` | Reporting period: `af` (annual), `saf` (semi-annual), `qf` (quarterly), `q1` (Q1), `3q` (Q3) | af |
:::info US Accounts
For `.US` symbols on US data-center accounts, omitting `--kind` returns a financial overview via the US API.
To get detailed income statement / balance sheet / cash flow for US stocks, use the [`financial-statement`](/docs/cli/fundamentals/financial-statement) command instead.
:::
#### valuation-rank
# 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.
#### invest-relation
# longbridge invest-relation
View investment relations for a company — subsidiary and parent company relationships.
## Basic Usage
```bash
longbridge invest-relation 700.HK
```
```
Total: 30
| company | symbol | % shares | value | currency | rank |
|--------------|----------|----------|---------|----------|------|
| HUYA | HUYA.US | 67.28% | 4.74B | USD | 1 |
| China Lit. | 772.HK | 56.55% | 149.96B | HKD | 1 |
| TME | 1698.HK | 53.56% | 305.10B | HKD | 1 |
| TME | TME.US | 53.56% | 77.64B | USD | 1 |
| Yixin Group | 2858.HK | 51.79% | 75.58B | HKD | 1 |
...
```
## Examples
### View company relationships
```bash
longbridge invest-relation 700.HK
longbridge invest-relation AAPL.US
```
Displays the corporate structure including subsidiaries and parent companies.
### JSON output
```bash
longbridge invest-relation 700.HK --format json
```
#### macrodata
# longbridge macrodata
Browse macrodata indicators and their historical release data — covering US, HK, CN, EU, JP, and SG markets.
## Modes
| Mode | Usage | Description |
| ---- | ----- | ----------- |
| List | `longbridge macrodata` | List all available indicators |
| History | `longbridge macrodata ` | 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` |
#### forecast-eps
# longbridge forecast-eps
Get analyst consensus EPS forecasts for upcoming reporting periods — mean, median, highest, and lowest estimates.
## Basic Usage
```bash
longbridge forecast-eps TSLA.US
```
```
EPS Forecasts (recent 19):
| end_date | mean | median | highest | lowest | up | down | total |
|------------|-------|--------|---------|--------|----|------|-------|
| 2026-02-03 | 2.092 | 2.04 | 2.75 | 1.212 | 0 | 0 | 0 |
| 2026-02-04 | 2.092 | 2.04 | 2.75 | 1.212 | 0 | 0 | 0 |
| 2026-02-08 | 2.057 | 2.035 | 2.75 | 1.212 | 0 | 0 | 0 |
...
```
## Examples
### Check EPS forecast
```bash
longbridge forecast-eps TSLA.US
```
Displays the analyst consensus EPS forecast for each upcoming period, along with the range of estimates (highest and lowest).
### JSON for tracking estimates
```bash
longbridge forecast-eps TSLA.US --format json
```
```json
{
"items": [
{
"forecast_end_date": "1726790400",
"forecast_eps_highest": "3.79",
"forecast_eps_lowest": "2.37",
"forecast_eps_mean": "3.043",
"forecast_eps_median": "3.02",
"institution_down": 0,
"institution_total": 0,
"institution_up": 0
}
]
}
```
Each item covers one reporting period. `forecast_eps_mean` and `forecast_eps_median` represent the consensus, while `highest` and `lowest` show the range of analyst estimates.
#### compare
# longbridge compare
Cross-stock valuation comparison (PE/PB/PS/market cap/close price/ROE). When no comparison symbols are specified, the server automatically selects peers from the same industry.
## Basic Usage
```bash
longbridge compare AAPL.US
```
```
Valuation Comparison
| symbol | name | market_value | close | pe | pb | ps | roe |
|---------|-----------|--------------|----------|-------|-------|-------|--------|
| AAPL.US | Apple | $3.01T | 205.10 | 31.2 | 45.2 | 7.8 | 136.5% |
| MSFT.US | Microsoft | $3.12T | 420.30 | 35.8 | 12.1 | 12.3 | 35.2% |
```
When no peers are specified, the system automatically selects representative stocks from the same industry.
## Examples
### Auto-select industry peers
```bash
longbridge compare AAPL.US
```
The system selects industry peers automatically based on the sector classification of the primary symbol.
### Specify comparison symbols
```bash
longbridge compare AAPL.US MSFT.US GOOGL.US
```
Supports up to 5 stocks (including the primary symbol) for side-by-side comparison.
### HK stocks with currency conversion
```bash
longbridge compare 700.HK 9988.HK --currency HKD
```
Use `--currency` to unify market cap and price units when comparing across markets.
### JSON output
```bash
longbridge compare TSLA.US RIVN.US --format json
```
## Options
| Flag | Description |
|------|-------------|
| `symbol` | Primary symbol (required) |
| `[others...]` | Comparison symbols (optional, up to 4) |
| `--currency` | Normalise to a single currency: `USD`, `HKD`, or `CNY` |
| `--format` | Output format: `table` (default) or `json` |
## Notes
- When comparing across markets (e.g. US vs HK), use `--currency` to avoid FX distortions
- PE, PB, PS use TTM (trailing twelve months) data
- ROE is based on the most recent reporting period
#### financial-statement
# longbridge financial-statement
Fetch a fully detailed, line-item financial statement — income statement, balance sheet, or cash flow — for any public company.
:::info US Accounts
For `.US` symbols on US data-center accounts, `financial-statement` calls `us_financial_statement()` — the US-specific detailed statement API.
:::
## Basic Usage
```bash
longbridge financial-statement TSLA.US --kind IS
```
```
(in USD)
Q1 2026 Q4 2025 Q3 2025 Q2 2025 Q1 2025 YoY
─────────────────────────────────────────────────────────────────────────────────────────────────
Revenue
Total Operating Revenue 22.39B 24.90B 28.09B 22.50B 19.34B -10.1%
Revenue 22.39B 24.90B 28.09B 22.50B 19.34B -10.1%
Cost
Operating Cost 17.67B 19.89B 23.04B 18.62B 16.18B -11.2%
COGS 17.67B 19.89B 23.04B 18.62B 16.18B -11.2%
Gross Profit 4.72B 5.01B 5.05B 3.88B 3.15B -5.8%
...
```
## Examples
### Quarterly income statement
```bash
longbridge financial-statement TSLA.US --kind IS --report qf
longbridge financial-statement AAPL.US --kind IS --report qf
```
Returns the quarterly income statement with a side-by-side YoY comparison.
### Annual balance sheet
```bash
longbridge financial-statement TSLA.US --kind BS --report af
longbridge financial-statement 700.HK --kind BS --report af
```
Returns the full annual balance sheet with assets, liabilities, and equity breakdowns.
### Cash flow statement
```bash
longbridge financial-statement NVDA.US --kind CF
```
Returns operating, investing, and financing cash flows.
### All three statements
```bash
longbridge financial-statement AAPL.US
```
Fetches all three statement types in one call. Equivalent to `--kind ALL`.
### Cumulative period
```bash
longbridge financial-statement TSLA.US --kind IS --report cumul
```
Returns the cumulative year-to-date income statement.
### Report period options
| `--report` | Description |
|---|---|
| `af` | Annual (default) |
| `saf` | Semi-annual |
| `qf` | Quarterly |
| `cumul` | Cumulative (year-to-date) |
#### executive
# longbridge executive
View a company's executives and key personnel — names, titles, and roles.
## Basic Usage
```bash
longbridge executive AAPL.US
```
```
| name | title |
|---------------------|-------------------------------------------------|
| Timothy D. Cook | CEO & Director |
| Arthur D. Levinson | Independent Non-Executive Chairman of the Board |
| Kevan Parekh | Senior VP & CFO |
| Sabih Khan | Senior VP & Chief Operating Officer |
| Deirdre O'Brien | Senior Vice President of Retail & People |
...
```
## Examples
### List executives
```bash
longbridge executive AAPL.US
longbridge executive 700.HK
```
Displays the executive team with their names and titles.
### JSON output
```bash
longbridge executive TSLA.US --format json
```
#### dividend
# longbridge dividend
View the historical dividend payment history for a stock.
## Basic Usage
```bash
longbridge dividend 700.HK
```
```
| desc | ex_date | payment_date | record_date |
|--------------------------------------|------------|--------------|-------------|
| Dividend: HKD 5.3/share | 2026.05.15 | 2026.06.01 | 2026.05.18 |
| Dividend: HKD 4.5/share | 2025.05.16 | 2025.05.30 | 2025.05.19 |
| Dividend: HKD 3.4/share | 2024.05.17 | 2024.05.31 | 2024.05.20 |
| Dividend: HKD 2.4/share | 2023.05.19 | 2023.06.05 | 2023.05.22 |
```
## Examples
### View dividend history
```bash
longbridge dividend AAPL.US
```
Lists all historical dividend payments for Apple, including payment dates, amounts per share, and dividend type.
### HK dividend example
```bash
longbridge dividend 700.HK
```
Works the same for Hong Kong-listed stocks. Tencent pays dividends periodically and this shows the full payment history.
### Find the next ex-dividend date
```bash
# The ex_date field shows the ex-dividend date for each record
longbridge dividend AAPL.US
```
The most recent record shows the last known ex-dividend date. For upcoming dividends not yet announced, check `finance-calendar` with the `dividend` type.
### View dividend distribution scheme details
```bash
# Show detailed dividend distribution scheme (lot size, currency, ratio)
longbridge dividend detail AAPL.US
```
The `detail` subcommand shows the full distribution scheme — useful when a dividend includes bonus shares or rights alongside cash.
### JSON for automation
```bash
longbridge dividend AAPL.US --format json
```
Returns structured JSON with `ex_date`, `payment_date`, `record_date`, and a `desc` field containing the dividend amount description (e.g., `"Dividend: USD 0.26/share"`) — suitable for piping into scripts or tracking tools.
:::info US Accounts
For US data-center accounts: `.US` ETF symbols route to the US ETF dividend API; `.US` stock symbols route to the US company dividends API.
:::
#### etf-docs
# longbridge etf-docs
List regulatory documents for a US ETF — prospectus, fact sheets, and other filings.
:::warning Longbridge US Accounts
This command is only available for US data-center accounts.
:::
## Basic Usage
```bash
longbridge etf-docs IVV.US
```
```
Name
----
iShares Core S&P 500 ETF Prospectus
iShares Core S&P 500 ETF Statement of Additional Information
iShares Core S&P 500 ETF Annual Report
...
```
## Examples
### List ETF documents
longbridge etf-docs IVV.US
longbridge etf-docs SPY.US
### Limit number of results
```bash
longbridge etf-docs IVV.US --limit 5
```
## Options
| Option | Description | Default |
| ------ | ----------- | ------- |
| `--limit` | Maximum number of documents to return | 10 |
#### Orders
#### max-qty
# 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/) for setup details.
#### exchange-rate
# 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.
#### margin-ratio
# 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/) for setup details.
#### order
# 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
Only orders in cancellable states (New, PartialFilled, etc.) are accepted. Use `-y` to skip the confirmation prompt in scripts.
### 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. Use `-y` to skip the confirmation prompt in scripts.
## Options
| Option | Description | Default |
| ------ | ----------- | ------- |
| `--action` | Filter by side: `buy` \| `sell` (US accounts) | — |
| `--attached` | Show attached child order in `order detail` (US accounts) | false |
## Requirements
OAuth trade permission is required to place, cancel, or replace orders. See the [trade permission setup](/docs/trade/) guide to enable trading access.
## Notes
`buy` and `sell` always prompt for confirmation before submitting. Use `-y` with `cancel` and `replace` to skip confirmation in scripting contexts.
#### Market-data
#### trade-stats
# longbridge trade-stats
View trade statistics — price distribution by volume for a stock.
> **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: not supported.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## 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
```
#### intraday
# longbridge intraday
Get minute-by-minute price and volume data (intraday line) for any symbol — today's live data or a historical date.
> **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)".
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## 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.
#### anomaly
# longbridge anomaly
Detect unusual market movements and quote anomalies — price spikes, volume surges, and other abnormal activity.
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## 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.
#### brokers
# longbridge brokers
See which broker IDs are present at each price level in the HK order book. Useful for identifying institutional order flow.
> **Quote Permission Required: LV2 Advanced (HK only)**
> - 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.
> [Go to Quote Store](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## 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/) 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.
#### rank
# 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.
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## Basic Usage
```bash
longbridge rank
```
```
Ranking Categories (use second-level key with --key)
| key | name | sub-key | market |
|----------------|--------|-------------------|--------|
| hot_all | 总热度 | hot_all-us | US |
| hot_all | 总热度 | hot_all-hk | HK |
| hot_up | 热度上升 | hot_up-us | US |
| hot_up | 热度上升 | hot_up-hk | HK |
| trade_heat | 热门交易 | trade_heat-us | US |
| trade_heat | 热门交易 | trade_heat-hk | HK |
| discuss_heat | 热议 | discuss_heat-us | US |
| discuss_heat | 热议 | discuss_heat-hk | HK |
| discuss_heat | 热议 | discuss_heat-cn | CN |
| discuss_heat | 热议 | discuss_heat-sg | SG |
| watchlist_heat | 关注度 | watchlist_heat-us | US |
| watchlist_heat | 关注度 | watchlist_heat-hk | HK |
| watchlist_heat | 关注度 | watchlist_heat-cn | CN |
| watchlist_heat | 关注度 | 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 | 英伟达 | 215.330 | -0.0190 | 214.297 | -0.0048 |
| 2 | AAPL.US | 苹果 | 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": "英伟达",
"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": "总热度",
"second_tags": [
{ "key": "hot_all-us", "market": "US", "name": "美股" },
{ "key": "hot_all-hk", "market": "HK", "name": "港股" }
]
}
]
}
```
## 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
#### kline
# longbridge kline
Fetch candlestick (K-line) data for any symbol. Supports multiple periods and historical date ranges.
> **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)".
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## 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.
#### static
# longbridge static
Get static reference data for any symbol — name, exchange, currency, lot size, shares outstanding, EPS, BPS, and dividend yield.
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## 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.
#### ah-premium
# longbridge ah-premium
View the A/H premium ratio for dual-listed stocks — K-line history or intraday timeshare data.
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## 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.
#### trading
# longbridge trading
Look up trading session schedules and trading day calendars for any market.
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## 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.
#### security-list
# longbridge security-list
List securities available for a given market on Longbridge. Supports US, HK, CN, and SG markets.
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## 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.
#### participants
# 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.
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## 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.
#### top-movers
# 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.
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## Basic Usage
```bash
longbridge top-movers
```
```
| time | symbol | change% | reason | tags |
|----------------------|---------|---------|------------------|------------------|
| 2026-05-22T17:44:45Z | TSLA.US | +3.24% | 波动超 20 日均值 | 汽车制造商 |
| 2026-05-22T14:42:36Z | RKLB.US | +11.32% | 波动超 20 日均值 | 航空航天与国防 |
```
## 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": "波动超 20 日均值",
"alert_type": 11,
"timestamp": "1779471885",
"stock": {
"symbol": "TSLA.US",
"code": "TSLA",
"market": "US",
"name": "特斯拉",
"change": "0.0324",
"last_done": "426.010",
"labels": ["汽车制造商"]
}
}
],
"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
#### capital
# 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`.
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## 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.
#### subscriptions
# longbridge subscriptions
List your current active real-time quote subscriptions.
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## 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.
#### broker-holding
:::warning Not for Longbridge US Accounts
This command requires an AP data-center account (HK / SG). US data-center accounts are not supported. AP accounts can use this command 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.
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## 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.
#### market-status
# longbridge market-status
Check the current open/close status for each exchange.
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## 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.
#### depth
# longbridge depth
View the Level 2 order book for a symbol — the top 10 bid and ask prices with order counts and volumes.
> **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)".
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## 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/) for subscription options.
#### market-temp
# longbridge market-temp
Get the Longbridge market temperature index — a composite 0–100 sentiment gauge combining valuation and market sentiment. Higher = more bullish.
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## 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.
#### constituent
# longbridge constituent
View constituent stocks of an index or ETF — with sorting options and rise/fall statistics.
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## 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
```
#### quote
# longbridge quote
Get real-time quotes for one or more symbols — price, volume, change from previous close, and extended-hours data for US stocks.
> **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.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## 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.
#### calc-index
# longbridge calc-index
Compute financial indexes for any symbol — P/E, P/B, dividend yield, turnover rate, options greeks, and more.
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## 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.
#### trades
# longbridge trades
Fetch recent tick-by-tick trade records for a symbol, including price, volume, time, and trade direction.
> **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)".
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## 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.
#### Quant
#### Backtest
# 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");
}
'
```
#### Stock Screener
# 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": {}
}
]
```
#### Indicator
# 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`.
#### Watchlist
#### watchlist
# 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.
#### sharelist
# 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 | 新能源 | Regular | -0.40% | 6.64% | 500 |
Subscribed Sharelists:
| ID | Name | Type | Day Chg | YTD Chg | Subscribers |
|-------|------------------|---------|---------|---------|-------------|
| 11538 | 持股收息等待过激 | 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 | 无人机概念股 | Official | 20.51% | -3.82% | 768 |
| 29001357 | SpaceX概念 | 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.
#### Derivatives
#### warrant
# longbridge warrant
Browse HK warrants — list all warrants on an underlying, get real-time quotes for individual warrant contracts, or look up issuer information.
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## Basic Usage
```bash
longbridge warrant 700.HK
```
```
| Symbol | Name | Last | Leverage Ratio | Expiry | Type |
|----------|-----------------|------|----------------|------------|------|
| 24760.HK | UBTENCT@EP2606B | 0.66 | 7.65 | 2026-06-30 | Call |
| 25228.HK | GJTENCT@EP2606B | 0.65 | 7.77 | 2026-06-30 | Call |
| 24687.HK | JPTENCT@EP2606A | 0.65 | 7.77 | 2026-06-30 | Call |
| 24880.HK | CITENCT@EP2606B | 0.64 | 7.89 | 2026-06-30 | Call |
...
```
## Examples
### List all warrants on a stock
```bash
longbridge warrant 700.HK --format json
```
```json
[
{
"expiry": "2026-06-30",
"last": "0.65",
"leverage_ratio": "7.7846153846153845",
"name": "UBTENCT@EP2606B",
"symbol": "24760.HK",
"type": "Put"
},
{
"expiry": "2026-06-30",
"last": "0.65",
"leverage_ratio": "7.7846153846153845",
"name": "JPTENCT@EP2606A",
"symbol": "24687.HK",
"type": "Put"
},
{
"expiry": "2026-06-30",
"last": "0.64",
"leverage_ratio": "7.90625",
"name": "GJTENCT@EP2606B",
"symbol": "25228.HK",
"type": "Put"
}
]
```
Returns all listed warrants for the underlying, including type (Call/Put), last price, leverage ratio, and expiry date. Use the `symbol` field to get a detailed quote.
### Get a quote for one warrant
```bash
longbridge warrant quote 24760.HK --format json
```
```json
[
{
"expiry": "2026-06-30",
"implied_vol": "0.344",
"last": "0.650",
"prev_close": "0.640",
"symbol": "24760.HK",
"type": "Put"
}
]
```
Returns the real-time quote including implied volatility alongside the last and previous close prices.
### Look up warrant issuers
```bash
longbridge warrant issuers --format json
```
```json
[
{ "id": "1", "name_cn": "瑞信", "name_en": "CS" },
{ "id": "3", "name_cn": "摩通", "name_en": "JP" },
{ "id": "4", "name_cn": "麦银", "name_en": "MB" },
{ "id": "8", "name_cn": "法兴", "name_en": "SG" }
]
```
Lists all active warrant issuers in the HK market with their IDs and names.
## Requirements
Warrant market data permission is required. Warrant data covers the HK market only. See [Quote Subscriptions](/docs/quote/) for permission details.
#### option
# longbridge option
Look up real-time quotes for US option contracts, browse the full option chain, and view call/put volume statistics.
> **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.
> [Go to Quote Store](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## Basic Usage
```bash
longbridge option chain AAPL.US
```
```
| Expiry Date |
|-------------|
| 2026-04-17 |
| 2026-04-22 |
| 2026-04-24 |
| 2026-05-01 |
| 2026-05-15 |
| 2026-06-18 |
| 2026-07-17 |
| 2026-09-18 |
...
```
## Examples
### Browse the option chain for a stock
Without `--date`, returns all available expiry dates for the underlying. Pick an expiry date, then pass it with `--date` to see strike prices.
### View strikes for a specific expiry
```bash
longbridge option chain AAPL.US --date 2026-04-17 --format json
```
```json
[
{ "call_symbol": "AAPL260417C110000.US", "put_symbol": "AAPL260417P110000.US", "standard": "true", "strike": "110" },
{ "call_symbol": "AAPL260417C115000.US", "put_symbol": "AAPL260417P115000.US", "standard": "true", "strike": "115" },
{ "call_symbol": "AAPL260417C120000.US", "put_symbol": "AAPL260417P120000.US", "standard": "true", "strike": "120" }
]
```
Each row shows the call and put symbols for that strike. Copy a symbol from `call_symbol` or `put_symbol` to get a live quote.
### Get a real-time quote for an option contract
```bash
longbridge option quote AAPL260417C190000.US --format json
```
```json
[
{
"symbol": "AAPL260417C190000.US",
"last": "12.35",
"bid": "12.30",
"ask": "12.40",
"open_interest": "4821",
"implied_volatility": "0.2341",
"delta": "0.4812",
"gamma": "0.0231",
"theta": "-0.0512",
"vega": "0.1843"
}
]
```
Returns the latest bid, ask, last price, implied volatility, and greeks (delta, gamma, theta, vega) for the given contract.
### Option volume
Real-time call/put volume snapshot for today:
```bash
longbridge option volume AAPL.US
```
```
Option Volume Stats — AAPL.US
| call_vol | put_vol | pc_ratio |
|----------|---------|----------|
| 910,397 | 296,578 | 0.3258 |
```
Historical daily call/put volume and open interest:
```bash
longbridge option volume daily AAPL.US
longbridge option volume daily AAPL.US --count 60
```
```
Option Volume Daily — AAPL.US
| date | total_vol | call_vol | put_vol | pc_vol | call_oi | put_oi | pc_oi |
|------------|-----------|----------|---------|----------|-----------|-----------|----------|
| 2026-04-16 | 1,205,125 | 909,133 | 295,992 | 0.325576 | 2,719,025 | 1,913,086 | 0.703593 |
| 2026-04-15 | 1,611,875 | 1,250,894| 360,981 | 0.288578 | 2,684,251 | 1,914,190 | 0.713119 |
```
`pc_vol` is the put/call volume ratio; `pc_oi` is the put/call open interest ratio.
## Requirements
`option quote` requires an options account and options market data permission. `option chain` and `option volume` work with LV1 quote access. See [Quote Permissions](/docs/quote/) for subscription details.
## Notes
Option symbol format: `AAPL260417C190000.US` — underlying AAPL, expiry 2026-04-17, Call, $190.00 strike. The numeric price component is in units of $0.001, so 190000 = $190.00.
#### short-trades
# longbridge short-trades
Daily short sale volume — unlike `short-positions` (outstanding balance), this command shows the actual short selling transactions that occurred each day. Supports US stocks (FINRA/Nasdaq) and HK stocks (HKEX). Market is auto-detected from the symbol suffix.
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## Basic Usage
```bash
longbridge short-trades AAPL.US
```
```
Short Trades — AAPL.US
| date | nas_short | ny_short | total_vol | rate% | close |
|------------|-----------|----------|------------|--------|---------|
| 2026-05-22 | 3,809,598 | 0 | 10,564,290 | 36.06% | 308.820 |
| 2026-05-21 | 3,485,781 | 0 | 9,375,861 | 37.18% | 304.990 |
```
## Examples
### View US daily short sale volume
```bash
longbridge short-trades AAPL.US
longbridge short-trades AAPL.US --count 30
```
US field reference:
| Field | Description |
|-------|-------------|
| `date` | Trading date (`YYYY-MM-DD`) |
| `nas_short` | Short volume on Nasdaq/national trading systems |
| `ny_short` | Short volume on NYSE |
| `total_vol` | Total short volume for the day |
| `rate%` | Short volume as a percentage of total daily volume |
| `close` | Closing price for the day |
### US JSON output
```bash
longbridge short-trades AAPL.US --format json
```
```json
{
"symbol": "AAPL.US",
"data": [
{
"close": "308.820",
"nus_amount": "3809598",
"ny_amount": "0",
"rate": "0.3606",
"timestamp": "1779422400",
"total_amount": "10564290"
}
],
"sources": 1
}
```
JSON field reference (US):
| Field | Description |
|-------|-------------|
| `symbol` | Symbol in `CODE.MARKET` format |
| `data[].timestamp` | Trading date as Unix timestamp (seconds) |
| `data[].nus_amount` | Short volume on national trading systems (NUS/Nasdaq) |
| `data[].ny_amount` | Short volume on NYSE |
| `data[].total_amount` | Total short volume for the day |
| `data[].rate` | Short volume as a ratio (e.g. `"0.3606"` = 36.06%) |
| `data[].close` | Closing price for the day |
### View HK daily short sale volume
```bash
longbridge short-trades 700.HK
longbridge short-trades 700.HK --count 30
```
```
Short Trades — 700.HK
| date | rate% | short_shares | balance | total_vol | close |
|------------|--------|--------------|------------------|------------|-------|
| 2026-05-21 | 8.16% | 1,957,600 | 865,793,700.00 | 23,998,219 | 441.4 |
```
HK field reference:
| Field | Description |
|-------|-------------|
| `date` | Trading date (`YYYY-MM-DD`) |
| `short_shares` | Short shares sold for the day |
| `balance` | Outstanding short selling balance (HKD) |
| `total_vol` | Total market shares traded for the day |
| `rate%` | Short volume as a percentage of total daily volume |
| `close` | Closing price for the day |
### HK JSON output
```bash
longbridge short-trades 700.HK --format json
```
```json
{
"symbol": "700.HK",
"data": [
{
"amount": "1957600",
"balance": "865793700.00",
"close": "441.4",
"rate": "0.0816",
"timestamp": "1779379200",
"total_amount": "23998219"
}
]
}
```
JSON field reference (HK):
| Field | Description |
|-------|-------------|
| `symbol` | Symbol in `CODE.MARKET` format |
| `data[].timestamp` | Trading date as Unix timestamp (seconds) |
| `data[].amount` | Short shares sold for the day |
| `data[].balance` | Outstanding short selling balance (HKD) |
| `data[].total_amount` | Total market shares traded for the day |
| `data[].rate` | Short volume ratio (e.g. `"0.0816"` = 8.16%) |
| `data[].close` | Closing price for the day |
### Difference from short-positions
- `short-trades`: actual short sale transactions that happened each day (flow)
- `short-positions`: outstanding short position balance at a point in time (stock), updated bi-monthly for US stocks
## Options
| Flag | Description |
|------|-------------|
| `--count` | Number of records (1–100, default: 20) |
| `--format` | Output format: `table` (default) or `json` |
## Requirements
- US: US market data subscription required.
- HK: HK market data subscription required.
#### short-positions
# longbridge short-positions
Short selling position data — short ratio, short share count, and related metrics. Supports both HK and US stocks; the market is auto-detected from the symbol suffix.
- **HK**: HKEX daily data
- **US**: FINRA bi-monthly data
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
## Basic Usage
```bash
longbridge short-positions TSLA.US
```
```
Short Selling Data — TSLA.US
| date | rate% | short_shares | avg_daily_vol | days_cover | close |
|------------|-------|--------------|---------------|------------|---------|
| 2026-03-31 | 1.75% | 65,598,603 | 62,121,644 | 1.06 | 371.750 |
| 2026-03-13 | 1.62% | 60,860,404 | 60,676,562 | 1.00 | 391.200 |
| 2026-02-27 | 1.65% | 61,839,735 | 51,533,435 | 1.20 | 402.510 |
```
## Examples
### View US short interest history
```bash
longbridge short-positions TSLA.US
longbridge short-positions AAPL.US --count 50
```
Returns up to 100 records newest first. Each row shows the settlement date, short ratio (short shares ÷ float), number of short shares, average daily volume, days-to-cover ratio, and closing price.
### View HK short positions
```bash
longbridge short-positions 700.HK
longbridge short-positions 700.HK --count 30
```
```
Short Positions — 700.HK
| date | rate% | amount | balance | close |
|------------|-------|--------------|------------------|--------|
| 2026-05-19 | 1.45% | 2,748,900 | 1,256,859,880.00 | 455.20 |
```
HK fields: settlement date, short ratio, daily short sale amount, outstanding balance, and closing price.
### Machine-readable output
```bash
longbridge short-positions NVDA.US --format json
```
```json
[
{
"date": "2026-03-31",
"rate": "0.0175",
"short_shares": "65598603",
"avg_daily_vol": "62121644",
"days_cover": "1.06",
"close": "371.750"
}
]
```
## Options
| Flag | Description |
|------|-------------|
| `--count` | Number of records (1–100, default: 20) |
| `--format` | Output format: `table` (default) or `json` |
## Requirements
- US: US market data subscription required. Only works for US-listed stocks and ETFs.
- HK: HK market data subscription required.
#### Account
#### fund-positions
# longbridge fund-positions
List your current fund and ETF positions.
## Basic Usage
```bash
longbridge fund-positions
```
```
| Symbol | Name | Net Asset Value | Cost Net Asset Value | Currency | Holding Units |
|--------|------|-----------------|----------------------|----------|---------------|
```
## Examples
### View fund/ETF holdings
```bash
longbridge fund-positions
longbridge fund-positions --format json
```
Displays all fund and ETF positions in your account, including symbol, quantity, and cost information.
## Requirements
OAuth account permission required. See the [account permission setup](/docs/trade/) guide.
#### fund-holder
# longbridge fund-holder
Find which ETFs and funds hold a given stock, along with each fund's position ratio and report date.
## Basic Usage
```bash
longbridge fund-holder AAPL.US
```
```
| name | symbol | currency | weight | report_date |
|----------------------------------------|---------|----------|--------|-------------|
| T-Rex 2X Long Apple Daily Target ETF | AAPX.US | USD | 67.62% | 2026.04.03 |
| Global X PureCap MSCI Infor Tech ETF | GXPT.US | USD | 19.58% | 2026.04.06 |
| Roundhill Apple Weekly Income ETF | AAPW.US | USD | 16.76% | 2026.04.06 |
| Vanguard Information Technology ETF | VGT.US | USD | 15.84% | 2026.02.28 |
...
```
## Examples
### Find top ETF holders of a stock
```bash
longbridge fund-holder AAPL.US
longbridge fund-holder AAPL.US --format json
```
Lists the ETFs and funds with the largest exposure to the given stock, sorted by position ratio.
### Get more holders
```bash
longbridge fund-holder TSLA.US --count 50
```
Use `--count` to retrieve more results beyond the default limit.
## Requirements
OAuth account permission required. See the [account permission setup](/docs/trade/) guide.
#### cash-flow
# longbridge cash-flow
View your cash flow history — deposits, withdrawals, dividend payments, trade settlements, and other account movements.
## Basic Usage
```bash
longbridge cash-flow
```
```
| Flow Name | Symbol | Business Type | Balance | Currency | Time | Description |
|-----------|--------|---------------|---------|----------|------|-------------|
```
## Examples
### View last 30 days of cash flow
```bash
longbridge cash-flow
```
Lists all cash movements in the past 30 days, including the flow type, associated symbol, balance, currency, and timestamp.
### Filter by date range
```bash
longbridge cash-flow --start 2026-01-01 --end 2026-03-31
```
Fetches cash flow records within a specific date range. Useful for quarterly reconciliation or tax reporting.
## Requirements
OAuth account permission required. See the [account permission setup](/docs/trade/) guide.
#### deposits
# longbridge deposits
View your deposit history with optional filtering by state and currency.
## Basic Usage
```bash
longbridge deposits
```
```
Total: 3
| id | date | amount | currency | type | state |
|---------|----------------------|----------|----------|------|----------|
| 2096375 | 2026-04-30T07:57:49Z | 3000.00 | USD | Wire | Credited |
| 2036889 | 2026-03-27T02:54:49Z | 10000.00 | USD | Wire | Credited |
| 1980183 | 2026-03-02T02:32:11Z | 3132.60 | USD | Wire | Credited |
```
## Examples
### View all deposits
```bash
longbridge deposits
```
### Filter by state
```bash
# 0=pending, 1=credited, 2=failed
longbridge deposits --states 1
```
### Filter by currency
```bash
longbridge deposits --currencies HKD,USD
```
### Paginate
```bash
longbridge deposits --page 2 --count 50
```
## Requirements
OAuth account permission required. See the [account permission setup](/docs/trade/) guide.
#### positions
# longbridge positions
List your current stock positions — symbol, quantity, available quantity, cost price, and market.
## Basic Usage
```bash
longbridge positions
```
```
| Symbol | Name | Quantity | Available | Cost Price | Currency | Market |
|---------|-----------|----------|-----------|------------|----------|--------|
| NVDA.US | NVIDIA | 101 | 101 | 50.229 | USD | US |
| MSFT.US | Microsoft | 15 | 15 | 373.310 | USD | US |
| AAPL.US | Apple | 133 | 133 | 211.589 | USD | US |
| 9988.HK | BABA-W | 500 | 500 | 95.640 | HKD | HK |
```
## Examples
### View all positions
```bash
longbridge positions
longbridge positions --format json
```
Displays every open stock position with its name, symbol, quantity, available quantity for trading, cost price, and market.
## Requirements
OAuth account permission required. See the [account permission setup](/docs/trade/) guide.
#### portfolio
# longbridge portfolio
Get a full portfolio overview — total P/L, total assets, market value by market (US/HK/CN/SG), and cash balances.
## Basic Usage
```bash
longbridge portfolio
```
```
| Field | Value |
|-------------------|-----------|
| Currency | USD |
| Total Asset | 125422.43 |
| Market Cap | 66783.59 |
| Total Cash | 58638.84 |
| P/L | 140473.44 |
| Intraday P/L | 14637.05 |
| Margin Call | 0 |
| Risk Level | Safe |
| Credit Limit | 410651.27 |
| Market | Value (USD) | % |
|--------|-------------|---------|
| US | 58659.65 | 46.76% |
| HK | 493265.25 | 393.28% |
| Cash | 58638.84 | 46.75% |
```
## Examples
### View portfolio summary
```bash
longbridge portfolio
longbridge portfolio --format json
```
Displays total asset value, total and today's P/L, and a breakdown of market value per market.
### Short margin deposit
```bash
longbridge portfolio short-margin
```
Shows the short-selling margin deposit details for your account, including per-position margin requirements and deposit amounts.
## Requirements
OAuth account permission required. See the [account permission setup](/docs/trade/) guide.
#### withdrawals
# longbridge withdrawals
View your withdrawal history.
## Basic Usage
```bash
longbridge withdrawals
```
```
Total: 5
| id | date | amount | currency | type | state |
|---------|----------------------|----------|----------|------|----------|
| 2096375 | 2026-04-30T07:57:49Z | 3000.00 | USD | Wire | Credited |
| 2036889 | 2026-03-27T02:54:49Z | 10000.00 | USD | Wire | Credited |
```
## Examples
### View withdrawal history
```bash
longbridge withdrawals
```
### Paginate through records
```bash
longbridge withdrawals --page 2 --count 50
```
## Requirements
OAuth account permission required. See the [account permission setup](/docs/trade/) guide.
#### dca
:::warning Not for Longbridge US Accounts
This command requires an AP data-center account (HK / SG). US data-center accounts are not supported. AP accounts can use this command with any supported symbol, including US stocks.
:::
# longbridge dca
Recurring investment — automatically invest a fixed amount at regular intervals. Create and manage plans that execute stock purchases on a daily, weekly, fortnightly, or monthly schedule. Track trade history, monitor cumulative profit, and check upcoming trade dates.
Without a subcommand, lists all recurring investment plans.
## Basic Usage
```bash
longbridge dca
```
```
| Plan ID | Symbol | Status | Amount | Frequency | Day of Week | Next Trade Date | Cum Amount | Cum Profit | Avg Cost |
|---------------------|---------|----------|--------|-------------|-------------|----------------------|------------|------------|----------|
| 1225781523156889600 | SPY.US | Finished | 750 | Fortnightly | Wed | 2026-04-08T14:00:00Z | 0 | 0 | 0 |
| 1225781323482853376 | QQQ.US | Finished | 750 | Fortnightly | Tue | 2026-04-07T14:00:00Z | 0 | 0 | 0 |
```
## Examples
### List plans
```bash
longbridge dca
longbridge dca --status Active
longbridge dca --symbol AAPL.US
```
Filter plans by status (`Active`, `Suspended`, `Finished`) or by symbol.
### Create a plan
```bash
# Monthly on the 15th
longbridge dca create AAPL.US --amount 500 --frequency monthly --day-of-month 15
# Weekly every Monday
longbridge dca create TSLA.US --amount 200 --frequency weekly --day-of-week mon
# Fortnightly every Wednesday
longbridge dca create 700.HK --amount 1000 --frequency fortnightly --day-of-week wed
```
Before creating a plan, the CLI shows Terms and Conditions with links. Confirm interactively, or pass `--agree-terms` to skip the prompt:
```bash
longbridge dca create AAPL.US --amount 500 --frequency monthly --day-of-month 15 --agree-terms
```
### Manage plans
```bash
longbridge dca pause 1225781523156889600
longbridge dca resume 1225781523156889600
longbridge dca stop 1225781523156889600
```
`stop` permanently terminates a plan and cannot be undone.
### Trade history
```bash
longbridge dca history 1225781523156889600
```
Shows the execution history for a specific plan — trade dates, amounts, prices, and quantities.
### Statistics summary
```bash
longbridge dca stats
```
```
| Field | Value |
|-----------------|-------|
| active_count | 2 |
| finished_count | 3 |
| suspended_count | 0 |
| total_amount | 1500 |
| total_profit | 243 |
```
### Check if a symbol supports recurring investment
```bash
longbridge dca check AAPL.US TSLA.US 700.HK
```
```
| Symbol | Supports Recurring Investment |
|---------|-------------------------------|
| AAPL.US | yes |
| TSLA.US | yes |
| 700.HK | yes |
```
### Calculate next trade date
```bash
longbridge dca calc-date --frequency weekly --day-of-week wed
longbridge dca calc-date --frequency monthly --day-of-month 15
```
Returns the next scheduled trade date for the given plan parameters, without creating a plan.
### Set pre-trade reminder
```bash
longbridge dca set-reminder --hours 1
```
Sets how many hours before each trade execution you receive a reminder notification.
## Requirements
A Longbridge account with recurring investment enabled is required. HK and SG accounts must agree to the respective Terms and Conditions before creating a plan. See [Trade Permissions](/docs/trade/) for account setup.
#### statement
# longbridge statement
Download and export account statements — daily settlement summaries or monthly reports.
## Basic Usage
```bash
longbridge statement
```
```
| date | file_key |
|------------|--------------------------------------|
| 2026-04-10 | stmt_daily_20260410_abc123 |
| 2026-04-09 | stmt_daily_20260409_def456 |
| 2026-04-08 | stmt_daily_20260408_ghi789 |
...
```
## Examples
### List recent daily statements
```bash
longbridge statement
# Specify a start date and limit
longbridge statement --start-date 20260401 --limit 10
```
Lists available daily statements with their dates and file keys. File keys are used with the `export` subcommand.
### List monthly statements
```bash
longbridge statement --type monthly
# Limit to last 6 months
longbridge statement --type monthly --limit 6
```
Returns monthly summary statements instead of daily ones.
### List statements (subcommand form)
```bash
longbridge statement list
longbridge statement list --type daily --start-date 20260401
```
Equivalent to `longbridge statement` — the `list` subcommand makes the intent explicit.
### Export a statement to terminal
```bash
longbridge statement export --file-key stmt_daily_20260410_abc123
```
Prints all non-empty sections of the statement as Markdown to stdout. Use a `file_key` from `longbridge statement list`.
### Export specific sections
```bash
# Export only equity holdings and stock trades
longbridge statement export --file-key stmt_daily_20260410_abc123 --section equity_holdings --section stock_trades
```
Available sections include: `asset`, `account_balances`, `equity_holdings`, `account_balance_changes`, `stock_trades`, `equity_holding_changes`, `option_trades`, `fund_trades`, and more.
### Export as CSV files
```bash
# Export all sections to a directory as CSV
longbridge statement export --file-key stmt_daily_20260410_abc123 -o ./statements/
# Export specific sections as CSV
longbridge statement export --file-key stmt_daily_20260410_abc123 --section equity_holdings --export-format csv -o ./statements/
```
When `-o` is provided, the default export format switches to CSV. Each section is saved as a separate file in the output directory.
## Requirements
A valid OAuth login is required. Run `longbridge auth login` if you have not yet authenticated.
#### alert
# longbridge alert
Manage price alerts — list, add, and delete alerts for any symbol.
## Basic Usage
```bash
longbridge alert
```
```
| id | symbol | price | alert | enabled | frequency |
|--------|---------|---------|------------------|---------|-----------|
| 112326 | TSLA.US | 348.950 | Price drop 239 | ✓ | every |
| 101526 | TSLA.US | 348.950 | Price drop 190 | | every |
| 179741 | NVDA.US | 188.630 | Price drop 130 | | once |
...
```
## Examples
### List all alerts
```bash
longbridge alert
longbridge alert --format json
```
Shows all active price alerts across all symbols.
### Filter by symbol
```bash
longbridge alert TSLA.US
longbridge alert QQQ.US
```
### Add a price alert
```bash
# Alert when TSLA rises to $300
longbridge alert add TSLA.US --price 300 --direction rise
# Alert when AAPL drops to $150
longbridge alert add AAPL.US --price 150 --direction fall
```
### Enable / Disable an alert
```bash
# Disable an alert (keeps it without deleting)
longbridge alert disable 112326
# Re-enable a disabled alert
longbridge alert enable 112326
```
### Delete an alert
```bash
# Delete alert by ID (from the alert list)
longbridge alert delete 486469
```
## Requirements
OAuth account permission required. See the [account permission setup](/docs/trade/) guide.
#### assets
# longbridge assets
View your full account overview — net assets, buying power, margin status, risk level, and cash balances across all currencies.
## Basic Usage
```bash
longbridge assets
```
```
| Currency | Net Assets | Total Cash | Buy Power | Max Finance | Remaining Finance | Init Margin | Maintenance Margin | Risk Level |
|----------|------------|------------|------------|-------------|-------------------|-------------|--------------------|------------|
| USD | 125422.43 | 58638.84 | 106743.46 | 410651.27 | 371985.59 | 18678.97 | 16305.97 | Safe |
| Currency | Available Cash | Frozen Cash | Settling Cash | Withdrawable |
|----------|----------------|-------------|---------------|--------------|
| USD | -38665.68 | 332.19 | -10108.02 | -38665.68 |
| HKD | 755592.21 | 64.69 | -27760.00 | 755592.21 |
```
## Examples
### Check account overview
```bash
longbridge assets
longbridge assets --format json
```
Displays net assets, total cash, buying power, margin usage, and risk level in a readable table.
## Requirements
OAuth account permission required. See the [account permission setup](/docs/trade/) guide.
#### profit-analysis
# longbridge profit-analysis
Analyze profit and loss — overall P&L summary, per-stock breakdown, individual stock detail with transaction flows, and market-filtered views.
## Basic Usage
```bash
longbridge profit-analysis
```
```
P&L Summary (USD) 2023-12-04 ~ 2026-04-17
Total Asset 125413.01
Initial Asset 0.00
Ending Asset 125413.01
Invest Amount 76997.11
Total P&L 48415.89
Stocks Traded 12
Simple Yield 62.88%
TWR 58.41%
Stock P&L 47203.15
Fund P&L 1212.74
MMF P&L 0.00
P&L Breakdown
| Symbol | Name | Market | P&L |
|---------|---------|--------|---------|
| 9988.HK | Alibaba | HK | 18406.9 |
| AAPL.US | Apple | US | 6498.14 |
```
## Examples
### P&L summary with date range
```bash
longbridge profit-analysis
longbridge profit-analysis --start 2026-01-01 --end 2026-04-17
longbridge profit-analysis --format json
```
Without `--start`/`--end`, shows the full account history. With a date range, filters the P&L summary and breakdown to that period. Simple Yield and TWR are shown as percentages.
### Individual stock P&L detail
```bash
longbridge profit-analysis detail TSLA.US
longbridge profit-analysis detail 700.HK --currency HKD
```
Shows detailed P&L for a specific stock — underlying and derivative positions with buy/sell/fee breakdowns, plus transaction flow history.
### Filter derivative flows
```bash
longbridge profit-analysis detail TSLA.US --derivative
```
### Paginate transaction flows
```bash
longbridge profit-analysis detail TSLA.US --page 2 --size 20
```
### P&L by market
```bash
longbridge profit-analysis by-market HK
longbridge profit-analysis by-market US --size 50
```
Shows stock P&L filtered by market with pagination support.
## Requirements
OAuth account permission required. See the [account permission setup](/docs/trade/) guide.
## Subcommands
### `realized` — Realized P&L (US accounts)
```bash
longbridge profit-analysis realized
longbridge profit-analysis realized --category stock
longbridge profit-analysis realized --category option --currency USD
```
Returns realized profit and loss breakdown by asset category for US accounts.
:::warning Longbridge US Accounts
`profit-analysis realized` is only available for US data-center accounts.
:::
| Option | Description | Default |
| ------ | ----------- | ------- |
| `--category` | Asset category: `all` \| `stock` \| `option` \| `crypto` | all |
| `--currency` | Settlement currency | USD |
#### bank-cards
# longbridge bank-cards
List the bank cards linked to your Longbridge account.
## Basic Usage
```bash
longbridge bank-cards
```
```
| bank | account | currency | swift | region | status |
|------------------------------|------------------|----------|----------|----------------|--------|
| DBS Bank | 2712065366 | SGD | DBSSSGSG | Singapore | active |
| China Merchants Bank | 6212998605139779 | ALL | CMBCHKHH | Hong Kong | active |
```
## Examples
### List linked bank cards
```bash
longbridge bank-cards
longbridge bank-cards --format json
```
Shows all linked bank cards with bank name, masked account number, currency, SWIFT code, and status.
## Requirements
OAuth account permission required. See the [account permission setup](/docs/trade/) guide.
#### Content
#### topic
# longbridge topic
Fetch community discussion topics related to a symbol from the Longbridge platform. Browse the full community on [Topics](https://longbridge.com/topics).
## Basic Usage
```bash
longbridge topic TSLA.US
```
```
| id | title | published_at | likes | comments | shares |
|----------|-------------------------------------------------|----------------------|-------|----------|--------|
| 39798312 | AI's Hard Limit: Compute Boom Meets a Power Cr… | 2026-04-09T11:32:03Z | 41 | 7 | 97 |
| 39816927 | Tesla is weirdly terrible. Other stocks are up… | 2026-04-09T19:54:50Z | 6 | 4 | 0 |
| 39822930 | What does everyone think about current Tesla? | 2026-04-10T04:43:49Z | 0 | 0 | 0 |
...
```
## Examples
### View community discussions
```bash
longbridge topic TSLA.US
# View discussions for another symbol
longbridge topic NVDA.US
```
Lists community posts and discussions related to the symbol, including titles, descriptions, and engagement metrics.
### Search topics by keyword
```bash
longbridge topic search TSLA
longbridge topic search "AI stocks" --count 10
```
Searches community topics by keyword. Returns posts matching the keyword with title, author excerpt, and engagement stats. Use `--count` to control the number of results (default: 20).
### Read the full content of a post
```bash
longbridge topic detail 39798312
```
```
ID: 39798312
Type: article
Title: AI's Hard Limit: Compute Boom Meets a Power Crunch; Gas Turbines the Hidden Boss?
Tickers: ST/US/TSLA, ST/US/NVDA, ST/US/GOOG
Stats: 42 likes 7 comments 0 views
Created: 2026-04-09T11:32:03Z
URL: https://longbridge.cn/topics/39798312
In the prior piece on AI infrastructure, Dolphin Research argued that
the U.S. power shortfall is not a cyclical mismatch but a structural conflict
between surging AI compute and long-lagging energy and grid build-out...
```
Use the `id` from the topic list to fetch the full body text of any post.
### Find high-engagement posts
```bash
# Filter posts with significant likes using jq
longbridge topic TSLA.US --format json | jq '[.[] | select(.likes_count > 10)]'
```
Combines with `jq` to surface the most-discussed posts. Useful for gauging retail sentiment spikes around earnings or news events.
### View your own topics
```bash
longbridge topic mine
# Filter by content type
longbridge topic mine --type article
longbridge topic mine --type post
```
Lists topics you have published. Use `--page` and `--size` to paginate through results.
### View replies to a topic
```bash
longbridge topic replies 39798312
# Paginate through replies
longbridge topic replies 39798312 --page 2 --size 10
```
Lists replies under a specific topic. Use the `id` from the topic list.
### Publish a new post
```bash
# Short-form post (plain text)
longbridge topic create --body "TSLA earnings beat expectations, bullish on Q3 guidance"
# Post with associated tickers
longbridge topic create --body "Watching NVDA and ARM for AI infrastructure plays" --tickers NVDA.US,ARM.US
```
Creates a short-form community post. Text is plain text. Use `--tickers` to tag related symbols (max 10, comma-separated).
### Publish an article
```bash
longbridge topic create --type article --title "Tesla Q1 2026 Earnings Analysis" --body "## Key Takeaways\n\nRevenue grew 15% YoY..."
```
Creates a long-form article with a title. The body supports Markdown formatting. `--title` is required for articles.
### Reply to a topic
```bash
# Top-level reply
longbridge topic create-reply 39798312 --body "Great analysis, thanks for sharing"
# Nested reply (reply to a specific reply)
longbridge topic create-reply 39798312 --body "Agreed" --reply-to 50012345
```
Posts a reply to a community topic. Use `--reply-to` with a reply ID (from `topic replies`) to create a nested reply.
## Requirements
A valid OAuth login is required for `mine`, `create`, and `create-reply`. Run `longbridge auth login` if you have not yet authenticated.
#### filing
# longbridge filing
Browse regulatory filings and disclosure documents for a symbol. For US-listed stocks, this includes [SEC EDGAR](https://www.sec.gov/cgi-bin/browse-edgar) filings such as [Form 4](https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&type=4&dateb=&owner=include&count=40) insider transactions, [8-K](https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&type=8-K&dateb=&owner=include&count=40) current reports, and [10-K](https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany&type=10-K&dateb=&owner=include&count=40) annual reports. HK-listed stocks return exchange disclosure filings from the [Hong Kong Stock Exchange](https://www.hkexnews.hk/).
## Basic Usage
```bash
longbridge filing TSLA.US
```
```
| id | title | file_name | files | publish_at |
|--------------------|---------------------------------------|----------------------------|-------|----------------------|
| 633214836329945345 | Tesla | 4 - Tesla, Inc. (Issuer) | 4 - Tesla, Inc. (Issuer) | 1 | 2026-04-03T00:08:52Z |
| 633048285147044097 | Tesla | 8-K - Tesla, Inc. (Filer) | 8-K - Tesla, Inc. (Filer) | 2 | 2026-04-02T13:07:13Z |
| 632835137097963777 | Tesla | 4 - Tesla, Inc. (Issuer) | 4 - Tesla, Inc. (Issuer) | 1 | 2026-04-01T23:00:13Z |
...
```
## Examples
### View recent filings
```bash
longbridge filing TSLA.US
# Output as JSON for scripting
longbridge filing TSLA.US --format json
```
Lists the most recent filings for the symbol with titles, form types, and publication dates. The `file_urls` field in JSON output contains direct download links to the filing documents.
### Read a full filing
```bash
# Use the symbol and id from the filing list to read the full document
longbridge filing detail TSLA.US 633214836329945345
```
Returns the full text content of the filing. Useful for extracting specific disclosures or feeding to an AI model for analysis.
#### news
# longbridge news
Get latest news articles for a symbol, or fetch the full content of an article by ID. Browse the full feed on [News](https://longbridge.com/news).
## Basic Usage
```bash
longbridge news TSLA.US
```
```
| id | title | published_at | likes | comments |
|-----------|---------------------------------------------------------|----------------------|-------|----------|
| 282284711 | Wall Street Backs Tesla? Cathie Wood Spends Nearly $28… | 2026-04-10T03:48:22Z | 0 | 0 |
| 282276051 | In response to market rumors that "Tesla is developing… | 2026-04-10T02:16:27Z | 0 | 0 |
| 282265091 | SpaceX posted nearly $5 billion loss in 2025 | 2026-04-10T00:31:27Z | 0 | 0 |
| 282247843 | Down More Than 30% from All-Time Highs, Should You Buy… | 2026-04-09T20:46:26Z | 0 | 0 |
...
```
## Examples
### Latest news for a stock
```bash
longbridge news TSLA.US
# Get more articles
longbridge news NVDA.US --count 5
# Output as JSON for scripting
longbridge news TSLA.US --format json
```
Lists the most recent news articles for the symbol with titles, publication times, and URLs.
### Get full article content
```bash
longbridge news detail 282276051
```
Fetches the full Markdown content of a single article by its ID. Article IDs are available in the `id` field of the list output.
### Search news by keyword
```bash
longbridge news search "AI stocks"
longbridge news search TSLA --count 10
```
```
| id | title | time |
|-----------|--------------------------------------------------------|----------------------|
| 285710139 | Why stocks hit new highs amid ceasefire bets | 2026-05-08T10:53:18Z |
| 285708897 | Why Akamai stock jumped 26% | 2026-05-08T09:54:55Z |
...
```
Searches news articles by keyword across all markets. Use `--count` to control the number of results (default: 20).
#### Research
#### investors
# 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
# 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 filter_marketcap:100:1000 --filter 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
# 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` |
#### insider-trades
# 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).
### Market
### Historical Temperature
This interface is used to get historical market temperature.
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
# 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
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.quote._quote_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.quote._quote_context) |
| Rust | [longbridge:: ::quote#_quote_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.quote.html#method._quote_context) |
| Go | [quote.history_market_temperature](https://pkg.go.dev/github.com/longbridge/openapi-go/ #quote.history_market_temperature) |
| Node.js | [quote#QuoteContext](https://longbridge.github.io/openapi/nodejs/classes/quote.html#quotecontext) |
| Java | [quote.getQuoteContext](https://longbridge.github.io/openapi/java/com/longbridge/ /quote.html#getQuoteContext) |
| C++ | [longbridge:: ::quote::_quote_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_quote.html) |
## 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 Temperature
Get Current Market Temperature
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
# 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
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.quote._quote_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.quote._quote_context) |
| Rust | [longbridge:: ::quote#_quote_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.quote.html#method._quote_context) |
| Go | [quote.market_temperature](https://pkg.go.dev/github.com/longbridge/openapi-go/ #quote.market_temperature) |
| Node.js | [quote#QuoteContext](https://longbridge.github.io/openapi/nodejs/classes/quote.html#quotecontext) |
| Java | [quote.getQuoteContext](https://longbridge.github.io/openapi/java/com/longbridge/ /quote.html#getQuoteContext) |
| C++ | [longbridge:: ::quote::_quote_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_quote.html) |
## 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 |
### Popularity Leaderboard
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
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.market._market_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.market._market_context) |
| Rust | [longbridge:: ::market#_market_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.market.html#method._market_context) |
| Go | [market.rank_list](https://pkg.go.dev/github.com/longbridge/openapi-go/ #market.rank_list) |
| Node.js | [market#MarketContext](https://longbridge.github.io/openapi/nodejs/classes/market.html#marketcontext) |
| Java | [market.getMarketContext](https://longbridge.github.io/openapi/java/com/longbridge/ /market.html#getMarketContext) |
| C++ | [longbridge:: ::market::_market_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_market.html) |
## 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)) {
var resp = ctx.getRankList("hot_all-us", false).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.
### Unusual Items
Detect unusual market movements — price spikes, volume surges, and other abnormal trading activity.
longbridge anomaly --market US
longbridge anomaly --market HK
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.market._market_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.market._market_context) |
| Rust | [longbridge:: ::market#_market_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.market.html#method._market_context) |
| Go | [market.unusual_items](https://pkg.go.dev/github.com/longbridge/openapi-go/ #market.unusual_items) |
| Node.js | [market#MarketContext](https://longbridge.github.io/openapi/nodejs/classes/market.html#marketcontext) |
| Java | [market.getMarketContext](https://longbridge.github.io/openapi/java/com/longbridge/ /market.html#getMarketContext) |
| C++ | [longbridge:: ::market::_market_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_market.html) |
## 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": "大宗交易",
"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 |
### Trading Days
This API is used to obtain the trading days of the market.
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
# 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
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.quote._quote_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.quote._quote_context) |
| Rust | [longbridge:: ::quote#_quote_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.quote.html#method._quote_context) |
| Go | [quote.trading_days](https://pkg.go.dev/github.com/longbridge/openapi-go/ #quote.trading_days) |
| Node.js | [quote#QuoteContext](https://longbridge.github.io/openapi/nodejs/classes/quote.html#quotecontext) |
| Java | [quote.getQuoteContext](https://longbridge.github.io/openapi/java/com/longbridge/ /quote.html#getQuoteContext) |
| C++ | [longbridge:: ::quote::_quote_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_quote.html) |
:::info
[Business Command](../../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
This API is used to obtain the daily trading hours of each market.
> **Quote Permission Required: Free**
> Included with OpenAPI activation — no extra purchase needed.
> [My Quotes](https://open.longbridge.com/account)
> OpenAPI quote perms are separate from App/Web perms
# trading session schedule for all markets (US, HK, CN, SG)
longbridge trading session
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.quote._quote_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.quote._quote_context) |
| Rust | [longbridge:: ::quote#_quote_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.quote.html#method._quote_context) |
| Go | [quote.trading_session](https://pkg.go.dev/github.com/longbridge/openapi-go/ #quote.trading_session) |
| Node.js | [quote#QuoteContext](https://longbridge.github.io/openapi/nodejs/classes/quote.html#quotecontext) |
| Java | [quote.getQuoteContext](https://longbridge.github.io/openapi/java/com/longbridge/ /quote.html#getQuoteContext) |
| C++ | [longbridge:: ::quote::_quote_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_quote.html) |
:::info
[Business Command](../../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](../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 |
### Rank Categories
Get the tag category configuration for the popularity leaderboard. `second_tags[].key` can be passed to `rank_list`.
longbridge rank
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.market._market_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.market._market_context) |
| Rust | [longbridge:: ::market#_market_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.market.html#method._market_context) |
| Go | [market.rank_categories](https://pkg.go.dev/github.com/longbridge/openapi-go/ #market.rank_categories) |
| Node.js | [market#MarketContext](https://longbridge.github.io/openapi/nodejs/classes/market.html#marketcontext) |
| Java | [market.getMarketContext](https://longbridge.github.io/openapi/java/com/longbridge/ /market.html#getMarketContext) |
| C++ | [longbridge:: ::market::_market_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_market.html) |
## 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` |
### Top Movers
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
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.market._market_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.market._market_context) |
| Rust | [longbridge:: ::market#_market_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.market.html#method._market_context) |
| Go | [market.top_movers](https://pkg.go.dev/github.com/longbridge/openapi-go/ #market.top_movers) |
| Node.js | [market#MarketContext](https://longbridge.github.io/openapi/nodejs/classes/market.html#marketcontext) |
| Java | [market.getMarketContext](https://longbridge.github.io/openapi/java/com/longbridge/ /market.html#getMarketContext) |
| C++ | [longbridge:: ::market::_market_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_market.html) |
## 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",
"counter_id": "ST/US/TSLA",
"name": "特斯拉",
"change": "-0.0388",
"last_done": "404.110",
"market": "US",
"labels": ["汽车制造商"],
"logo": "https://assets.lbkrs.com/ticker/ST/US/TSLA.png",
"trade_status": 0
},
"timestamp": "1779202097",
"alert_reason": "波动超 20 日均值",
"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`) |
| ∟ ∟ counter_id | string | false | Counter ID (e.g. `ST/US/TSLA`) |
| ∟ ∟ 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 |
### Market Status
Get the current open/close status for each exchange.
longbridge market-status
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.market._market_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.market._market_context) |
| Rust | [longbridge:: ::market#_market_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.market.html#method._market_context) |
| Go | [market.market_status](https://pkg.go.dev/github.com/longbridge/openapi-go/ #market.market_status) |
| Node.js | [market#MarketContext](https://longbridge.github.io/openapi/nodejs/classes/market.html#marketcontext) |
| Java | [market.getMarketContext](https://longbridge.github.io/openapi/java/com/longbridge/ /market.html#getMarketContext) |
| C++ | [longbridge:: ::market::_market_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_market.html) |
## 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 |
#### Calendar
#### IPO Calendar
Get upcoming and recent IPO listings with expected offer price and listing date.
longbridge finance-calendar ipo
longbridge finance-calendar ipo --market US
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.calendar._calendar_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.calendar._calendar_context) |
| Rust | [longbridge:: ::calendar#_calendar_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.calendar.html#method._calendar_context) |
| Go | [calendar.finance_calendar](https://pkg.go.dev/github.com/longbridge/openapi-go/ #calendar.finance_calendar) |
| Node.js | [calendar#CalendarContext](https://longbridge.github.io/openapi/nodejs/classes/calendar.html#calendarcontext) |
| Java | [calendar.getCalendarContext](https://longbridge.github.io/openapi/java/com/longbridge/ /calendar.html#getCalendarContext) |
| C++ | [longbridge:: ::calendar::_calendar_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_calendar.html) |
## 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. |
## Request Example
```python
from longbridge.openapi import CalendarContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = CalendarContext(config)
resp = ctx.ipo_calendar("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncCalendarContext, 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.ipo_calendar("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, CalendarContext, 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.ipo_calendar('AAPL.US')
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.getIpoCalendar("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, calendar::CalendarContext, 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.ipo_calendar("AAPL.US").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.ipo_calendar("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/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.IpoCalendar(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": "2026-04-30",
"list": [
{
"date": "2026-05-05",
"count": 1,
"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": []
}
]
}
]
}
}
```
### 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
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
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.calendar._calendar_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.calendar._calendar_context) |
| Rust | [longbridge:: ::calendar#_calendar_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.calendar.html#method._calendar_context) |
| Go | [calendar.finance_calendar](https://pkg.go.dev/github.com/longbridge/openapi-go/ #calendar.finance_calendar) |
| Node.js | [calendar#CalendarContext](https://longbridge.github.io/openapi/nodejs/classes/calendar.html#calendarcontext) |
| Java | [calendar.getCalendarContext](https://longbridge.github.io/openapi/java/com/longbridge/ /calendar.html#getCalendarContext) |
| C++ | [longbridge:: ::calendar::_calendar_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_calendar.html) |
## 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. |
## Request Example
```python
from longbridge.openapi import CalendarContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = CalendarContext(config)
resp = ctx.macro_calendar("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncCalendarContext, 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.macro_calendar("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, CalendarContext, 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.macro_calendar('AAPL.US')
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.getMacroCalendar("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, calendar::CalendarContext, 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.macro_calendar("AAPL.US").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.macro_calendar("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/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.MacroCalendar(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": "2026-04-30",
"list": [
{
"date": "2026-05-02",
"count": 0,
"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": []
}
]
}
]
}
}
```
### 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
Browse upcoming earnings reports and recent results, with EPS and revenue estimates.
longbridge finance-calendar report
longbridge finance-calendar report --market US
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.calendar._calendar_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.calendar._calendar_context) |
| Rust | [longbridge:: ::calendar#_calendar_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.calendar.html#method._calendar_context) |
| Go | [calendar.finance_calendar](https://pkg.go.dev/github.com/longbridge/openapi-go/ #calendar.finance_calendar) |
| Node.js | [calendar#CalendarContext](https://longbridge.github.io/openapi/nodejs/classes/calendar.html#calendarcontext) |
| Java | [calendar.getCalendarContext](https://longbridge.github.io/openapi/java/com/longbridge/ /calendar.html#getCalendarContext) |
| C++ | [longbridge:: ::calendar::_calendar_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_calendar.html) |
## 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. |
## Request Example
```python
from longbridge.openapi import CalendarContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = CalendarContext(config)
resp = ctx.earnings_calendar("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncCalendarContext, 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.earnings_calendar("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, CalendarContext, 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.earnings_calendar('AAPL.US')
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.getEarningsCalendar("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, calendar::CalendarContext, 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.earnings_calendar("AAPL.US").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.earnings_calendar("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/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.EarningsCalendar(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": "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": []
}
]
}
]
}
}
```
### 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 |
#### Dividend Calendar
Get upcoming and past dividend events including ex-date, pay date, and dividend amount.
longbridge finance-calendar dividend
longbridge finance-calendar dividend --filter positions
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.calendar._calendar_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.calendar._calendar_context) |
| Rust | [longbridge:: ::calendar#_calendar_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.calendar.html#method._calendar_context) |
| Go | [calendar.finance_calendar](https://pkg.go.dev/github.com/longbridge/openapi-go/ #calendar.finance_calendar) |
| Node.js | [calendar#CalendarContext](https://longbridge.github.io/openapi/nodejs/classes/calendar.html#calendarcontext) |
| Java | [calendar.getCalendarContext](https://longbridge.github.io/openapi/java/com/longbridge/ /calendar.html#getCalendarContext) |
| C++ | [longbridge:: ::calendar::_calendar_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_calendar.html) |
## 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. |
## Request Example
```python
from longbridge.openapi import CalendarContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = CalendarContext(config)
resp = ctx.dividend_calendar("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncCalendarContext, 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.dividend_calendar("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, CalendarContext, 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.dividend_calendar('AAPL.US')
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.getDividendCalendar("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, calendar::CalendarContext, 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.dividend_calendar("AAPL.US").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.dividend_calendar("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/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.DividendCalendar(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": "2026-04-30",
"list": [
{
"date": "2026-04-30",
"count": 275,
"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": []
}
]
}
]
}
}
```
### 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 |
#### Merge Calendar
Browse upcoming M&A and merger events.
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.calendar._calendar_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.calendar._calendar_context) |
| Rust | [longbridge:: ::calendar#_calendar_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.calendar.html#method._calendar_context) |
| Go | [calendar.finance_calendar](https://pkg.go.dev/github.com/longbridge/openapi-go/ #calendar.finance_calendar) |
| Node.js | [calendar#CalendarContext](https://longbridge.github.io/openapi/nodejs/classes/calendar.html#calendarcontext) |
| Java | [calendar.getCalendarContext](https://longbridge.github.io/openapi/java/com/longbridge/ /calendar.html#getCalendarContext) |
| C++ | [longbridge:: ::calendar::_calendar_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_calendar.html) |
## 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. |
## 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).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 |
#### Meeting Calendar
Browse upcoming shareholder meetings and company events.
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.calendar._calendar_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.calendar._calendar_context) |
| Rust | [longbridge:: ::calendar#_calendar_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.calendar.html#method._calendar_context) |
| Go | [calendar.finance_calendar](https://pkg.go.dev/github.com/longbridge/openapi-go/ #calendar.finance_calendar) |
| Node.js | [calendar#CalendarContext](https://longbridge.github.io/openapi/nodejs/classes/calendar.html#calendarcontext) |
| Java | [calendar.getCalendarContext](https://longbridge.github.io/openapi/java/com/longbridge/ /calendar.html#getCalendarContext) |
| C++ | [longbridge:: ::calendar::_calendar_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_calendar.html) |
## 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. |
## 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).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 |
#### Split Calendar
Get upcoming and historical stock split and reverse split events.
longbridge finance-calendar split
longbridge finance-calendar split --market HK
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.calendar._calendar_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.calendar._calendar_context) |
| Rust | [longbridge:: ::calendar#_calendar_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.calendar.html#method._calendar_context) |
| Go | [calendar.finance_calendar](https://pkg.go.dev/github.com/longbridge/openapi-go/ #calendar.finance_calendar) |
| Node.js | [calendar#CalendarContext](https://longbridge.github.io/openapi/nodejs/classes/calendar.html#calendarcontext) |
| Java | [calendar.getCalendarContext](https://longbridge.github.io/openapi/java/com/longbridge/ /calendar.html#getCalendarContext) |
| C++ | [longbridge:: ::calendar::_calendar_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_calendar.html) |
## 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. |
## Request Example
```python
from longbridge.openapi import CalendarContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = CalendarContext(config)
resp = ctx.split_calendar("AAPL.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncCalendarContext, 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.split_calendar("AAPL.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, CalendarContext, 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.split_calendar('AAPL.US')
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.getSplitCalendar("AAPL.US").get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, calendar::CalendarContext, 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.split_calendar("AAPL.US").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.split_calendar("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/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.SplitCalendar(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": "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": []
}
]
}
]
}
}
```
### 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 |
### Trade
### Definition
## 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) |
| 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 |
### 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"
}
}
```
### Overview
# 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;
}
```
#### Order
#### Estimate Maximum Purchase Quantity
This API is used for estimating the maximum purchase quantity for Hong Kong and US stocks, warrants, and options.
longbridge max-qty TSLA.US
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.trade._trade_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.trade._trade_context) |
| Rust | [longbridge:: ::trade#_trade_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.trade.html#method._trade_context) |
| Go | [trade.estimate_max_purchase_quantity](https://pkg.go.dev/github.com/longbridge/openapi-go/ #trade.estimate_max_purchase_quantity) |
| Node.js | [trade#TradeContext](https://longbridge.github.io/openapi/nodejs/classes/trade.html#tradecontext) |
| Java | [trade.getTradeContext](https://longbridge.github.io/openapi/java/com/longbridge/ /trade.html#getTradeContext) |
| C++ | [longbridge:: ::trade::_trade_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_trade.html) |
## 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. |
#### Submit Order
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
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.trade._trade_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.trade._trade_context) |
| Rust | [longbridge:: ::trade#_trade_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.trade.html#method._trade_context) |
| Go | [trade.submit_order](https://pkg.go.dev/github.com/longbridge/openapi-go/ #trade.submit_order) |
| Node.js | [trade#TradeContext](https://longbridge.github.io/openapi/nodejs/classes/trade.html#tradecontext) |
| Java | [trade.getTradeContext](https://longbridge.github.io/openapi/java/com/longbridge/ /trade.html#getTradeContext) |
| C++ | [longbridge:: ::trade::_trade_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_trade.html) |
## 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` |
| 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 |
| 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 |
### 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 |
#### History Orders
This API is used to get history order.
longbridge order --history
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.trade._trade_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.trade._trade_context) |
| Rust | [longbridge:: ::trade#_trade_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.trade.html#method._trade_context) |
| Go | [trade.history_orders](https://pkg.go.dev/github.com/longbridge/openapi-go/ #trade.history_orders) |
| Node.js | [trade#TradeContext](https://longbridge.github.io/openapi/nodejs/classes/trade.html#tradecontext) |
| Java | [trade.getTradeContext](https://longbridge.github.io/openapi/java/com/longbridge/ /trade.html#getTradeContext) |
| C++ | [longbridge:: ::trade::_trade_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_trade.html) |
## 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": ""
}
]
}
]
}
}
```
### 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 |
#### US Order Detail
:::warning Longbridge US Accounts
This method is only available for US data-center accounts.
:::
Get detail for a specific US order — execution history, order status, and any attached child orders.
# View US order detail
longbridge order detail 701276261045858304
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.trade._trade_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.trade._trade_context) |
| Rust | [longbridge:: ::trade#_trade_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.trade.html#method._trade_context) |
| Go | [trade.us_order_detail](https://pkg.go.dev/github.com/longbridge/openapi-go/ #trade.us_order_detail) |
| Node.js | [trade#TradeContext](https://longbridge.github.io/openapi/nodejs/classes/trade.html#tradecontext) |
| Java | [trade.getTradeContext](https://longbridge.github.io/openapi/java/com/longbridge/ /trade.html#getTradeContext) |
| C++ | [longbridge:: ::trade::_trade_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_trade.html) |
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| order_id | string | YES | Order ID |
## 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.us_order_detail("701276261045858304")
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.us_order_detail("701276261045858304")
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.usOrderDetail("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)) {
var resp = ctx.getUsOrderDetail("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: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = TradeContext::new(config);
let resp = ctx.us_order_detail("701276261045858304").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/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)
}
c, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.USOrderDetail(context.Background(), "701276261045858304")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"order": {
"id": "701276261045858304",
"symbol": "AAPL.US",
"action": "Buy",
"order_type": "LO",
"status": "Filled",
"price": "185.00",
"quantity": "10",
"executed_qty": "10",
"executed_price": "184.95",
"executed_amount": "1849.50",
"currency": "USD",
"submitted_at": "1751866334",
"done_at": "1751866400",
"time_in_force": 0,
"msg": ""
},
"current_attached_order": null,
"current_millisecond": "1751866400000"
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [USOrderDetailResponse](#USOrderDetailResponse) |
| 400 | Bad request | None |
### USOrderDetailResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| order | USOrderDetail \| null | true | Full order detail, null if not found |
| current_attached_order | USOrderDetail \| null | false | Attached child order (bracket/OCO) |
| current_millisecond | string | false | Server timestamp (milliseconds) |
### USOrderDetail
Core fields (the full response contains 50+ fields for fees, triggers, and settlement details):
| Name | Type | Description |
| ---- | ---- | ----------- |
| id | string | Order ID |
| symbol | string | Trading symbol (e.g. `AAPL.US`) |
| action | int | Direction: 1=Buy, 2=Sell |
| order_type | string | Order type |
| status | string | Order status |
| price | string | Order price |
| quantity | string | Order quantity |
| executed_qty | string | Executed quantity |
| executed_price | string | Average executed price |
| executed_amount | string | Total executed amount |
| currency | string | Currency code |
| submitted_at | string | Submission time |
| done_at | string | Completion time |
| time_in_force | int | Time-in-force type |
| trigger_price | string | Trigger price (stop orders) |
| msg | string | Status message |
| order_histories | USOrderHistory[] | Order state-transition history |
| attached_orders | USAttachedOrder[] | Attached child orders |
| button_control | USButtonControl | Available action buttons |
| charge_detail | USChargeDetail \| null | Fee breakdown |
### USOrderHistory
| Name | Type | Description |
| ---- | ---- | ----------- |
| exec_type | int | Execution type |
| status | string | Order status at this point |
| price | string | Price |
| qty | string | Quantity |
| time | string | Timestamp |
| msg | string | Message |
#### Cancel Order
This API is used to withdraw an open order.
# Replace the order ID below with your actual order ID
longbridge order cancel 693664675163312128
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.trade._trade_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.trade._trade_context) |
| Rust | [longbridge:: ::trade#_trade_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.trade.html#method._trade_context) |
| Go | [trade.cancel_order](https://pkg.go.dev/github.com/longbridge/openapi-go/ #trade.cancel_order) |
| Node.js | [trade#TradeContext](https://longbridge.github.io/openapi/nodejs/classes/trade.html#tradecontext) |
| Java | [trade.getTradeContext](https://longbridge.github.io/openapi/java/com/longbridge/ /trade.html#getTradeContext) |
| C++ | [longbridge:: ::trade::_trade_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_trade.html) |
## 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 |
#### Today Orders
This API is used to get today order or get order by order id.
longbridge order
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.trade._trade_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.trade._trade_context) |
| Rust | [longbridge:: ::trade#_trade_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.trade.html#method._trade_context) |
| Go | [trade.today_orders](https://pkg.go.dev/github.com/longbridge/openapi-go/ #trade.today_orders) |
| Node.js | [trade#TradeContext](https://longbridge.github.io/openapi/nodejs/classes/trade.html#tradecontext) |
| Java | [trade.getTradeContext](https://longbridge.github.io/openapi/java/com/longbridge/ /trade.html#getTradeContext) |
| C++ | [longbridge:: ::trade::_trade_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_trade.html) |
## 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": ""
}
]
}
]
}
}
```
### 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 |
#### Order Details
This API is used for order detail query
# Replace the order ID below with your actual order ID
longbridge order detail 693664675163312128
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.trade._trade_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.trade._trade_context) |
| Rust | [longbridge:: ::trade#_trade_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.trade.html#method._trade_context) |
| Go | [trade.order_detail](https://pkg.go.dev/github.com/longbridge/openapi-go/ #trade.order_detail) |
| Node.js | [trade#TradeContext](https://longbridge.github.io/openapi/nodejs/classes/trade.html#tradecontext) |
| Java | [trade.getTradeContext](https://longbridge.github.io/openapi/java/com/longbridge/ /trade.html#getTradeContext) |
| C++ | [longbridge:: ::trade::_trade_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_trade.html) |
## 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": ""
}
]
}
}
```
### 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 |
#### Replace Order
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
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.trade._trade_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.trade._trade_context) |
| Rust | [longbridge:: ::trade#_trade_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.trade.html#method._trade_context) |
| Go | [trade.replace_order](https://pkg.go.dev/github.com/longbridge/openapi-go/ #trade.replace_order) |
| Node.js | [trade#TradeContext](https://longbridge.github.io/openapi/nodejs/classes/trade.html#tradecontext) |
| Java | [trade.getTradeContext](https://longbridge.github.io/openapi/java/com/longbridge/ /trade.html#getTradeContext) |
| C++ | [longbridge:: ::trade::_trade_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_trade.html) |
## 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 |
### 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 |
#### US Order History
:::warning Longbridge US Accounts
This method is only available for US data-center accounts.
:::
Query historical and pending orders for US accounts with pagination and filtering.
# List US orders
longbridge order
# Filter pending orders
longbridge order --status pending
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.trade._trade_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.trade._trade_context) |
| Rust | [longbridge:: ::trade#_trade_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.trade.html#method._trade_context) |
| Go | [trade.us_query_orders](https://pkg.go.dev/github.com/longbridge/openapi-go/ #trade.us_query_orders) |
| Node.js | [trade#TradeContext](https://longbridge.github.io/openapi/nodejs/classes/trade.html#tradecontext) |
| Java | [trade.getTradeContext](https://longbridge.github.io/openapi/java/com/longbridge/ /trade.html#getTradeContext) |
| C++ | [longbridge:: ::trade::_trade_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_trade.html) |
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | NO | Filter by symbol, e.g. `AAPL.US` |
| action | int | NO | Direction filter: `0`=all, `1`=buy, `2`=sell (default: `0`) |
| start_at | int64 | NO | Start time (Unix seconds); `0` = last 90 days |
| end_at | int64 | NO | End time (Unix seconds); `0` = now |
| query_type | int | NO | `0`=all (incl. rejected), `1`=pending, `2`=filled only (default: `0`) |
| page | int | NO | Page number, 1-based (default: `1`) |
| limit | int | NO | Page size (default: `20`) |
## 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)
# List all orders (all defaults)
resp = ctx.us_query_orders()
# Filter: buy orders for AAPL.US
resp = ctx.us_query_orders(symbol="AAPL.US", action=1)
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.us_query_orders()
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.usQueryOrders(null, 0, 0, 0, 0, 1, 20)
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)) {
var resp = ctx.getUsQueryOrders("", 0, 0L, 0L, 0, 1, 20).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: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = TradeContext::new(config);
let opts = longbridge::trade::GetUSHistoryOrders {
symbol: None,
side: longbridge::trade::OrderSide::Unknown,
start_at: 0,
end_at: 0,
};
let resp = ctx.us_query_orders(opts).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/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)
}
c, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
page := int32(1)
limit := int32(20)
resp, err := c.QueryUSOrders(context.Background(), &trade.GetUSHistoryOrders{Page: page, Limit: limit})
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"orders": [
{
"id": "701276261045858304",
"symbol": "AAPL.US",
"action": "Buy",
"order_type": "LO",
"status": "Filled",
"price": "185.00",
"quantity": "10",
"submitted_at": 1751866334,
"updated_at": 1751866400
}
],
"total_count": 1
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [QueryUSOrdersResponse](#QueryUSOrdersResponse) |
| 400 | Bad request | None |
## Schemas
### QueryUSOrdersResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| orders | USOrder[] | true | List of orders matching the filter |
| total_count | int | true | Total number of matching orders |
### USOrder
| Name | Type | Description |
| ---- | ---- | ----------- |
| id | string | Order ID |
| symbol | string | Trading symbol (e.g. `AAPL.US`) |
| action | string | Direction: `Buy` or `Sell` |
| order_type | string | Order type |
| status | string | Order status |
| price | string | Order price |
| quantity | string | Order quantity |
| submitted_at | int64 | Submission time (Unix seconds) |
| updated_at | int64 | Last update time (Unix seconds) |
#### Execution
#### Today Executions
This API is used to get today executions.
longbridge order executions
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.trade._trade_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.trade._trade_context) |
| Rust | [longbridge:: ::trade#_trade_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.trade.html#method._trade_context) |
| Go | [trade.today_executions](https://pkg.go.dev/github.com/longbridge/openapi-go/ #trade.today_executions) |
| Node.js | [trade#TradeContext](https://longbridge.github.io/openapi/nodejs/classes/trade.html#tradecontext) |
| Java | [trade.getTradeContext](https://longbridge.github.io/openapi/java/com/longbridge/ /trade.html#getTradeContext) |
| C++ | [longbridge:: ::trade::_trade_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_trade.html) |
## 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",
"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 |
#### History Executions
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
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.trade._trade_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.trade._trade_context) |
| Rust | [longbridge:: ::trade#_trade_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.trade.html#method._trade_context) |
| Go | [trade.history_executions](https://pkg.go.dev/github.com/longbridge/openapi-go/ #trade.history_executions) |
| Node.js | [trade#TradeContext](https://longbridge.github.io/openapi/nodejs/classes/trade.html#tradecontext) |
| Java | [trade.getTradeContext](https://longbridge.github.io/openapi/java/com/longbridge/ /trade.html#getTradeContext) |
| C++ | [longbridge:: ::trade::_trade_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_trade.html) |
## 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. |
### 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",
"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 |
#### Asset
#### Fund Positions
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
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.trade._trade_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.trade._trade_context) |
| Rust | [longbridge:: ::trade#_trade_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.trade.html#method._trade_context) |
| Go | [trade.fund_positions](https://pkg.go.dev/github.com/longbridge/openapi-go/ #trade.fund_positions) |
| Node.js | [trade#TradeContext](https://longbridge.github.io/openapi/nodejs/classes/trade.html#tradecontext) |
| Java | [trade.getTradeContext](https://longbridge.github.io/openapi/java/com/longbridge/ /trade.html#getTradeContext) |
| C++ | [longbridge:: ::trade::_trade_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_trade.html) |
## 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": [
{
"symbol": "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 |
| ∟∟ symbol | string | true | Fund ISIN code |
| ∟∟ 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 |
#### US Realized P&L
:::warning Longbridge US Accounts
This method is only available for US data-center accounts.
:::
Get realized profit and loss for a US account, broken down by asset category.
# US realized P&L
longbridge profit-analysis realized
# Filter by stock
longbridge profit-analysis realized --category stock
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.trade._trade_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.trade._trade_context) |
| Rust | [longbridge:: ::trade#_trade_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.trade.html#method._trade_context) |
| Go | [trade.us_realized_pl](https://pkg.go.dev/github.com/longbridge/openapi-go/ #trade.us_realized_pl) |
| Node.js | [trade#TradeContext](https://longbridge.github.io/openapi/nodejs/classes/trade.html#tradecontext) |
| Java | [trade.getTradeContext](https://longbridge.github.io/openapi/java/com/longbridge/ /trade.html#getTradeContext) |
| C++ | [longbridge:: ::trade::_trade_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_trade.html) |
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| currency | string | YES | Settlement currency, e.g. `USD` |
| category | string | NO | Asset category: `ALL` \| `STOCK` \| `OPTION` \| `CRYPTO` (default: `ALL`) |
## 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.us_realized_pl("USD", category="STOCK")
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.us_realized_pl("USD", category="STOCK")
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.usRealizedPl("USD", "STOCK")
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)) {
var resp = ctx.getUsRealizedPl("USD", "STOCK").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: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = TradeContext::new(config);
let opts = longbridge::trade::GetUSRealizedPLOptions {
currency: "USD".to_string(),
category: "STOCK".to_string(),
};
let resp = ctx.us_realized_pl(opts).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/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)
}
c, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
cat := "STOCK"
resp, err := c.USRealizedPL(context.Background(), &trade.GetUSRealizedPL{Currency: "USD", Category: &cat})
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"realized_pl_list": [
{
"category": 1,
"currency": "USD",
"metrics": [
{"amount": "1250.50", "period": 1, "rate": "0.0312"}
]
},
{
"category": 3,
"currency": "USD",
"metrics": [
{"amount": "-85.20", "period": 1, "rate": "-0.0215"}
]
}
]
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [USRealizedPL](#USRealizedPL) |
| 400 | Bad request | None |
## Schemas
### USRealizedPL
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| realized_pl_list | USRealizedPLEntry[] | true | P&L breakdown by asset category |
### USRealizedPLEntry
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| category | int | true | Asset category: `1`=stock, `2`=option, `3`=crypto |
| currency | string | true | Currency code (e.g. `USD`) |
| metrics | USRealizedPLMetric[] | true | P&L metrics by time period |
### USRealizedPLMetric
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| amount | string | true | Realized P&L amount |
| period | int | true | Time period |
| rate | string | true | Return rate (%) |
#### Account Assets
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
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.trade._trade_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.trade._trade_context) |
| Rust | [longbridge:: ::trade#_trade_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.trade.html#method._trade_context) |
| Go | [trade.account_balance](https://pkg.go.dev/github.com/longbridge/openapi-go/ #trade.account_balance) |
| Node.js | [trade#TradeContext](https://longbridge.github.io/openapi/nodejs/classes/trade.html#tradecontext) |
| Java | [trade.getTradeContext](https://longbridge.github.io/openapi/java/com/longbridge/ /trade.html#getTradeContext) |
| C++ | [longbridge:: ::trade::_trade_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_trade.html) |
## 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 |
#### Stock Positions
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
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.trade._trade_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.trade._trade_context) |
| Rust | [longbridge:: ::trade#_trade_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.trade.html#method._trade_context) |
| Go | [trade.stock_positions](https://pkg.go.dev/github.com/longbridge/openapi-go/ #trade.stock_positions) |
| Node.js | [trade#TradeContext](https://longbridge.github.io/openapi/nodejs/classes/trade.html#tradecontext) |
| Java | [trade.getTradeContext](https://longbridge.github.io/openapi/java/com/longbridge/ /trade.html#getTradeContext) |
| C++ | [longbridge:: ::trade::_trade_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_trade.html) |
## 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 |
#### Margin Ratio
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
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.trade._trade_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.trade._trade_context) |
| Rust | [longbridge:: ::trade#_trade_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.trade.html#method._trade_context) |
| Go | [trade.margin_ratio](https://pkg.go.dev/github.com/longbridge/openapi-go/ #trade.margin_ratio) |
| Node.js | [trade#TradeContext](https://longbridge.github.io/openapi/nodejs/classes/trade.html#tradecontext) |
| Java | [trade.getTradeContext](https://longbridge.github.io/openapi/java/com/longbridge/ /trade.html#getTradeContext) |
| C++ | [longbridge:: ::trade::_trade_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_trade.html) |
## 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 |
#### US Asset Overview
:::warning Longbridge US Accounts
This method is only available for US data-center accounts.
:::
Get an overview of US account assets — buying power, cash, stocks, options, and crypto.
# US account asset overview
longbridge positions
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.trade._trade_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.trade._trade_context) |
| Rust | [longbridge:: ::trade#_trade_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.trade.html#method._trade_context) |
| Go | [trade.us_asset_overview](https://pkg.go.dev/github.com/longbridge/openapi-go/ #trade.us_asset_overview) |
| Node.js | [trade#TradeContext](https://longbridge.github.io/openapi/nodejs/classes/trade.html#tradecontext) |
| Java | [trade.getTradeContext](https://longbridge.github.io/openapi/java/com/longbridge/ /trade.html#getTradeContext) |
| C++ | [longbridge:: ::trade::_trade_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_trade.html) |
## Parameters
> **SDK method parameters.**
No parameters required.
## 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.us_asset_overview()
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.us_asset_overview()
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.usAssetOverview()
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)) {
var resp = ctx.getUsAssetOverview().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: {url}")).await?;
let config = Arc::new(Config::from_oauth(oauth));
let ctx = TradeContext::new(config);
let resp = ctx.us_asset_overview().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/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)
}
c, err := trade.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.USAssetOverview(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"account_type": "US",
"asset_timestamp": 1751866334,
"cash_buy_power": "12500.00",
"overnight_buy_power": "10000.00",
"currency": "USD",
"cash_list": [
{
"currency": "USD",
"total_cash": "12500.00",
"settled_cash": "12000.00",
"total_amount": "12500.00",
"outstanding": "500.00",
"frozen_buy_cash": "0.00"
}
],
"stock_list": [
{
"symbol": "AAPL.US",
"quantity": "10",
"currency": "USD",
"average_cost": "180.00",
"last_done": "185.00",
"prev_close": "183.00",
"asset_type": "stock",
"trade_status": "Normal"
}
],
"crypto_list": [
{
"symbol": "BTCUSD.BKKT",
"average_cost": "50000.00",
"currency": "USD",
"asset_type": "crypto",
"industry_name": "Cryptocurrency"
}
]
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [USAssetOverview](#USAssetOverview) |
| 400 | Bad request | None |
## Schemas
### USAssetOverview
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| account_type | string | true | Account type identifier |
| asset_timestamp | string | true | Snapshot time (Unix seconds) |
| cash_buy_power | string | true | Available buying power (cash) |
| overnight_buy_power | string | true | Overnight buying power |
| currency | string | true | Base currency |
| cash_list | USCashEntry[] | false | Cash balances by currency |
| stock_list | USStockEntry[] | false | Stock positions |
| option_list | object[] | false | Option positions |
| crypto_list | USCryptoEntry[] | false | Crypto positions |
### USCashEntry
| Name | Type | Description |
| ---- | ---- | ----------- |
| currency | string | Currency code |
| total_cash | string | Total cash |
| settled_cash | string | Settled cash |
| total_amount | string | Total amount including unsettled |
| outstanding | string | Outstanding (unsettled) amount |
| frozen_buy_cash | string | Frozen amount for pending buys |
### USStockEntry
| Name | Type | Description |
| ---- | ---- | ----------- |
| symbol | string | Ticker symbol (e.g. `AAPL`) |
| full_symbol | string | Qualified symbol (e.g. `AAPL.US`) |
| asset_type | string | Asset type |
| quantity | string | Quantity held |
| currency | string | Currency code |
| average_cost | string | Average cost price |
| market | string | Market identifier |
| trade_status | string | Trading status |
| prev_close | string | Previous close price |
| last_done | string | Last traded price |
| market_price | string | Current market price |
| today_pl | string | Today's P&L |
| name | string | Security name |
| position_side | string | Position side (long/short) |
| industry_name | string | Industry/sector name |
### USCryptoEntry
| Name | Type | Description |
| ---- | ---- | ----------- |
| symbol | string | Crypto trading-pair symbol (e.g. `BTCUSD.BKKT`) |
| average_cost | string | Average cost price |
| currency | string | Quote currency |
| asset_type | string | Asset type |
| industry_name | string | Industry/category name |
#### Cash Flow
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
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.trade._trade_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.trade._trade_context) |
| Rust | [longbridge:: ::trade#_trade_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.trade.html#method._trade_context) |
| Go | [trade.cash_flow](https://pkg.go.dev/github.com/longbridge/openapi-go/ #trade.cash_flow) |
| Node.js | [trade#TradeContext](https://longbridge.github.io/openapi/nodejs/classes/trade.html#tradecontext) |
| Java | [trade.getTradeContext](https://longbridge.github.io/openapi/java/com/longbridge/ /trade.html#getTradeContext) |
| C++ | [longbridge:: ::trade::_trade_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_trade.html) |
## 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 |
### Qa
### Trade
## 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 and Grid orders.
## Q2: What are the trading hours for paper accounts?
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?
Paper accounts currently support trading in Hong Kong and U.S. stocks, ETFs, Hong Kong warrants, and U.S. options. Short selling is supported for U.S. stocks. However, OTC trading and pre & post market trading are 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.
### Quote Releated
## 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)
```
### General
## Q1: Do I need to open a live account to call Longbridge Developers?
No. 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.
## 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?
Market: Supports 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: Supports trading of Hong Kong and US stocks, ETFs, Hong Kong warrant trading, and US options. Short selling is supported for US stocks. OTC stocks and pre & post market trading are not supported in paper 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/apps/longbridge/asdk_app_6a2baf2fad748191812393c3e00308ef) 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.
### Account
### Overview
# Account API Overview
Account management APIs covering portfolio analysis, price alerts, recurring investment plans, and share lists. Most methods require Trade-level authentication.
## PortfolioContext
Portfolio profit/loss analysis and currency exchange rates.
| Method | Description |
|---|---|
| [profit_analysis_summary](./portfolio/profit-analysis-summary) | Overall portfolio P&L summary |
| [profit_analysis_detail](./portfolio/profit-analysis-detail) | Per-position P&L breakdown |
| [profit_analysis_by_market](./portfolio/profit-analysis-by-market) | P&L grouped by market |
| [capital_flow](./portfolio/capital-flow) | Account capital flow history |
| [exchange_rates](./portfolio/exchange-rates) | Current exchange rates for supported currencies |
## AlertContext
Create and manage price alerts for securities.
| Method | Description |
|---|---|
| [list_alerts](./alert/list-alerts) | List all active price alerts |
| [create_alert](./alert/create-alert) | Create a new price alert |
| [update_alert](./alert/update-alert) | Update an existing alert |
| [delete_alert](./alert/delete-alert) | Delete a price alert |
## DCAContext
Manage dollar-cost averaging (recurring investment) plans.
| Method | Description |
|---|---|
| [list_dca](./dca/list-dca) | List all DCA plans |
| [create_dca](./dca/create-dca) | Create a new DCA plan |
| [dca_history](./dca/dca-history) | View execution history for a DCA plan |
| [delete_dca](./dca/delete-dca) | Cancel a DCA plan |
## SharelistContext
Create and manage community share lists (watchlists shared with others).
| Method | Description |
|---|---|
| [list_sharelist](./sharelist/list-sharelist) | List all share lists |
| [create_sharelist](./sharelist/create-sharelist) | Create a new share list |
| [update_sharelist](./sharelist/update-sharelist) | Update a share list |
| [delete_sharelist](./sharelist/delete-sharelist) | Delete a share list |
#### Portfolio
#### Profit Analysis Detail
Get detailed P&L for a specific security including transaction flow and cost breakdown.
longbridge profit-analysis detail TSLA.US
longbridge profit-analysis detail AAPL.US
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.portfolio._portfolio_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.portfolio._portfolio_context) |
| Rust | [longbridge:: ::portfolio#_portfolio_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.portfolio.html#method._portfolio_context) |
| Go | [portfolio.profit_analysis_detail](https://pkg.go.dev/github.com/longbridge/openapi-go/ #portfolio.profit_analysis_detail) |
| Node.js | [portfolio#PortfolioContext](https://longbridge.github.io/openapi/nodejs/classes/portfolio.html#portfoliocontext) |
| Java | [portfolio.getPortfolioContext](https://longbridge.github.io/openapi/java/com/longbridge/ /portfolio.html#getPortfolioContext) |
| C++ | [longbridge:: ::portfolio::_portfolio_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_portfolio.html) |
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `AAPL.US` |
| start | string | NO | Start date, `YYYY-MM-DD` |
| end | string | NO | End date, `YYYY-MM-DD` | Analysis end date in `YYYY-MM-DD` format |
## Request Example
```python
from longbridge.openapi import PortfolioContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = PortfolioContext(config)
resp = ctx.profit_analysis_detail("TSLA.US")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncPortfolioContext, 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 = AsyncPortfolioContext.create(config)
resp = await ctx.profit_analysis_detail("TSLA.US")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, PortfolioContext, 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 = PortfolioContext.new(config)
const resp = await ctx.profit_analysis_detail()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.portfolio.*;
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);
PortfolioContext ctx = PortfolioContext.create(config)) {
var resp = ctx.getProfitAnalysisDetail().get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, portfolio::PortfolioContext, 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 = PortfolioContext::new(config);
let resp = ctx.profit_analysis_detail().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::portfolio;
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);
PortfolioContext ctx = PortfolioContext::create(config);
ctx.profit_analysis_detail([](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/portfolio"
)
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 := portfolio.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.ProfitAnalysisDetail(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"name": "Apple",
"currency": "USD",
"profit": "100.00",
"start": "1763769600",
"end": "1778724973",
"start_date": "2025-11-22",
"end_date": "2026-05-14",
"default_tag": 0,
"updated_at": "1778724973",
"updated_date": "2026-05-14",
"underlying_details": {
"profit": "100.00",
"holding_value": "1790.16",
"holding_value_at_beginning": null,
"holding_value_at_ending": "1790.16",
"long_holding_value": "1790.16",
"short_holding_value": "0.00",
"cumulative_credited_amount": "0.00",
"cumulative_debited_amount": "0.00",
"cumulative_fee_amount": "0.00",
"credited_details": [],
"debited_details": [],
"fee_details": []
},
"derivative_pnl_details": {
"profit": "0.00",
"holding_value": "0.00",
"holding_value_at_beginning": null,
"holding_value_at_ending": "0.00",
"long_holding_value": "0.00",
"short_holding_value": "0.00",
"cumulative_credited_amount": "0.00",
"cumulative_debited_amount": "0.00",
"cumulative_fee_amount": "0.00",
"credited_details": [],
"debited_details": [],
"fee_details": []
}
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [ProfitAnalysisDetailResponse](#ProfitAnalysisDetailResponse) |
| 400 | Bad request | None |
## Schemas
### ProfitAnalysisDetailResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| name | string | false | Security name |
| currency | string | false | Currency |
| profit | string | false | Total profit/loss |
| start | integer | false | Period start |
| end | integer | false | Period end |
| start_date | string | false | Start date |
| end_date | string | false | End date |
| default_tag | integer | false | Default display tag |
| underlying_details | object | false | Underlying asset P&L breakdown |
| updated_at | string | false | Last update timestamp |
| updated_date | string | false | Last update date |
| derivative_pnl_details | object | false | Derivatives P&L breakdown |
### ProfitDetails
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| profit | string | false | Total profit/loss |
| holding_value | string | false | Current holding value |
| holding_value_at_beginning | string | false | Holding value at period start |
| holding_value_at_ending | string | false | Holding value at period end |
| long_holding_value | string | false | Long position value |
| short_holding_value | string | false | Short position value |
| cumulative_credited_amount | string | false | Cumulative credited amount |
| cumulative_debited_amount | string | false | Cumulative debited amount |
| cumulative_fee_amount | string | false | Cumulative fee amount |
| credited_details | object[] | false | Credit transaction details |
| debited_details | object[] | false | Debit transaction details |
| fee_details | object[] | false | Fee transaction details |
#### Profit Analysis Flows
Query account cash flow history including deposits, withdrawals, dividends, and settlements.
longbridge cash-flow
longbridge cash-flow --format json
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.portfolio._portfolio_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.portfolio._portfolio_context) |
| Rust | [longbridge:: ::portfolio#_portfolio_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.portfolio.html#method._portfolio_context) |
| Go | [portfolio.profit_analysis_flows](https://pkg.go.dev/github.com/longbridge/openapi-go/ #portfolio.profit_analysis_flows) |
| Node.js | [portfolio#PortfolioContext](https://longbridge.github.io/openapi/nodejs/classes/portfolio.html#portfoliocontext) |
| Java | [portfolio.getPortfolioContext](https://longbridge.github.io/openapi/java/com/longbridge/ /portfolio.html#getPortfolioContext) |
| C++ | [longbridge:: ::portfolio::_portfolio_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_portfolio.html) |
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol |
| page | integer | NO | Page number (default: 1) |
| size | integer | NO | Page size (default: 20) |
| derivative | boolean | NO | Include derivative positions |
## Request Example
```python
from longbridge.openapi import PortfolioContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = PortfolioContext(config)
resp = ctx.profit_analysis_flows()
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncPortfolioContext, 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 = AsyncPortfolioContext.create(config)
resp = await ctx.profit_analysis_flows()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, PortfolioContext, 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 = PortfolioContext.new(config)
const resp = await ctx.profit_analysis_flows()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.portfolio.*;
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);
PortfolioContext ctx = PortfolioContext.create(config)) {
var resp = ctx.getProfitAnalysisFlows().get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, portfolio::PortfolioContext, 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 = PortfolioContext::new(config);
let resp = ctx.profit_analysis_flows().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::portfolio;
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);
PortfolioContext ctx = PortfolioContext::create(config);
ctx.profit_analysis_flows([](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/portfolio"
)
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 := portfolio.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.ProfitAnalysisFlows(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"has_more": false,
"flows_list": [
{
"code": "AAPL",
"symbol": "AAPL.US",
"direction": "In",
"executed_date": "2025-11-22",
"executed_timestamp": "1763769600",
"executed_quantity": "10",
"executed_price": "180.50",
"executed_cost": "1805.00",
"describe": "Buy AAPL.US"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [ProfitAnalysisFlowsResponse](#ProfitAnalysisFlowsResponse) |
| 400 | Bad request | None |
## Schemas
### ProfitAnalysisFlowsResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| flows_list | object[] | true | Paginated list of flow items |
| ∟ executed_date | string | true | Execution date (e.g. `2024-01-15`) |
| ∟ executed_timestamp | string | false | Execution timestamp |
| ∟ code | string | false | Security code |
| ∟ direction | string | false | Direction: `In` or `Out` |
| ∟ executed_quantity | string | false | Executed quantity |
| ∟ executed_price | string | false | Executed price |
| ∟ executed_cost | string | false | Executed cost |
| ∟ describe | string | false | Human-readable description |
| has_more | boolean | false | Whether there are more pages |
#### Profit Analysis Summary
Get a P&L summary for the account including total asset, total P&L, and yield metrics.
longbridge profit-analysis
longbridge profit-analysis --start 2026-01-01
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.portfolio._portfolio_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.portfolio._portfolio_context) |
| Rust | [longbridge:: ::portfolio#_portfolio_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.portfolio.html#method._portfolio_context) |
| Go | [portfolio.profit_analysis_summary](https://pkg.go.dev/github.com/longbridge/openapi-go/ #portfolio.profit_analysis_summary) |
| Node.js | [portfolio#PortfolioContext](https://longbridge.github.io/openapi/nodejs/classes/portfolio.html#portfoliocontext) |
| Java | [portfolio.getPortfolioContext](https://longbridge.github.io/openapi/java/com/longbridge/ /portfolio.html#getPortfolioContext) |
| C++ | [longbridge:: ::portfolio::_portfolio_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_portfolio.html) |
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| start_date | string | NO | Analysis start date in `YYYY-MM-DD` format |
| end_date | string | NO | Analysis end date in `YYYY-MM-DD` format |
## Request Example
```python
from longbridge.openapi import PortfolioContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = PortfolioContext(config)
resp = ctx.profit_analysis_summary()
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncPortfolioContext, 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 = AsyncPortfolioContext.create(config)
resp = await ctx.profit_analysis_summary()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, PortfolioContext, 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 = PortfolioContext.new(config)
const resp = await ctx.profit_analysis_summary()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.portfolio.*;
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);
PortfolioContext ctx = PortfolioContext.create(config)) {
var resp = ctx.getProfitAnalysisSummary().get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, portfolio::PortfolioContext, 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 = PortfolioContext::new(config);
let resp = ctx.profit_analysis_summary().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::portfolio;
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);
PortfolioContext ctx = PortfolioContext::create(config);
ctx.profit_analysis_summary([](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/portfolio"
)
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 := portfolio.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.ProfitAnalysisSummary(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"summary": {
"currency": "USD",
"sum_profit": "62905.97",
"sum_profit_rate": "0.6128",
"invest_amount": "102659.74",
"current_total_asset": "165565.71",
"initial_asset_value": "0.00",
"ending_asset_value": "165565.71",
"is_traded": true,
"start_date": "2025-10-17",
"start_time": "1760659200",
"end_date": "2026-05-14",
"end_time": "1778731947",
"profits": {
"stock": "66370.84",
"crypto": "0",
"fund": null,
"ipo": null,
"mmf": null,
"other": null,
"cumulative_transaction_amount": "1244920.28"
}
},
"sublist": {
"start": "2025-10-17",
"start_date": "2025-10-17",
"end": "2026-05-14",
"end_date": "2026-05-14",
"updated_at": "1778731947",
"updated_date": "2026-05-14",
"items": [
{
"symbol": "AAPL.US",
"name": "Apple",
"market": "US",
"currency": "USD",
"profit": "100.00",
"profit_rate": "0.05",
"holding_period": "180",
"clearance_times": 0,
"is_holding": true,
"item_type": "Stock",
"isin": "",
"security_code": "AAPL",
"underlying_profit": "100.00",
"derivatives_profit": "0.00",
"order_profit": null
}
]
}
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [ProfitAnalysisResponse](#ProfitAnalysisResponse) |
| 400 | Bad request | None |
## Schemas
### ProfitAnalysisResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| summary | object | true | Overall summary |
| sublist | object | false | Per-position breakdown |
### ProfitAnalysisSummary
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| currency | string | false | Currency |
| sum_profit | string | false | Total profit/loss |
| sum_profit_rate | string | false | Total profit/loss rate |
| invest_amount | string | false | Total invested amount |
| current_total_asset | string | false | Current total asset value |
| initial_asset_value | string | false | Initial asset value |
| ending_asset_value | string | false | Ending asset value |
| is_traded | boolean | false | Whether any trades exist |
| start_date | string | false | Period start date |
| start_time | string | false | Period start timestamp |
| end_date | string | false | Period end date |
| end_time | string | false | Period end timestamp |
| profits | object | false | Profit breakdown by category |
| profits.stock | string | false | Stock profit |
| profits.crypto | string | false | Crypto profit |
| profits.fund | string | false | Fund profit |
| profits.ipo | string | false | IPO profit |
| profits.mmf | string | false | Money market fund profit |
| profits.other | string | false | Other profit |
| profits.cumulative_transaction_amount | string | false | Cumulative transaction amount |
### ProfitAnalysisSublist
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| start | string | false | Period start |
| start_date | string | false | Start date |
| end | string | false | Period end |
| end_date | string | false | End date |
| updated_at | string | false | Last update timestamp |
| updated_date | string | false | Last update date |
| items | object[] | false | Per-position P&L items, see [ProfitAnalysisItem](#ProfitAnalysisItem) |
### ProfitAnalysisItem
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | false | Security symbol |
| name | string | false | Security name |
| market | string | false | Market |
| currency | string | false | Currency |
| profit | string | false | Profit/loss |
| profit_rate | string | false | Profit/loss rate |
| holding_period | string | false | Holding period (days) |
| clearance_times | integer | false | Number of clearances |
| is_holding | boolean | false | Whether currently holding |
| item_type | string | false | Asset type: `Stock`, `Fund`, `Crypto`, etc. |
| isin | string | false | ISIN code |
| security_code | string | false | Security code |
| underlying_profit | string | false | Underlying stock profit |
| derivatives_profit | string | false | Derivatives profit |
| order_profit | string | false | Order profit |
#### Exchange Rates
Get current foreign exchange rates for all currency pairs used in your account.
longbridge exchange-rate
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.portfolio._portfolio_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.portfolio._portfolio_context) |
| Rust | [longbridge:: ::portfolio#_portfolio_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.portfolio.html#method._portfolio_context) |
| Go | [portfolio.exchange_rates](https://pkg.go.dev/github.com/longbridge/openapi-go/ #portfolio.exchange_rates) |
| Node.js | [portfolio#PortfolioContext](https://longbridge.github.io/openapi/nodejs/classes/portfolio.html#portfoliocontext) |
| Java | [portfolio.getPortfolioContext](https://longbridge.github.io/openapi/java/com/longbridge/ /portfolio.html#getPortfolioContext) |
| C++ | [longbridge:: ::portfolio::_portfolio_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_portfolio.html) |
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| base | string | NO | Base currency, e.g. `USD`. Omit for all pairs. |
## Request Example
```python
from longbridge.openapi import PortfolioContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = PortfolioContext(config)
resp = ctx.exchange_rates()
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncPortfolioContext, 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 = AsyncPortfolioContext.create(config)
resp = await ctx.exchange_rates()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, PortfolioContext, 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 = PortfolioContext.new(config)
const resp = await ctx.exchange_rates()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.portfolio.*;
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);
PortfolioContext ctx = PortfolioContext.create(config)) {
var resp = ctx.getExchangeRates().get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, portfolio::PortfolioContext, 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 = PortfolioContext::new(config);
let resp = ctx.exchange_rates().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::portfolio;
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);
PortfolioContext ctx = PortfolioContext::create(config);
ctx.exchange_rates([](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/portfolio"
)
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 := portfolio.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.ExchangeRates(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"exchanges": [
{
"base_currency": "USD",
"other_currency": "HKD",
"bid_rate": 7.785,
"offer_rate": 7.795,
"average_rate": 7.79
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [ExchangeRatesResponse](#ExchangeRatesResponse) |
| 400 | Bad request | None |
## Schemas
### ExchangeRatesResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| exchanges | object[] | true | List of exchange rates |
| ∟ base_currency | string | true | Base currency |
| ∟ other_currency | string | true | Quote currency |
| ∟ bid_rate | number | false | Bid rate |
| ∟ offer_rate | number | false | Offer rate |
| ∟ average_rate | number | false | Average exchange rate |
#### Profit Analysis by Market
Get P&L breakdown grouped by market (US, HK, CN, SG).
longbridge profit-analysis --format json
longbridge profit-analysis --start 2026-01-01
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.portfolio._portfolio_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.portfolio._portfolio_context) |
| Rust | [longbridge:: ::portfolio#_portfolio_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.portfolio.html#method._portfolio_context) |
| Go | [portfolio.profit_analysis_by_market](https://pkg.go.dev/github.com/longbridge/openapi-go/ #portfolio.profit_analysis_by_market) |
| Node.js | [portfolio#PortfolioContext](https://longbridge.github.io/openapi/nodejs/classes/portfolio.html#portfoliocontext) |
| Java | [portfolio.getPortfolioContext](https://longbridge.github.io/openapi/java/com/longbridge/ /portfolio.html#getPortfolioContext) |
| C++ | [longbridge:: ::portfolio::_portfolio_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_portfolio.html) |
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| start_date | string | NO | Analysis start date in `YYYY-MM-DD` format |
| end_date | string | NO | Analysis end date in `YYYY-MM-DD` format |
## Request Example
```python
from longbridge.openapi import PortfolioContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = PortfolioContext(config)
resp = ctx.profit_analysis_by_market()
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncPortfolioContext, 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 = AsyncPortfolioContext.create(config)
resp = await ctx.profit_analysis_by_market()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, PortfolioContext, 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 = PortfolioContext.new(config)
const resp = await ctx.profit_analysis_by_market()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.portfolio.*;
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);
PortfolioContext ctx = PortfolioContext.create(config)) {
var resp = ctx.getProfitAnalysisByMarket().get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, portfolio::PortfolioContext, 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 = PortfolioContext::new(config);
let resp = ctx.profit_analysis_by_market().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::portfolio;
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);
PortfolioContext ctx = PortfolioContext::create(config);
ctx.profit_analysis_by_market([](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/portfolio"
)
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 := portfolio.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.ProfitAnalysisByMarket(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"has_more": false,
"profit": "-16325.26",
"stock_items": [
{
"code": "AAPL",
"market": "US",
"name": "Apple",
"profit": "100.00"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [ProfitAnalysisByMarketResponse](#ProfitAnalysisByMarketResponse) |
| 400 | Bad request | None |
## Schemas
### ProfitAnalysisByMarketResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| has_more | boolean | false | Whether there are more pages |
| profit | string | false | Total profit/loss |
| stock_items | object[] | false | P&L breakdown by stock |
| ∟ code | string | false | Stock code |
| ∟ market | string | false | Market code |
| ∟ name | string | false | Stock name |
| ∟ profit | string | false | Profit/loss for this stock |
#### Dca
#### Stop DCA Plan
:::warning Not for Longbridge US Accounts
This method requires an AP data-center account (HK / SG). US data-center accounts will receive a region restriction error. AP accounts can call this method with any supported symbol, including US stocks.
:::
Permanently stop a DCA plan. This action cannot be undone.
longbridge dca stop 12345
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.dca._d_c_a_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.dca._d_c_a_context) |
| Rust | [longbridge:: ::dca#_d_c_a_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.dca.html#method._d_c_a_context) |
| Go | [dca.stop](https://pkg.go.dev/github.com/longbridge/openapi-go/ #dca.stop) |
| Node.js | [dca#DCAContext](https://longbridge.github.io/openapi/nodejs/classes/dca.html#dcacontext) |
| Java | [dca.getDCAContext](https://longbridge.github.io/openapi/java/com/longbridge/ /dca.html#getDCAContext) |
| C++ | [longbridge:: ::dca::_d_c_a_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_dca.html) |
## Parameters
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| plan_id | string | YES | DCA plan ID |
## Request Example
```python
from longbridge.openapi import DCAContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = DCAContext(config)
ctx.stop("12345")
```
```python
import asyncio
from longbridge.openapi import AsyncDCAContext, 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 = AsyncDCAContext.create(config)
await ctx.stop("12345")
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, DCAContext, 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 = DCAContext.new(config)
await ctx.stop('12345')
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.dca.*;
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);
DCAContext ctx = DCAContext.create(config)) {
ctx.stop("12345").get();
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, dca::DCAContext, 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 = DCAContext::new(config);
ctx.stop("12345").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/dca"
)
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 := dca.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
if err := c.Stop(context.Background(), "12345"); 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 DCA Plan
:::warning Not for Longbridge US Accounts
This method requires an AP data-center account (HK / SG). US data-center accounts will receive a region restriction error. AP accounts can call this method with any supported symbol, including US stocks.
:::
Create a new recurring investment plan for a security.
longbridge dca create AAPL.US --amount 500 --frequency monthly --day-of-month 15
longbridge dca create TSLA.US --amount 200 --frequency weekly --day-of-week mon
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.dca._d_c_a_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.dca._d_c_a_context) |
| Rust | [longbridge:: ::dca#_d_c_a_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.dca.html#method._d_c_a_context) |
| Go | [dca.create](https://pkg.go.dev/github.com/longbridge/openapi-go/ #dca.create) |
| Node.js | [dca#DCAContext](https://longbridge.github.io/openapi/nodejs/classes/dca.html#dcacontext) |
| Java | [dca.getDCAContext](https://longbridge.github.io/openapi/java/com/longbridge/ /dca.html#getDCAContext) |
| C++ | [longbridge:: ::dca::_d_c_a_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_dca.html) |
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `AAPL.US` |
| amount | string | YES | Recurring investment amount |
| frequency | string | YES | Frequency: `Daily`, `Weekly`, `Fortnightly`, `Monthly` |
| day_of_week | string | NO | Day of week for weekly/fortnightly plans: `mon`–`fri` |
| day_of_month | integer | NO | Day of month for monthly plans (1–28) |
## Request Example
```python
from longbridge.openapi import DCAContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = DCAContext(config)
resp = ctx.create_dca("AAPL.US", amount="500", frequency="Monthly", day_of_month=15)
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncDCAContext, 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 = AsyncDCAContext.create(config)
resp = await ctx.create_dca("AAPL.US", amount="500", frequency="Monthly", day_of_month=15)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, DCAContext, 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 = DCAContext.new(config)
const resp = await ctx.create_dca()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.dca.*;
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);
DCAContext ctx = DCAContext.create(config)) {
var resp = ctx.getCreateDca().get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, dca::DCAContext, 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 = DCAContext::new(config);
let resp = ctx.create_dca().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::dca;
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);
DCAContext ctx = DCAContext::create(config);
ctx.create_dca([](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/dca"
)
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 := dca.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.CreateDca(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"id": "1225781523156889601"
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [CreateDcaResponse](#CreateDcaResponse) |
| 400 | Bad request | None |
## Schemas
### CreateDcaResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | string | true | ID of the newly created plan |
#### Set DCA Reminder
:::warning Not for Longbridge US Accounts
This method requires an AP data-center account (HK / SG). US data-center accounts will receive a region restriction error. AP accounts can call this method with any supported symbol, including US stocks.
:::
Set the advance reminder time for DCA plans. Supported values: `1`, `6`, or `12` hours.
longbridge dca set-reminder 12
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.dca._d_c_a_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.dca._d_c_a_context) |
| Rust | [longbridge:: ::dca#_d_c_a_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.dca.html#method._d_c_a_context) |
| Go | [dca.set_reminder](https://pkg.go.dev/github.com/longbridge/openapi-go/ #dca.set_reminder) |
| Node.js | [dca#DCAContext](https://longbridge.github.io/openapi/nodejs/classes/dca.html#dcacontext) |
| Java | [dca.getDCAContext](https://longbridge.github.io/openapi/java/com/longbridge/ /dca.html#getDCAContext) |
| C++ | [longbridge:: ::dca::_d_c_a_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_dca.html) |
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| hours | string | YES | Reminder advance hours: `1`, `6`, or `12` |
## Request Example
```python
from longbridge.openapi import DCAContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = DCAContext(config)
ctx.set_reminder("12")
```
```python
import asyncio
from longbridge.openapi import AsyncDCAContext, 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 = AsyncDCAContext.create(config)
await ctx.set_reminder("12")
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, DCAContext, 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 = DCAContext.new(config)
await ctx.setReminder('12')
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.dca.*;
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);
DCAContext ctx = DCAContext.create(config)) {
ctx.setReminder("12").get();
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, dca::DCAContext, 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 = DCAContext::new(config);
ctx.set_reminder("12").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/dca"
)
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 := dca.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
if err := c.SetReminder(context.Background(), "12"); 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 |
#### Pause DCA Plan
:::warning Not for Longbridge US Accounts
This method requires an AP data-center account (HK / SG). US data-center accounts will receive a region restriction error. AP accounts can call this method with any supported symbol, including US stocks.
:::
Temporarily pause a DCA plan. The plan can be resumed later.
longbridge dca pause 12345
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.dca._d_c_a_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.dca._d_c_a_context) |
| Rust | [longbridge:: ::dca#_d_c_a_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.dca.html#method._d_c_a_context) |
| Go | [dca.pause](https://pkg.go.dev/github.com/longbridge/openapi-go/ #dca.pause) |
| Node.js | [dca#DCAContext](https://longbridge.github.io/openapi/nodejs/classes/dca.html#dcacontext) |
| Java | [dca.getDCAContext](https://longbridge.github.io/openapi/java/com/longbridge/ /dca.html#getDCAContext) |
| C++ | [longbridge:: ::dca::_d_c_a_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_dca.html) |
## Parameters
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| plan_id | string | YES | DCA plan ID |
## Request Example
```python
from longbridge.openapi import DCAContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = DCAContext(config)
ctx.pause("12345")
```
```python
import asyncio
from longbridge.openapi import AsyncDCAContext, 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 = AsyncDCAContext.create(config)
await ctx.pause("12345")
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, DCAContext, 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 = DCAContext.new(config)
await ctx.pause('12345')
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.dca.*;
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);
DCAContext ctx = DCAContext.create(config)) {
ctx.pause("12345").get();
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, dca::DCAContext, 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 = DCAContext::new(config);
ctx.pause("12345").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/dca"
)
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 := dca.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
if err := c.Pause(context.Background(), "12345"); 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 |
#### Calculate DCA Date
:::warning Not for Longbridge US Accounts
This method requires an AP data-center account (HK / SG). US data-center accounts will receive a region restriction error. AP accounts can call this method with any supported symbol, including US stocks.
:::
Calculate the next projected trade date for given DCA plan parameters.
longbridge dca calc-date AAPL.US --frequency monthly --day-of-month 15
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.dca._d_c_a_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.dca._d_c_a_context) |
| Rust | [longbridge:: ::dca#_d_c_a_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.dca.html#method._d_c_a_context) |
| Go | [dca.calc_date](https://pkg.go.dev/github.com/longbridge/openapi-go/ #dca.calc_date) |
| Node.js | [dca#DCAContext](https://longbridge.github.io/openapi/nodejs/classes/dca.html#dcacontext) |
| Java | [dca.getDCAContext](https://longbridge.github.io/openapi/java/com/longbridge/ /dca.html#getDCAContext) |
| C++ | [longbridge:: ::dca::_d_c_a_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_dca.html) |
## Parameters
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol |
| frequency | string | YES | DCA frequency: `daily`, `weekly`, `fortnightly`, `monthly` |
| day_of_week | string | NO | Day of week for weekly plans: `mon`–`fri` |
| day_of_month | integer | NO | Day of month for monthly/fortnightly plans: 1–28 |
## Request Example
```python
from longbridge.openapi import DCAContext, Config, OAuthBuilder, DCAFrequency
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = DCAContext(config)
resp = ctx.calc_date("AAPL.US", DCAFrequency.Monthly, day_of_month=15)
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncDCAContext, Config, OAuthBuilder, DCAFrequency
async def main() -> None:
oauth = await OAuthBuilder("your-client-id").build_async(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AsyncDCAContext.create(config)
resp = await ctx.calc_date("AAPL.US", DCAFrequency.Monthly, day_of_month=15)
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, DCAContext, OAuth, DCAFrequency } = 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 = DCAContext.new(config)
const resp = await ctx.calcDate('AAPL.US', DCAFrequency.Monthly, undefined, 15)
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.dca.*;
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);
DCAContext ctx = DCAContext.create(config)) {
var opts = new CalcDateOptions("AAPL.US", DCAFrequency.MONTHLY).dayOfMonth(15);
var resp = ctx.calcDate(opts).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, dca::DCAContext, dca::DCAFrequency, 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 = DCAContext::new(config);
let resp = ctx.calc_date("AAPL.US", DCAFrequency::Monthly, None, Some(15)).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/dca"
)
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 := dca.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
dayOfMonth := 15
opts := &dca.CalcDateOptions{
Symbol: "AAPL.US",
Frequency: dca.FrequencyMonthly,
DayOfMonth: &dayOfMonth,
}
resp, err := c.CalcDate(context.Background(), opts)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"trade_date": "2024-02-15"
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [DcaCalcDateResult](#DcaCalcDateResult) |
| 400 | Bad request | None |
## Schemas
### DcaCalcDateResult
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| trade_date | string | true | Next projected trade date (YYYY-MM-DD) |
#### List DCA Plans
:::warning Not for Longbridge US Accounts
This method requires an AP data-center account (HK / SG). US data-center accounts will receive a region restriction error. AP accounts can call this method with any supported symbol, including US stocks.
:::
Get all recurring investment (DCA) plans for the current user.
longbridge dca
longbridge dca --status Active
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.dca._d_c_a_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.dca._d_c_a_context) |
| Rust | [longbridge:: ::dca#_d_c_a_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.dca.html#method._d_c_a_context) |
| Go | [dca.list](https://pkg.go.dev/github.com/longbridge/openapi-go/ #dca.list) |
| Node.js | [dca#DCAContext](https://longbridge.github.io/openapi/nodejs/classes/dca.html#dcacontext) |
| Java | [dca.getDCAContext](https://longbridge.github.io/openapi/java/com/longbridge/ /dca.html#getDCAContext) |
| C++ | [longbridge:: ::dca::_d_c_a_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_dca.html) |
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| status | string | NO | Filter by plan status: `Active`, `Suspended`, `Finished` |
| symbol | string | NO | Filter by security symbol |
## Request Example
```python
from longbridge.openapi import DCAContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = DCAContext(config)
resp = ctx.list_dca()
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncDCAContext, 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 = AsyncDCAContext.create(config)
resp = await ctx.list_dca()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, DCAContext, 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 = DCAContext.new(config)
const resp = await ctx.list_dca()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.dca.*;
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);
DCAContext ctx = DCAContext.create(config)) {
var resp = ctx.getListDca().get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, dca::DCAContext, 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 = DCAContext::new(config);
let resp = ctx.list_dca().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::dca;
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);
DCAContext ctx = DCAContext::create(config);
ctx.list_dca([](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/dca"
)
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 := dca.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.ListDca(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"plans": [
{
"plan_id": "1239402174908207104",
"symbol": "AAPL.US",
"stock_name": "Apple Inc.",
"market": "US",
"status": "Active",
"per_invest_amount": "100",
"invest_frequency": "Monthly",
"invest_day_of_month": "15",
"invest_day_of_week": "",
"next_trd_date": "1778853600",
"cum_amount": "0",
"cum_profit": "0",
"average_cost": "0",
"allow_margin_finance": false,
"alter_hours": "6",
"display_account": "LBPT10065023",
"member_id": "3162",
"aaid": "20975338",
"account_channel": "lb_papertrading",
"issue_number": 0,
"created_at": "1778725628",
"updated_at": "1778725628"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [DcaListResponse](#DcaListResponse) |
| 400 | Bad request | None |
## Schemas
### DcaListResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| plans | object[] | true | List of DCA plans, see [DcaPlan](#DcaPlan) |
### DcaPlan
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| plan_id | string | true | DCA plan ID |
| symbol | string | true | Security symbol |
| stock_name | string | false | Security name |
| market | string | false | Market |
| status | string | false | Plan status: `Active`, `Suspended`, `Finished` |
| per_invest_amount | string | false | Amount per investment |
| invest_frequency | string | false | Frequency: `Daily`, `Weekly`, `Fortnightly`, `Monthly` |
| invest_day_of_week | string | false | Day of week for weekly plans |
| invest_day_of_month | string | false | Day of month for monthly plans |
| next_trd_date | string | false | Next trade date |
| cum_amount | string | false | Cumulative invested amount |
| cum_profit | string | false | Cumulative profit/loss |
| average_cost | string | false | Average cost per share |
| allow_margin_finance | boolean | false | Whether margin financing is allowed |
| alter_hours | string | false | Reminder hours before trade |
| display_account | string | false | Account display name |
| account_channel | string | false | Account channel |
| aaid | string | false | Account asset ID |
| member_id | string | false | Member ID |
| issue_number | string | false | Execution count |
| created_at | string | false | Creation timestamp |
| updated_at | string | false | Last update timestamp |
#### DCA Trade History
:::warning Not for Longbridge US Accounts
This method requires an AP data-center account (HK / SG). US data-center accounts will receive a region restriction error. AP accounts can call this method with any supported symbol, including US stocks.
:::
Get the execution history for a specific DCA plan including trade dates, amounts, and prices.
longbridge dca history 1225781523156889600
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.dca._d_c_a_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.dca._d_c_a_context) |
| Rust | [longbridge:: ::dca#_d_c_a_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.dca.html#method._d_c_a_context) |
| Go | [dca.history](https://pkg.go.dev/github.com/longbridge/openapi-go/ #dca.history) |
| Node.js | [dca#DCAContext](https://longbridge.github.io/openapi/nodejs/classes/dca.html#dcacontext) |
| Java | [dca.getDCAContext](https://longbridge.github.io/openapi/java/com/longbridge/ /dca.html#getDCAContext) |
| C++ | [longbridge:: ::dca::_d_c_a_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_dca.html) |
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | string | YES | Plan ID (path parameter) |
| page | integer | NO | Page number (1-based, default: 1) |
| size | integer | NO | Records per page (default: 20) |
## Request Example
```python
from longbridge.openapi import DCAContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = DCAContext(config)
resp = ctx.dca_history("1225781523156889600")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncDCAContext, 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 = AsyncDCAContext.create(config)
resp = await ctx.dca_history("1225781523156889600")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, DCAContext, 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 = DCAContext.new(config)
const resp = await ctx.dca_history()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.dca.*;
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);
DCAContext ctx = DCAContext.create(config)) {
var resp = ctx.getDcaHistory().get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, dca::DCAContext, 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 = DCAContext::new(config);
let resp = ctx.dca_history().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::dca;
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);
DCAContext ctx = DCAContext::create(config);
ctx.dca_history([](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/dca"
)
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 := dca.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.DcaHistory(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"has_more": false,
"records": [
{
"symbol": "AAPL.US",
"order_id": "123456",
"status": "Filled",
"action": "Buy",
"order_type": "Market",
"executed_qty": "1",
"executed_price": "180.50",
"executed_amount": "180.50",
"created_at": "1763769600",
"rejected_reason": ""
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [DcaHistoryResponse](#DcaHistoryResponse) |
| 400 | Bad request | None |
## Schemas
### DcaHistoryResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| records | object[] | true | List of execution records |
| ∟ symbol | string | true | Security symbol |
| ∟ order_id | string | false | Associated order ID |
| ∟ status | string | false | Execution status |
| ∟ action | string | false | Action type (e.g. `buy`) |
| ∟ order_type | string | false | Order type (e.g. `market`) |
| ∟ executed_qty | string | false | Executed quantity |
| ∟ executed_price | string | false | Executed price |
| ∟ executed_amount | string | false | Executed cost amount |
| ∟ rejected_reason | string | false | Rejection reason if failed |
| ∟ created_at | string | false | Creation Unix timestamp |
| ∟ created_at | string | false | Execution time |
| ∟ rejected_reason | string | false | Rejection reason (if any) |
| has_more | boolean | false | Whether more records exist |
#### Update DCA Plan
:::warning Not for Longbridge US Accounts
This method requires an AP data-center account (HK / SG). US data-center accounts will receive a region restriction error. AP accounts can call this method with any supported symbol, including US stocks.
:::
Pause or resume an existing recurring investment plan.
longbridge dca pause 1225781523156889600
longbridge dca resume 1225781523156889600
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.dca._d_c_a_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.dca._d_c_a_context) |
| Rust | [longbridge:: ::dca#_d_c_a_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.dca.html#method._d_c_a_context) |
| Go | [dca.update](https://pkg.go.dev/github.com/longbridge/openapi-go/ #dca.update) |
| Node.js | [dca#DCAContext](https://longbridge.github.io/openapi/nodejs/classes/dca.html#dcacontext) |
| Java | [dca.getDCAContext](https://longbridge.github.io/openapi/java/com/longbridge/ /dca.html#getDCAContext) |
| C++ | [longbridge:: ::dca::_d_c_a_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_dca.html) |
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | string | YES | Plan ID (path parameter) |
| action | string | YES | Action to perform: `pause` or `resume` |
## Request Example
```python
from longbridge.openapi import DCAContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = DCAContext(config)
resp = ctx.update_dca("1225781523156889600", action="pause")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncDCAContext, 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 = AsyncDCAContext.create(config)
resp = await ctx.update_dca("1225781523156889600", action="pause")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, DCAContext, 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 = DCAContext.new(config)
const resp = await ctx.update_dca()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.dca.*;
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);
DCAContext ctx = DCAContext.create(config)) {
var resp = ctx.getUpdateDca().get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, dca::DCAContext, 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 = DCAContext::new(config);
let resp = ctx.update_dca().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::dca;
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);
DCAContext ctx = DCAContext::create(config);
ctx.update_dca([](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/dca"
)
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 := dca.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.UpdateDca(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 | [UpdateDcaResponse](#UpdateDcaResponse) |
| 400 | Bad request | None |
## Schemas
### UpdateDcaResponse
No response body fields.
#### Check DCA Support
:::warning Not for Longbridge US Accounts
This method requires an AP data-center account (HK / SG). US data-center accounts will receive a region restriction error. AP accounts can call this method with any supported symbol, including US stocks.
:::
Check whether the given securities support DCA recurring investment.
longbridge dca check AAPL.US 700.HK
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.dca._d_c_a_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.dca._d_c_a_context) |
| Rust | [longbridge:: ::dca#_d_c_a_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.dca.html#method._d_c_a_context) |
| Go | [dca.check_support](https://pkg.go.dev/github.com/longbridge/openapi-go/ #dca.check_support) |
| Node.js | [dca#DCAContext](https://longbridge.github.io/openapi/nodejs/classes/dca.html#dcacontext) |
| Java | [dca.getDCAContext](https://longbridge.github.io/openapi/java/com/longbridge/ /dca.html#getDCAContext) |
| C++ | [longbridge:: ::dca::_d_c_a_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_dca.html) |
## Parameters
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbols | string[] | YES | List of security symbols to check |
## Request Example
```python
from longbridge.openapi import DCAContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = DCAContext(config)
resp = ctx.check_support(["AAPL.US", "700.HK"])
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncDCAContext, 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 = AsyncDCAContext.create(config)
resp = await ctx.check_support(["AAPL.US", "700.HK"])
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, DCAContext, 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 = DCAContext.new(config)
const resp = await ctx.checkSupport(['AAPL.US', '700.HK'])
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.dca.*;
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);
DCAContext ctx = DCAContext.create(config)) {
var resp = ctx.checkSupport(Arrays.asList("AAPL.US", "700.HK")).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, dca::DCAContext, 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 = DCAContext::new(config);
let resp = ctx.check_support(vec!["AAPL.US".into(), "700.HK".into()]).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/dca"
)
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 := dca.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.CheckSupport(context.Background(), []string{"AAPL.US", "700.HK"})
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"infos": [
{
"symbol": "AAPL.US",
"support_regular_saving": true
},
{
"symbol": "700.HK",
"support_regular_saving": false
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [DcaSupportListResponse](#DcaSupportListResponse) |
| 400 | Bad request | None |
## Schemas
### DcaSupportListResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| infos | object[] | true | List of DCA support results |
| ∟ symbol | string | true | Security symbol |
| ∟ support_regular_saving | boolean | true | Whether DCA is supported |
#### Resume DCA Plan
:::warning Not for Longbridge US Accounts
This method requires an AP data-center account (HK / SG). US data-center accounts will receive a region restriction error. AP accounts can call this method with any supported symbol, including US stocks.
:::
Resume a previously paused DCA plan.
longbridge dca resume 12345
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.dca._d_c_a_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.dca._d_c_a_context) |
| Rust | [longbridge:: ::dca#_d_c_a_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.dca.html#method._d_c_a_context) |
| Go | [dca.resume](https://pkg.go.dev/github.com/longbridge/openapi-go/ #dca.resume) |
| Node.js | [dca#DCAContext](https://longbridge.github.io/openapi/nodejs/classes/dca.html#dcacontext) |
| Java | [dca.getDCAContext](https://longbridge.github.io/openapi/java/com/longbridge/ /dca.html#getDCAContext) |
| C++ | [longbridge:: ::dca::_d_c_a_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_dca.html) |
## Parameters
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| plan_id | string | YES | DCA plan ID |
## Request Example
```python
from longbridge.openapi import DCAContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = DCAContext(config)
ctx.resume("12345")
```
```python
import asyncio
from longbridge.openapi import AsyncDCAContext, 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 = AsyncDCAContext.create(config)
await ctx.resume("12345")
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, DCAContext, 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 = DCAContext.new(config)
await ctx.resume('12345')
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.dca.*;
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);
DCAContext ctx = DCAContext.create(config)) {
ctx.resume("12345").get();
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, dca::DCAContext, 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 = DCAContext::new(config);
ctx.resume("12345").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/dca"
)
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 := dca.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
if err := c.Resume(context.Background(), "12345"); 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 |
#### DCA Statistics
:::warning Not for Longbridge US Accounts
This method requires an AP data-center account (HK / SG). US data-center accounts will receive a region restriction error. AP accounts can call this method with any supported symbol, including US stocks.
:::
Get DCA statistics summary including total invested amount and profit/loss.
longbridge dca stats
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.dca._d_c_a_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.dca._d_c_a_context) |
| Rust | [longbridge:: ::dca#_d_c_a_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.dca.html#method._d_c_a_context) |
| Go | [dca.stats](https://pkg.go.dev/github.com/longbridge/openapi-go/ #dca.stats) |
| Node.js | [dca#DCAContext](https://longbridge.github.io/openapi/nodejs/classes/dca.html#dcacontext) |
| Java | [dca.getDCAContext](https://longbridge.github.io/openapi/java/com/longbridge/ /dca.html#getDCAContext) |
| C++ | [longbridge:: ::dca::_d_c_a_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_dca.html) |
## Parameters
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | NO | Filter by symbol |
## Request Example
```python
from longbridge.openapi import DCAContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = DCAContext(config)
resp = ctx.stats()
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncDCAContext, 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 = AsyncDCAContext.create(config)
resp = await ctx.stats()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, DCAContext, 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 = DCAContext.new(config)
const resp = await ctx.stats()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.dca.*;
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);
DCAContext ctx = DCAContext.create(config)) {
var resp = ctx.stats(null).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, dca::DCAContext, 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 = DCAContext::new(config);
let resp = ctx.stats(None).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/dca"
)
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 := dca.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.Stats(context.Background(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"active_count": "2",
"finished_count": "1",
"suspended_count": "0",
"rest_days": "3",
"total_amount": "5400",
"total_profit": "120.50",
"nearest_plans": [
{
"plan_id": "1239402174908207104",
"symbol": "AAPL.US",
"stock_name": "Apple Inc.",
"market": "US",
"status": "Active",
"per_invest_amount": "100",
"invest_frequency": "Monthly",
"invest_day_of_month": "15",
"next_trd_date": "1778853600",
"cum_amount": "0",
"cum_profit": "0"
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [DcaStats](#DcaStats) |
| 400 | Bad request | None |
## Schemas
### DcaStatsResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| active_count | string | false | Number of active plans |
| finished_count | string | false | Number of finished plans |
| suspended_count | string | false | Number of suspended plans |
| rest_days | string | false | Days until next investment |
| total_amount | string | false | Total invested amount |
| total_profit | string | false | Total profit/loss |
| nearest_plans | object[] | false | Nearest upcoming DCA plans (same structure as DcaPlan) |
> `nearest_plans` items use the same `DcaPlan` structure as [List DCA Plans](./list-dca).
#### Alert
#### Create Alert
Create a new price alert for a security when it rises above or falls below a target price.
longbridge alert add TSLA.US --price 300 --direction rise
longbridge alert add AAPL.US --price 150 --direction fall
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.alert._alert_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.alert._alert_context) |
| Rust | [longbridge:: ::alert#_alert_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.alert.html#method._alert_context) |
| Go | [alert.create_alert](https://pkg.go.dev/github.com/longbridge/openapi-go/ #alert.create_alert) |
| Node.js | [alert#AlertContext](https://longbridge.github.io/openapi/nodejs/classes/alert.html#alertcontext) |
| Java | [alert.getAlertContext](https://longbridge.github.io/openapi/java/com/longbridge/ /alert.html#getAlertContext) |
| C++ | [longbridge:: ::alert::_alert_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_alert.html) |
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | YES | Security symbol, e.g. `TSLA.US` |
| price | string | YES | Target price |
| direction | string | YES | Alert direction: `rise` or `fall` |
| frequency | string | NO | Trigger frequency: `once` (default) or `every` |
## Request Example
```python
from longbridge.openapi import AlertContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AlertContext(config)
resp = ctx.create_alert()
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncAlertContext, 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 = AsyncAlertContext.create(config)
resp = await ctx.create_alert()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, AlertContext, 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 = AlertContext.new(config)
const resp = await ctx.create_alert()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.alert.*;
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);
AlertContext ctx = AlertContext.create(config)) {
var resp = ctx.getCreateAlert().get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, alert::AlertContext, 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 = AlertContext::new(config);
let resp = ctx.create_alert().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::alert;
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);
AlertContext ctx = AlertContext::create(config);
ctx.create_alert([](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/alert"
)
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 := alert.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.CreateAlert(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"id": 486469
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [CreateAlertResponse](#CreateAlertResponse) |
| 400 | Bad request | None |
## Schemas
### CreateAlertResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | int64 | true | ID of the newly created alert |
#### Update Alert
Enable or disable an existing price alert. First call `list` to obtain the full `AlertItem`, set `item.enabled` to `True` or `False`, then call `update(item)`.
# Enable an alert
longbridge alert enable 486469
# Disable an alert
longbridge alert disable 486469
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.alert._alert_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.alert._alert_context) |
| Rust | [longbridge:: ::alert#_alert_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.alert.html#method._alert_context) |
| Go | [alert.enable](https://pkg.go.dev/github.com/longbridge/openapi-go/ #alert.enable) |
| Node.js | [alert#AlertContext](https://longbridge.github.io/openapi/nodejs/classes/alert.html#alertcontext) |
| Java | [alert.getAlertContext](https://longbridge.github.io/openapi/java/com/longbridge/ /alert.html#getAlertContext) |
| C++ | [longbridge:: ::alert::_alert_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_alert.html) |
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | int64 | YES | Alert ID (path parameter) |
| enabled | bool | YES | New enabled state: `true` to enable, `false` to disable — set on the `AlertItem` before calling `update` |
## Request Example
```python
from longbridge.openapi import AlertContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AlertContext(config)
# Get the alert from list()
alerts = ctx.list()
item = alerts.lists[0].indicators[0] # pick the alert you want
# Enable: set enabled=True then call update
item.enabled = True
ctx.update(item)
# Disable: set enabled=False then call update
item.enabled = False
ctx.update(item)
```
```python
import asyncio
from longbridge.openapi import AsyncAlertContext, 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 = AsyncAlertContext.create(config)
alerts = await ctx.list()
item = alerts.lists[0].indicators[0]
item.enabled = True # or False to disable
await ctx.update(item)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, AlertContext, 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 = AlertContext.new(config)
const alerts = await ctx.list()
const item = alerts.lists[0].indicators[0]
item.enabled = true // or false to disable
await ctx.update(item)
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.alert.*;
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);
AlertContext ctx = AlertContext.create(config)) {
var alerts = ctx.list().get();
var item = alerts.getLists().get(0).getIndicators().get(0);
item.setEnabled(true); // or false to disable
ctx.update(item).get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, alert::AlertContext, 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 = AlertContext::new(config);
let mut item = ctx.list().await?.lists.remove(0).indicators.remove(0);
item.enabled = true; // or false to disable
ctx.update(&item).await?;
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::alert;
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);
AlertContext ctx = AlertContext::create(config);
ctx.list([&ctx](auto list_resp) {
auto& item = (*list_resp).lists[0].indicators[0];
ctx.enable(item, [](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/alert"
)
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 := alert.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
list, err := c.List(context.Background())
if err != nil { log.Fatal(err) }
item := list.Lists[0].Indicators[0]
item.Enabled = true // or false to disable
if err = c.Update(context.Background(), &item); err != nil {
log.Fatal(err)
}
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 | [UpdateAlertResponse](#UpdateAlertResponse) |
| 400 | Bad request | None |
## Schemas
### UpdateAlertResponse
No response body fields.
#### List Alerts
Get all price alerts for the current user, with optional filtering by symbol.
longbridge alert
longbridge alert TSLA.US
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.alert._alert_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.alert._alert_context) |
| Rust | [longbridge:: ::alert#_alert_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.alert.html#method._alert_context) |
| Go | [alert.list_alerts](https://pkg.go.dev/github.com/longbridge/openapi-go/ #alert.list_alerts) |
| Node.js | [alert#AlertContext](https://longbridge.github.io/openapi/nodejs/classes/alert.html#alertcontext) |
| Java | [alert.getAlertContext](https://longbridge.github.io/openapi/java/com/longbridge/ /alert.html#getAlertContext) |
| C++ | [longbridge:: ::alert::_alert_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_alert.html) |
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | NO | Filter by security symbol, e.g. `TSLA.US` |
## Request Example
```python
from longbridge.openapi import AlertContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AlertContext(config)
resp = ctx.list_alerts()
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncAlertContext, 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 = AsyncAlertContext.create(config)
resp = await ctx.list_alerts()
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, AlertContext, 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 = AlertContext.new(config)
const resp = await ctx.list_alerts()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.alert.*;
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);
AlertContext ctx = AlertContext.create(config)) {
var resp = ctx.getListAlerts().get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, alert::AlertContext, 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 = AlertContext::new(config);
let resp = ctx.list_alerts().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::alert;
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);
AlertContext ctx = AlertContext::create(config);
ctx.list_alerts([](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/alert"
)
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 := alert.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.ListAlerts(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v\n", resp)
}
```
## Response
### Response Example
```json
{
"code": 0,
"message": "success",
"data": {
"lists": [
{
"symbol": "AAPL.US",
"code": "AAPL",
"market": "US",
"name": "Apple",
"price": "298.87",
"chg": "4.07",
"p_chg": "1.38",
"product": "stock",
"indicators": [
{
"id": "514050",
"indicator_id": "1",
"enabled": true,
"frequency": 2,
"scope": 0,
"text": "价格涨到 400",
"state": [
1
],
"value_map": {
"price": "400"
}
}
]
}
]
}
}
```
### Response Status
| Status | Description | Schema |
| ------ | ----------- | ------ |
| 200 | Success | [AlertListResponse](#AlertListResponse) |
| 400 | Bad request | None |
## Schemas
### AlertListResponse
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| lists | object[] | true | Alert groups per security, see [AlertSymbolGroup](#AlertSymbolGroup) |
### AlertSymbolGroup
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| symbol | string | true | Security symbol |
| code | string | false | Ticker code |
| market | string | false | Market |
| name | string | false | Security name |
| price | string | false | Latest price |
| chg | string | false | Day change amount |
| p_chg | string | false | Day change percentage |
| product | string | false | Product type |
| indicators | object[] | false | Alert indicators, see [AlertItem](#AlertItem) |
### AlertItem
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | string | true | Alert ID |
| indicator_id | string | false | Condition: `1`=price_rise, `2`=price_fall, `3`=pct_rise, `4`=pct_fall |
| enabled | boolean | false | Whether the alert is active |
| frequency | integer | false | Frequency: `1`=daily, `2`=every_time, `3`=once |
| scope | integer | false | Scope |
| text | string | false | Display text |
| state | integer[] | false | Trigger state flags |
| value_map | object | false | Trigger value (e.g. `{"price":"400"}` or `{"chg":"5"}`) |
#### Delete Alert
Delete a price alert by its ID.
longbridge alert delete 486469
longbridge alert delete 112326
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.alert._alert_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.alert._alert_context) |
| Rust | [longbridge:: ::alert#_alert_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.alert.html#method._alert_context) |
| Go | [alert.delete_alert](https://pkg.go.dev/github.com/longbridge/openapi-go/ #alert.delete_alert) |
| Node.js | [alert#AlertContext](https://longbridge.github.io/openapi/nodejs/classes/alert.html#alertcontext) |
| Java | [alert.getAlertContext](https://longbridge.github.io/openapi/java/com/longbridge/ /alert.html#getAlertContext) |
| C++ | [longbridge:: ::alert::_alert_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_alert.html) |
## Parameters
> **SDK method parameters.**
| Name | Type | Required | Description |
| ---- | ---- | -------- | ----------- |
| id | int64 | YES | Alert ID (path parameter) |
## Request Example
```python
from longbridge.openapi import AlertContext, Config, OAuthBuilder
oauth = OAuthBuilder("your-client-id").build(lambda url: print("Visit:", url))
config = Config.from_oauth(oauth)
ctx = AlertContext(config)
resp = ctx.delete_alert("486469")
print(resp)
```
```python
import asyncio
from longbridge.openapi import AsyncAlertContext, 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 = AsyncAlertContext.create(config)
resp = await ctx.delete_alert("486469")
print(resp)
if __name__ == "__main__":
asyncio.run(main())
```
```javascript
const { Config, AlertContext, 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 = AlertContext.new(config)
const resp = await ctx.delete_alert()
console.log(resp)
}
main().catch(console.error)
```
```java
import com.longbridge.*;
import com.longbridge.alert.*;
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);
AlertContext ctx = AlertContext.create(config)) {
var resp = ctx.getDeleteAlert().get();
System.out.println(resp);
}
}
}
```
```rust
use std::sync::Arc;
use longbridge::{oauth::OAuthBuilder, alert::AlertContext, 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 = AlertContext::new(config);
let resp = ctx.delete_alert().await?;
println!("{:?}", resp);
Ok(())
}
```
```cpp
#include
#include
using namespace longbridge;
using namespace longbridge::alert;
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);
AlertContext ctx = AlertContext::create(config);
ctx.delete_alert([](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/alert"
)
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 := alert.NewFromCfg(conf)
if err != nil {
log.Fatal(err)
}
defer c.Close()
resp, err := c.DeleteAlert(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 | [DeleteAlertResponse](#DeleteAlertResponse) |
| 400 | Bad request | None |
## Schemas
### DeleteAlertResponse
No response body fields.
### Content
### Overview
# 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 detail 123
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.sharelist._sharelist_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.sharelist._sharelist_context) |
| Rust | [longbridge:: ::sharelist#_sharelist_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.sharelist.html#method._sharelist_context) |
| Go | [sharelist.detail](https://pkg.go.dev/github.com/longbridge/openapi-go/ #sharelist.detail) |
| Node.js | [sharelist#SharelistContext](https://longbridge.github.io/openapi/nodejs/classes/sharelist.html#sharelistcontext) |
| Java | [sharelist.getSharelistContext](https://longbridge.github.io/openapi/java/com/longbridge/ /sharelist.html#getSharelistContext) |
| C++ | [longbridge:: ::sharelist::_sharelist_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_sharelist.html) |
## 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
Reorder the securities in a sharelist. The symbols list defines the new order.
longbridge sharelist sort 123 TSLA.US AAPL.US 700.HK
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.sharelist._sharelist_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.sharelist._sharelist_context) |
| Rust | [longbridge:: ::sharelist#_sharelist_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.sharelist.html#method._sharelist_context) |
| Go | [sharelist.sort_securities](https://pkg.go.dev/github.com/longbridge/openapi-go/ #sharelist.sort_securities) |
| Node.js | [sharelist#SharelistContext](https://longbridge.github.io/openapi/nodejs/classes/sharelist.html#sharelistcontext) |
| Java | [sharelist.getSharelistContext](https://longbridge.github.io/openapi/java/com/longbridge/ /sharelist.html#getSharelistContext) |
| C++ | [longbridge:: ::sharelist::_sharelist_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_sharelist.html) |
## 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 |
#### Delete Sharelist
Permanently delete a sharelist you own. This action cannot be undone.
longbridge sharelist delete 15921
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.sharelist._sharelist_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.sharelist._sharelist_context) |
| Rust | [longbridge:: ::sharelist#_sharelist_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.sharelist.html#method._sharelist_context) |
| Go | [sharelist.delete_sharelist](https://pkg.go.dev/github.com/longbridge/openapi-go/ #sharelist.delete_sharelist) |
| Node.js | [sharelist#SharelistContext](https://longbridge.github.io/openapi/nodejs/classes/sharelist.html#sharelistcontext) |
| Java | [sharelist.getSharelistContext](https://longbridge.github.io/openapi/java/com/longbridge/ /sharelist.html#getSharelistContext) |
| C++ | [longbridge:: ::sharelist::_sharelist_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_sharelist.html) |
## 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
Get all community stock lists (sharelists) created by or subscribed to by the current user.
longbridge sharelist
longbridge sharelist --format json
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.sharelist._sharelist_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.sharelist._sharelist_context) |
| Rust | [longbridge:: ::sharelist#_sharelist_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.sharelist.html#method._sharelist_context) |
| Go | [sharelist.list_sharelist](https://pkg.go.dev/github.com/longbridge/openapi-go/ #sharelist.list_sharelist) |
| Node.js | [sharelist#SharelistContext](https://longbridge.github.io/openapi/nodejs/classes/sharelist.html#sharelistcontext) |
| Java | [sharelist.getSharelistContext](https://longbridge.github.io/openapi/java/com/longbridge/ /sharelist.html#getSharelistContext) |
| C++ | [longbridge:: ::sharelist::_sharelist_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_sharelist.html) |
## 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 |
#### Create Sharelist
Create a new community stock list with an optional initial set of securities.
longbridge sharelist create --name "AI Picks" --description "Top AI infrastructure stocks"
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.sharelist._sharelist_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.sharelist._sharelist_context) |
| Rust | [longbridge:: ::sharelist#_sharelist_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.sharelist.html#method._sharelist_context) |
| Go | [sharelist.create_sharelist](https://pkg.go.dev/github.com/longbridge/openapi-go/ #sharelist.create_sharelist) |
| Node.js | [sharelist#SharelistContext](https://longbridge.github.io/openapi/nodejs/classes/sharelist.html#sharelistcontext) |
| Java | [sharelist.getSharelistContext](https://longbridge.github.io/openapi/java/com/longbridge/ /sharelist.html#getSharelistContext) |
| C++ | [longbridge:: ::sharelist::_sharelist_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_sharelist.html) |
## 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 |
#### Add Securities to Sharelist
Add one or more securities to a sharelist.
longbridge sharelist add 123 TSLA.US AAPL.US
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.sharelist._sharelist_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.sharelist._sharelist_context) |
| Rust | [longbridge:: ::sharelist#_sharelist_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.sharelist.html#method._sharelist_context) |
| Go | [sharelist.add_securities](https://pkg.go.dev/github.com/longbridge/openapi-go/ #sharelist.add_securities) |
| Node.js | [sharelist#SharelistContext](https://longbridge.github.io/openapi/nodejs/classes/sharelist.html#sharelistcontext) |
| Java | [sharelist.getSharelistContext](https://longbridge.github.io/openapi/java/com/longbridge/ /sharelist.html#getSharelistContext) |
| C++ | [longbridge:: ::sharelist::_sharelist_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_sharelist.html) |
## 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 |
#### Remove Securities from Sharelist
Remove one or more securities from a sharelist.
longbridge sharelist remove 123 TSLA.US
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.sharelist._sharelist_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.sharelist._sharelist_context) |
| Rust | [longbridge:: ::sharelist#_sharelist_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.sharelist.html#method._sharelist_context) |
| Go | [sharelist.remove_securities](https://pkg.go.dev/github.com/longbridge/openapi-go/ #sharelist.remove_securities) |
| Node.js | [sharelist#SharelistContext](https://longbridge.github.io/openapi/nodejs/classes/sharelist.html#sharelistcontext) |
| Java | [sharelist.getSharelistContext](https://longbridge.github.io/openapi/java/com/longbridge/ /sharelist.html#getSharelistContext) |
| C++ | [longbridge:: ::sharelist::_sharelist_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_sharelist.html) |
## 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 |
#### Popular Sharelists
Get popular/trending sharelists from the community.
longbridge sharelist popular --count 10
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.sharelist._sharelist_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.sharelist._sharelist_context) |
| Rust | [longbridge:: ::sharelist#_sharelist_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.sharelist.html#method._sharelist_context) |
| Go | [sharelist.popular](https://pkg.go.dev/github.com/longbridge/openapi-go/ #sharelist.popular) |
| Node.js | [sharelist#SharelistContext](https://longbridge.github.io/openapi/nodejs/classes/sharelist.html#sharelistcontext) |
| Java | [sharelist.getSharelistContext](https://longbridge.github.io/openapi/java/com/longbridge/ /sharelist.html#getSharelistContext) |
| C++ | [longbridge:: ::sharelist::_sharelist_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_sharelist.html) |
## 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 |
#### Update Sharelist
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
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.sharelist._sharelist_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.sharelist._sharelist_context) |
| Rust | [longbridge:: ::sharelist#_sharelist_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.sharelist.html#method._sharelist_context) |
| Go | [sharelist.update_sharelist](https://pkg.go.dev/github.com/longbridge/openapi-go/ #sharelist.update_sharelist) |
| Node.js | [sharelist#SharelistContext](https://longbridge.github.io/openapi/nodejs/classes/sharelist.html#sharelistcontext) |
| Java | [sharelist.getSharelistContext](https://longbridge.github.io/openapi/java/com/longbridge/ /sharelist.html#getSharelistContext) |
| C++ | [longbridge:: ::sharelist::_sharelist_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_sharelist.html) |
## 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.
#### Topics
#### Topic Detail
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
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.content._content_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.content._content_context) |
| Rust | [longbridge:: ::content#_content_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.content.html#method._content_context) |
| Go | [content.topic_detail](https://pkg.go.dev/github.com/longbridge/openapi-go/ #content.topic_detail) |
| Node.js | [content#ContentContext](https://longbridge.github.io/openapi/nodejs/classes/content.html#contentcontext) |
| Java | [content.getContentContext](https://longbridge.github.io/openapi/java/com/longbridge/ /content.html#getContentContext) |
| C++ | [longbridge:: ::content::_content_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_content.html) |
## 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) |
#### My Topics
Get the list of topics I have published. View them on [Topics](https://longbridge.com/topics).
longbridge topic mine
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.content._content_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.content._content_context) |
| Rust | [longbridge:: ::content#_content_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.content.html#method._content_context) |
| Go | [content.topics_mine](https://pkg.go.dev/github.com/longbridge/openapi-go/ #content.topics_mine) |
| Node.js | [content#ContentContext](https://longbridge.github.io/openapi/nodejs/classes/content.html#contentcontext) |
| Java | [content.getContentContext](https://longbridge.github.io/openapi/java/com/longbridge/ /content.html#getContentContext) |
| C++ | [longbridge:: ::content::_content_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_content.html) |
## 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 Replies
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
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.content._content_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.content._content_context) |
| Rust | [longbridge:: ::content#_content_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.content.html#method._content_context) |
| Go | [content.list_topic_replies](https://pkg.go.dev/github.com/longbridge/openapi-go/ #content.list_topic_replies) |
| Node.js | [content#ContentContext](https://longbridge.github.io/openapi/nodejs/classes/content.html#contentcontext) |
| Java | [content.getContentContext](https://longbridge.github.io/openapi/java/com/longbridge/ /content.html#getContentContext) |
| C++ | [longbridge:: ::content::_content_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_content.html) |
## 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) |
#### Create Topic
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
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.content._content_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.content._content_context) |
| Rust | [longbridge:: ::content#_content_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.content.html#method._content_context) |
| Go | [content.create_topic](https://pkg.go.dev/github.com/longbridge/openapi-go/ #content.create_topic) |
| Node.js | [content#ContentContext](https://longbridge.github.io/openapi/nodejs/classes/content.html#contentcontext) |
| Java | [content.getContentContext](https://longbridge.github.io/openapi/java/com/longbridge/ /content.html#getContentContext) |
| C++ | [longbridge:: ::content::_content_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_content.html) |
## 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 |
#### Topics by Symbol
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
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.content._content_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.content._content_context) |
| Rust | [longbridge:: ::content#_content_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.content.html#method._content_context) |
| Go | [content.topics](https://pkg.go.dev/github.com/longbridge/openapi-go/ #content.topics) |
| Node.js | [content#ContentContext](https://longbridge.github.io/openapi/nodejs/classes/content.html#contentcontext) |
| Java | [content.getContentContext](https://longbridge.github.io/openapi/java/com/longbridge/ /content.html#getContentContext) |
| C++ | [longbridge:: ::content::_content_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_content.html) |
## 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 |
#### Create Topic Reply
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!"
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.content._content_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.content._content_context) |
| Rust | [longbridge:: ::content#_content_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.content.html#method._content_context) |
| Go | [content.create_topic_reply](https://pkg.go.dev/github.com/longbridge/openapi-go/ #content.create_topic_reply) |
| Node.js | [content#ContentContext](https://longbridge.github.io/openapi/nodejs/classes/content.html#contentcontext) |
| Java | [content.getContentContext](https://longbridge.github.io/openapi/java/com/longbridge/ /content.html#getContentContext) |
| C++ | [longbridge:: ::content::_content_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_content.html) |
## 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) |
#### News
#### Security News
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
## SDK
| Language | Link |
|---|---|
| Python | [longbridge.openapi.content._content_context](https://longbridge.github.io/openapi/python/reference_all/#longbridge.openapi.content._content_context) |
| Rust | [longbridge:: ::content#_content_context](https://longbridge.github.io/openapi/rust/longbridge/ /struct.content.html#method._content_context) |
| Go | [content.news](https://pkg.go.dev/github.com/longbridge/openapi-go/ #content.news) |
| Node.js | [content#ContentContext](https://longbridge.github.io/openapi/nodejs/classes/content.html#contentcontext) |
| Java | [content.getContentContext](https://longbridge.github.io/openapi/java/com/longbridge/ /content.html#getContentContext) |
| C++ | [longbridge:: ::content::_content_context](https://longbridge.github.io/openapi/cpp/classlongbridge_1_1 _1_1_content.html) |
## 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 |